From 0c24077c43549c7c0cf462051e947a93bb468568 Mon Sep 17 00:00:00 2001 From: Guenter Obiltschnig Date: Mon, 23 Oct 2006 16:25:09 +0000 Subject: [PATCH] set eol-style to native --- Net/Makefile | 74 +- Net/Net.vmsbuild | 14 +- Net/Net_vs71.sln | 60 +- Net/Net_vs71.vcproj | 1562 ++++++------- Net/Net_vs80.sln | 56 +- Net/Net_vs80.vcproj | 2014 ++++++++--------- Net/include/Poco/Net/DNS.h | 280 +-- Net/include/Poco/Net/DatagramSocket.h | 338 +-- Net/include/Poco/Net/DatagramSocketImpl.h | 162 +- Net/include/Poco/Net/DialogSocket.h | 420 ++-- Net/include/Poco/Net/FTPClientSession.h | 764 +++---- Net/include/Poco/Net/FTPStreamFactory.h | 276 +-- Net/include/Poco/Net/FilePartSource.h | 176 +- Net/include/Poco/Net/HTMLForm.h | 424 ++-- Net/include/Poco/Net/HTTPBasicCredentials.h | 238 +- Net/include/Poco/Net/HTTPBasicStreamBuf.h | 116 +- Net/include/Poco/Net/HTTPBufferAllocator.h | 144 +- Net/include/Poco/Net/HTTPChunkedStream.h | 250 +- Net/include/Poco/Net/HTTPClientSession.h | 526 ++--- Net/include/Poco/Net/HTTPCookie.h | 460 ++-- Net/include/Poco/Net/HTTPFixedLengthStream.h | 250 +- Net/include/Poco/Net/HTTPHeaderStream.h | 246 +- Net/include/Poco/Net/HTTPIOStream.h | 220 +- Net/include/Poco/Net/HTTPMessage.h | 354 +-- Net/include/Poco/Net/HTTPRequest.h | 352 +-- Net/include/Poco/Net/HTTPRequestHandler.h | 178 +- .../Poco/Net/HTTPRequestHandlerFactory.h | 160 +- Net/include/Poco/Net/HTTPResponse.h | 536 ++--- Net/include/Poco/Net/HTTPServer.h | 212 +- Net/include/Poco/Net/HTTPServerConnection.h | 156 +- .../Poco/Net/HTTPServerConnectionFactory.h | 158 +- Net/include/Poco/Net/HTTPServerParams.h | 348 +-- Net/include/Poco/Net/HTTPServerRequest.h | 264 +-- Net/include/Poco/Net/HTTPServerResponse.h | 244 +- Net/include/Poco/Net/HTTPServerSession.h | 174 +- Net/include/Poco/Net/HTTPSession.h | 428 ++-- Net/include/Poco/Net/HTTPSessionFactory.h | 308 +-- .../Poco/Net/HTTPSessionInstantiator.h | 232 +- Net/include/Poco/Net/HTTPStream.h | 248 +- Net/include/Poco/Net/HTTPStreamFactory.h | 202 +- Net/include/Poco/Net/HostEntry.h | 266 +-- Net/include/Poco/Net/ICMPClient.h | 214 +- Net/include/Poco/Net/ICMPEventArgs.h | 376 +-- Net/include/Poco/Net/ICMPPacket.h | 222 +- Net/include/Poco/Net/ICMPPacketImpl.h | 326 +-- Net/include/Poco/Net/ICMPSocket.h | 278 +-- Net/include/Poco/Net/ICMPSocketImpl.h | 168 +- Net/include/Poco/Net/ICMPv4PacketImpl.h | 372 +-- Net/include/Poco/Net/IPAddress.h | 688 +++--- Net/include/Poco/Net/MailMessage.h | 508 ++--- Net/include/Poco/Net/MailRecipient.h | 284 +-- Net/include/Poco/Net/MailStream.h | 336 +-- Net/include/Poco/Net/MediaType.h | 340 +-- Net/include/Poco/Net/MessageHeader.h | 314 +-- Net/include/Poco/Net/MulticastSocket.h | 276 +-- Net/include/Poco/Net/MultipartReader.h | 364 +-- Net/include/Poco/Net/MultipartWriter.h | 260 +-- Net/include/Poco/Net/NameValueCollection.h | 310 +-- Net/include/Poco/Net/Net.h | 140 +- Net/include/Poco/Net/NetException.h | 150 +- Net/include/Poco/Net/NetworkInterface.h | 370 +-- Net/include/Poco/Net/NullPartHandler.h | 138 +- Net/include/Poco/Net/POP3ClientSession.h | 414 ++-- Net/include/Poco/Net/PartHandler.h | 180 +- Net/include/Poco/Net/PartSource.h | 206 +- Net/include/Poco/Net/QuotedPrintableDecoder.h | 192 +- Net/include/Poco/Net/QuotedPrintableEncoder.h | 214 +- Net/include/Poco/Net/RawSocket.h | 338 +-- Net/include/Poco/Net/RawSocketImpl.h | 156 +- Net/include/Poco/Net/SMTPClientSession.h | 358 +-- Net/include/Poco/Net/ServerSocket.h | 312 +-- Net/include/Poco/Net/ServerSocketImpl.h | 134 +- Net/include/Poco/Net/Socket.h | 1178 +++++----- Net/include/Poco/Net/SocketAcceptor.h | 368 +-- Net/include/Poco/Net/SocketAddress.h | 324 +-- Net/include/Poco/Net/SocketConnector.h | 454 ++-- Net/include/Poco/Net/SocketDefs.h | 402 ++-- Net/include/Poco/Net/SocketImpl.h | 902 ++++---- Net/include/Poco/Net/SocketNotification.h | 324 +-- Net/include/Poco/Net/SocketNotifier.h | 228 +- Net/include/Poco/Net/SocketReactor.h | 442 ++-- Net/include/Poco/Net/SocketStream.h | 398 ++-- Net/include/Poco/Net/StreamSocket.h | 312 +-- Net/include/Poco/Net/StreamSocketImpl.h | 144 +- Net/include/Poco/Net/StringPartSource.h | 174 +- Net/include/Poco/Net/TCPServer.h | 382 ++-- Net/include/Poco/Net/TCPServerConnection.h | 216 +- .../Poco/Net/TCPServerConnectionFactory.h | 216 +- Net/include/Poco/Net/TCPServerDispatcher.h | 302 +-- Net/include/Poco/Net/TCPServerParams.h | 280 +-- Net/samples/EchoServer/EchoServer.properties | 20 +- Net/samples/EchoServer/EchoServer.vmsbuild | 16 +- Net/samples/EchoServer/EchoServer_vs71.vcproj | 304 +-- Net/samples/EchoServer/EchoServer_vs80.vcproj | 436 ++-- Net/samples/EchoServer/Makefile | 34 +- Net/samples/EchoServer/src/EchoServer.cpp | 456 ++-- .../HTTPFormServer/HTTPFormServer.properties | 20 +- .../HTTPFormServer/HTTPFormServer.vmsbuild | 16 +- .../HTTPFormServer/HTTPFormServer_vs71.vcproj | 304 +-- .../HTTPFormServer/HTTPFormServer_vs80.vcproj | 434 ++-- Net/samples/HTTPFormServer/Makefile | 34 +- .../HTTPFormServer/src/HTTPFormServer.cpp | 652 +++--- .../HTTPLoadTest/HTTPLoadTest.vmsbuild | 14 +- .../HTTPLoadTest/HTTPLoadTest_vs71.vcproj | 290 +-- .../HTTPLoadTest/HTTPLoadTest_vs80.vcproj | 418 ++-- Net/samples/HTTPLoadTest/Makefile | 34 +- Net/samples/HTTPLoadTest/src/HTTPLoadTest.cpp | 776 +++---- .../HTTPTimeServer/HTTPTimeServer.properties | 26 +- .../HTTPTimeServer/HTTPTimeServer.vmsbuild | 16 +- .../HTTPTimeServer/HTTPTimeServer_vs71.vcproj | 304 +-- .../HTTPTimeServer/HTTPTimeServer_vs80.vcproj | 434 ++-- Net/samples/HTTPTimeServer/Makefile | 34 +- .../HTTPTimeServer/src/HTTPTimeServer.cpp | 472 ++-- Net/samples/Mail/Mail.vmsbuild | 16 +- Net/samples/Mail/Mail_vs71.vcproj | 296 +-- Net/samples/Mail/Mail_vs80.vcproj | 428 ++-- Net/samples/Mail/Makefile | 34 +- Net/samples/Mail/src/Mail.cpp | 198 +- Net/samples/Mail/src/PocoLogo.hpp | 268 +-- Net/samples/Makefile | 42 +- Net/samples/Ping/Makefile | 34 +- Net/samples/Ping/Ping.vmsbuild | 14 +- Net/samples/Ping/Ping_vs71.vcproj | 304 +-- Net/samples/Ping/Ping_vs80.vcproj | 434 ++-- Net/samples/Ping/ping.properties | 16 +- Net/samples/Ping/src/Ping.cpp | 438 ++-- Net/samples/TimeServer/Makefile | 34 +- Net/samples/TimeServer/TimeServer.properties | 22 +- Net/samples/TimeServer/TimeServer.vmsbuild | 16 +- Net/samples/TimeServer/TimeServer_vs71.vcproj | 304 +-- Net/samples/TimeServer/TimeServer_vs80.vcproj | 434 ++-- Net/samples/TimeServer/src/TimeServer.cpp | 444 ++-- Net/samples/dict/Makefile | 34 +- Net/samples/dict/dict.vmsbuild | 16 +- Net/samples/dict/dict_vs71.vcproj | 290 +-- Net/samples/dict/dict_vs80.vcproj | 418 ++-- Net/samples/dict/src/dict.cpp | 170 +- Net/samples/download/Makefile | 34 +- Net/samples/download/download.vmsbuild | 16 +- Net/samples/download/download_vs71.vcproj | 290 +-- Net/samples/download/download_vs80.vcproj | 420 ++-- Net/samples/download/src/download.cpp | 164 +- Net/samples/httpget/Makefile | 34 +- Net/samples/httpget/httpget.vmsbuild | 16 +- Net/samples/httpget/httpget_vs71.vcproj | 290 +-- Net/samples/httpget/httpget_vs80.vcproj | 418 ++-- Net/samples/httpget/src/httpget.cpp | 170 +- Net/samples/samples_vs71.sln | 186 +- Net/samples/samples_vs80.sln | 146 +- Net/src/DNS.cpp | 454 ++-- Net/src/DatagramSocket.cpp | 260 +-- Net/src/DatagramSocketImpl.cpp | 166 +- Net/src/DialogSocket.cpp | 556 ++--- Net/src/FTPClientSession.cpp | 1016 ++++----- Net/src/FTPStreamFactory.cpp | 514 ++--- Net/src/FilePartSource.cpp | 176 +- Net/src/HTMLForm.cpp | 722 +++--- Net/src/HTTPBasicCredentials.cpp | 250 +- Net/src/HTTPBufferAllocator.cpp | 132 +- Net/src/HTTPChunkedStream.cpp | 428 ++-- Net/src/HTTPClientSession.cpp | 594 ++--- Net/src/HTTPCookie.cpp | 584 ++--- Net/src/HTTPFixedLengthStream.cpp | 378 ++-- Net/src/HTTPHeaderStream.cpp | 372 +-- Net/src/HTTPIOStream.cpp | 170 +- Net/src/HTTPMessage.cpp | 366 +-- Net/src/HTTPRequest.cpp | 462 ++-- Net/src/HTTPRequestHandler.cpp | 108 +- Net/src/HTTPRequestHandlerFactory.cpp | 108 +- Net/src/HTTPResponse.cpp | 682 +++--- Net/src/HTTPServer.cpp | 126 +- Net/src/HTTPServerConnection.cpp | 206 +- Net/src/HTTPServerConnectionFactory.cpp | 142 +- Net/src/HTTPServerParams.cpp | 190 +- Net/src/HTTPServerRequest.cpp | 182 +- Net/src/HTTPServerResponse.cpp | 302 +-- Net/src/HTTPServerSession.cpp | 176 +- Net/src/HTTPSession.cpp | 436 ++-- Net/src/HTTPSessionFactory.cpp | 306 +-- Net/src/HTTPSessionInstantiator.cpp | 176 +- Net/src/HTTPStream.cpp | 360 +-- Net/src/HTTPStreamFactory.cpp | 256 +-- Net/src/HostEntry.cpp | 260 +-- Net/src/ICMPClient.cpp | 332 +-- Net/src/ICMPEventArgs.cpp | 390 ++-- Net/src/ICMPPacket.cpp | 268 +-- Net/src/ICMPPacketImpl.cpp | 254 +-- Net/src/ICMPSocket.cpp | 202 +- Net/src/ICMPSocketImpl.cpp | 222 +- Net/src/ICMPv4PacketImpl.cpp | 550 ++--- Net/src/IPAddress.cpp | 1494 ++++++------ Net/src/MailMessage.cpp | 1008 ++++----- Net/src/MailRecipient.cpp | 232 +- Net/src/MailStream.cpp | 482 ++-- Net/src/MediaType.cpp | 382 ++-- Net/src/MessageHeader.cpp | 462 ++-- Net/src/MulticastSocket.cpp | 522 ++--- Net/src/MultipartReader.cpp | 634 +++--- Net/src/MultipartWriter.cpp | 204 +- Net/src/NameValueCollection.cpp | 348 +-- Net/src/NetException.cpp | 138 +- Net/src/NetworkInterface.cpp | 1008 ++++----- Net/src/NullPartHandler.cpp | 136 +- Net/src/POP3ClientSession.cpp | 600 ++--- Net/src/PartHandler.cpp | 108 +- Net/src/PartSource.cpp | 136 +- Net/src/QuotedPrintableDecoder.cpp | 248 +- Net/src/QuotedPrintableEncoder.cpp | 344 +-- Net/src/RawSocket.cpp | 266 +-- Net/src/RawSocketImpl.cpp | 182 +- Net/src/SMTPClientSession.cpp | 328 +-- Net/src/ServerSocket.cpp | 260 +-- Net/src/ServerSocketImpl.cpp | 108 +- Net/src/Socket.cpp | 324 +-- Net/src/SocketAddress.cpp | 772 +++---- Net/src/SocketImpl.cpp | 1728 +++++++------- Net/src/SocketNotification.cpp | 232 +- Net/src/SocketNotifier.cpp | 192 +- Net/src/SocketReactor.cpp | 466 ++-- Net/src/SocketStream.cpp | 356 +-- Net/src/StreamSocket.cpp | 286 +-- Net/src/StreamSocketImpl.cpp | 146 +- Net/src/StringPartSource.cpp | 166 +- Net/src/TCPServer.cpp | 352 +-- Net/src/TCPServerConnection.cpp | 164 +- Net/src/TCPServerConnectionFactory.cpp | 108 +- Net/src/TCPServerDispatcher.cpp | 512 ++--- Net/src/TCPServerParams.cpp | 158 +- Net/testsuite/Makefile | 66 +- Net/testsuite/TestSuite.vmsbuild | 18 +- Net/testsuite/TestSuite_vs71.vcproj | 1234 +++++----- Net/testsuite/TestSuite_vs80.vcproj | 1570 ++++++------- Net/testsuite/src/DNSTest.cpp | 262 +-- Net/testsuite/src/DNSTest.h | 124 +- Net/testsuite/src/DatagramSocketTest.cpp | 282 +-- Net/testsuite/src/DatagramSocketTest.h | 124 +- Net/testsuite/src/DialogServer.cpp | 380 ++-- Net/testsuite/src/DialogServer.h | 206 +- Net/testsuite/src/DialogSocketTest.cpp | 234 +- Net/testsuite/src/DialogSocketTest.h | 120 +- Net/testsuite/src/Driver.cpp | 78 +- Net/testsuite/src/EchoServer.cpp | 188 +- Net/testsuite/src/EchoServer.h | 140 +- Net/testsuite/src/FTPClientSessionTest.cpp | 1100 ++++----- Net/testsuite/src/FTPClientSessionTest.h | 138 +- Net/testsuite/src/FTPClientTestSuite.cpp | 92 +- Net/testsuite/src/FTPClientTestSuite.h | 98 +- Net/testsuite/src/FTPStreamFactoryTest.cpp | 558 ++--- Net/testsuite/src/FTPStreamFactoryTest.h | 128 +- Net/testsuite/src/HTMLFormTest.cpp | 614 ++--- Net/testsuite/src/HTMLFormTest.h | 134 +- Net/testsuite/src/HTMLTestSuite.cpp | 88 +- Net/testsuite/src/HTMLTestSuite.h | 98 +- Net/testsuite/src/HTTPClientSessionTest.cpp | 614 ++--- Net/testsuite/src/HTTPClientSessionTest.h | 140 +- Net/testsuite/src/HTTPClientTestSuite.cpp | 92 +- Net/testsuite/src/HTTPClientTestSuite.h | 98 +- Net/testsuite/src/HTTPCookieTest.cpp | 186 +- Net/testsuite/src/HTTPCookieTest.h | 120 +- Net/testsuite/src/HTTPCredentialsTest.cpp | 250 +- Net/testsuite/src/HTTPCredentialsTest.h | 122 +- Net/testsuite/src/HTTPRequestTest.cpp | 492 ++-- Net/testsuite/src/HTTPRequestTest.h | 138 +- Net/testsuite/src/HTTPResponseTest.cpp | 452 ++-- Net/testsuite/src/HTTPResponseTest.h | 134 +- Net/testsuite/src/HTTPServerTest.cpp | 890 ++++---- Net/testsuite/src/HTTPServerTest.h | 140 +- Net/testsuite/src/HTTPServerTestSuite.cpp | 88 +- Net/testsuite/src/HTTPServerTestSuite.h | 98 +- Net/testsuite/src/HTTPStreamFactoryTest.cpp | 304 +-- Net/testsuite/src/HTTPStreamFactoryTest.h | 128 +- Net/testsuite/src/HTTPTestServer.cpp | 472 ++-- Net/testsuite/src/HTTPTestServer.h | 162 +- Net/testsuite/src/HTTPTestSuite.cpp | 100 +- Net/testsuite/src/HTTPTestSuite.h | 98 +- Net/testsuite/src/ICMPClientTest.cpp | 304 +-- Net/testsuite/src/ICMPClientTest.h | 136 +- Net/testsuite/src/ICMPClientTestSuite.cpp | 88 +- Net/testsuite/src/ICMPClientTestSuite.h | 98 +- Net/testsuite/src/ICMPSocketTest.cpp | 230 +- Net/testsuite/src/ICMPSocketTest.h | 122 +- Net/testsuite/src/IPAddressTest.cpp | 784 +++---- Net/testsuite/src/IPAddressTest.h | 136 +- Net/testsuite/src/MailMessageTest.cpp | 882 ++++---- Net/testsuite/src/MailMessageTest.h | 134 +- Net/testsuite/src/MailStreamTest.cpp | 282 +-- Net/testsuite/src/MailStreamTest.h | 122 +- Net/testsuite/src/MailTestSuite.cpp | 100 +- Net/testsuite/src/MailTestSuite.h | 98 +- Net/testsuite/src/MediaTypeTest.cpp | 242 +- Net/testsuite/src/MediaTypeTest.h | 124 +- Net/testsuite/src/MessageHeaderTest.cpp | 770 +++---- Net/testsuite/src/MessageHeaderTest.h | 146 +- Net/testsuite/src/MessagesTestSuite.cpp | 108 +- Net/testsuite/src/MessagesTestSuite.h | 98 +- Net/testsuite/src/MulticastEchoServer.cpp | 234 +- Net/testsuite/src/MulticastEchoServer.h | 170 +- Net/testsuite/src/MulticastSocketTest.cpp | 192 +- Net/testsuite/src/MulticastSocketTest.h | 120 +- Net/testsuite/src/MultipartReaderTest.cpp | 800 +++---- Net/testsuite/src/MultipartReaderTest.h | 136 +- Net/testsuite/src/MultipartWriterTest.cpp | 232 +- Net/testsuite/src/MultipartWriterTest.h | 124 +- Net/testsuite/src/NameValueCollectionTest.cpp | 296 +-- Net/testsuite/src/NameValueCollectionTest.h | 120 +- Net/testsuite/src/NetCoreTestSuite.cpp | 96 +- Net/testsuite/src/NetCoreTestSuite.h | 98 +- Net/testsuite/src/NetTestSuite.cpp | 132 +- Net/testsuite/src/NetTestSuite.h | 98 +- Net/testsuite/src/NetworkInterfaceTest.cpp | 242 +- Net/testsuite/src/NetworkInterfaceTest.h | 126 +- Net/testsuite/src/POP3ClientSessionTest.cpp | 636 +++--- Net/testsuite/src/POP3ClientSessionTest.h | 134 +- Net/testsuite/src/QuotedPrintableTest.cpp | 244 +- Net/testsuite/src/QuotedPrintableTest.h | 122 +- Net/testsuite/src/RawSocketTest.cpp | 254 +-- Net/testsuite/src/RawSocketTest.h | 122 +- Net/testsuite/src/ReactorTestSuite.cpp | 88 +- Net/testsuite/src/ReactorTestSuite.h | 98 +- Net/testsuite/src/SMTPClientSessionTest.cpp | 432 ++-- Net/testsuite/src/SMTPClientSessionTest.h | 128 +- Net/testsuite/src/SocketAddressTest.cpp | 328 +-- Net/testsuite/src/SocketAddressTest.h | 122 +- Net/testsuite/src/SocketReactorTest.cpp | 600 ++--- Net/testsuite/src/SocketReactorTest.h | 124 +- Net/testsuite/src/SocketStreamTest.cpp | 274 +-- Net/testsuite/src/SocketStreamTest.h | 122 +- Net/testsuite/src/SocketTest.cpp | 914 ++++---- Net/testsuite/src/SocketTest.h | 144 +- Net/testsuite/src/SocketsTestSuite.cpp | 112 +- Net/testsuite/src/SocketsTestSuite.h | 98 +- Net/testsuite/src/TCPServerTest.cpp | 552 ++--- Net/testsuite/src/TCPServerTest.h | 124 +- Net/testsuite/src/TCPServerTestSuite.cpp | 88 +- Net/testsuite/src/TCPServerTestSuite.h | 98 +- Net/testsuite/src/UDPEchoServer.cpp | 210 +- Net/testsuite/src/UDPEchoServer.h | 156 +- Net/testsuite/src/WinDriver.cpp | 100 +- 338 files changed, 49884 insertions(+), 49884 deletions(-) diff --git a/Net/Makefile b/Net/Makefile index ccaba6519..9892c39ef 100644 --- a/Net/Makefile +++ b/Net/Makefile @@ -1,37 +1,37 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/Makefile#1 $ -# -# Makefile for Poco Net -# - -include $(POCO_BASE)/build/rules/global - -SHAREDOPT_CXX += -DNet_EXPORTS - -objects = \ - DNS HTTPResponse HostEntry Socket \ - DatagramSocket HTTPServer IPAddress SocketAddress \ - HTTPBasicCredentials HTTPCookie HTMLForm MediaType DialogSocket \ - DatagramSocketImpl FilePartSource HTTPServerConnection MessageHeader \ - HTTPChunkedStream HTTPServerConnectionFactory MulticastSocket SocketStream \ - HTTPClientSession HTTPServerParams MultipartReader StreamSocket SocketImpl \ - HTTPFixedLengthStream HTTPServerRequest MultipartWriter StreamSocketImpl \ - HTTPHeaderStream HTTPServerResponse 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 \ - MailRecipient MailMessage MailStream SMTPClientSession POP3ClientSession \ - RawSocket RawSocketImpl ICMPClient ICMPEventArgs ICMPPacket ICMPPacketImpl \ - ICMPSocket ICMPSocketImpl ICMPv4PacketImpl - -target = PocoNet -target_version = $(LIBVERSION) -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/lib +# +# Makefile +# +# $Id: //poco/1.2/Net/Makefile#1 $ +# +# Makefile for Poco Net +# + +include $(POCO_BASE)/build/rules/global + +SHAREDOPT_CXX += -DNet_EXPORTS + +objects = \ + DNS HTTPResponse HostEntry Socket \ + DatagramSocket HTTPServer IPAddress SocketAddress \ + HTTPBasicCredentials HTTPCookie HTMLForm MediaType DialogSocket \ + DatagramSocketImpl FilePartSource HTTPServerConnection MessageHeader \ + HTTPChunkedStream HTTPServerConnectionFactory MulticastSocket SocketStream \ + HTTPClientSession HTTPServerParams MultipartReader StreamSocket SocketImpl \ + HTTPFixedLengthStream HTTPServerRequest MultipartWriter StreamSocketImpl \ + HTTPHeaderStream HTTPServerResponse 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 \ + MailRecipient MailMessage MailStream SMTPClientSession POP3ClientSession \ + RawSocket RawSocketImpl ICMPClient ICMPEventArgs ICMPPacket ICMPPacketImpl \ + ICMPSocket ICMPSocketImpl ICMPv4PacketImpl + +target = PocoNet +target_version = $(LIBVERSION) +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/lib diff --git a/Net/Net.vmsbuild b/Net/Net.vmsbuild index b2270e3bf..2bb45361d 100644 --- a/Net/Net.vmsbuild +++ b/Net/Net.vmsbuild @@ -1,7 +1,7 @@ -# -# Net.vmsbuild -# -# $Id: //poco/1.2/Net/Net.vmsbuild#1 $ -# -LIB=PocoNet - +# +# Net.vmsbuild +# +# $Id: //poco/1.2/Net/Net.vmsbuild#1 $ +# +LIB=PocoNet + diff --git a/Net/Net_vs71.sln b/Net/Net_vs71.sln index 2c66d6100..a46e72c52 100644 --- a/Net/Net_vs71.sln +++ b/Net/Net_vs71.sln @@ -1,30 +1,30 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Net", "Net_vs71.vcproj", "{B057A1FE-09F7-465E-B8B5-E1B659051D76}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs71.vcproj", "{D5EFBF27-B934-4B8D-8AE5-6EC00374819C}" - ProjectSection(ProjectDependencies) = postProject - {B057A1FE-09F7-465E-B8B5-E1B659051D76} = {B057A1FE-09F7-465E-B8B5-E1B659051D76} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - debug_shared = debug_shared - release_shared = release_shared - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {B057A1FE-09F7-465E-B8B5-E1B659051D76}.debug_shared.ActiveCfg = debug_shared|Win32 - {B057A1FE-09F7-465E-B8B5-E1B659051D76}.debug_shared.Build.0 = debug_shared|Win32 - {B057A1FE-09F7-465E-B8B5-E1B659051D76}.release_shared.ActiveCfg = release_shared|Win32 - {B057A1FE-09F7-465E-B8B5-E1B659051D76}.release_shared.Build.0 = release_shared|Win32 - {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.debug_shared.ActiveCfg = debug_shared|Win32 - {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.debug_shared.Build.0 = debug_shared|Win32 - {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.release_shared.ActiveCfg = release_shared|Win32 - {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.release_shared.Build.0 = release_shared|Win32 - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 8.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Net", "Net_vs71.vcproj", "{B057A1FE-09F7-465E-B8B5-E1B659051D76}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs71.vcproj", "{D5EFBF27-B934-4B8D-8AE5-6EC00374819C}" + ProjectSection(ProjectDependencies) = postProject + {B057A1FE-09F7-465E-B8B5-E1B659051D76} = {B057A1FE-09F7-465E-B8B5-E1B659051D76} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + debug_shared = debug_shared + release_shared = release_shared + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {B057A1FE-09F7-465E-B8B5-E1B659051D76}.debug_shared.ActiveCfg = debug_shared|Win32 + {B057A1FE-09F7-465E-B8B5-E1B659051D76}.debug_shared.Build.0 = debug_shared|Win32 + {B057A1FE-09F7-465E-B8B5-E1B659051D76}.release_shared.ActiveCfg = release_shared|Win32 + {B057A1FE-09F7-465E-B8B5-E1B659051D76}.release_shared.Build.0 = release_shared|Win32 + {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.debug_shared.ActiveCfg = debug_shared|Win32 + {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.debug_shared.Build.0 = debug_shared|Win32 + {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.release_shared.ActiveCfg = release_shared|Win32 + {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.release_shared.Build.0 = release_shared|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/Net/Net_vs71.vcproj b/Net/Net_vs71.vcproj index 7f744a7e2..39fba8b88 100644 --- a/Net/Net_vs71.vcproj +++ b/Net/Net_vs71.vcproj @@ -1,781 +1,781 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/Net_vs80.sln b/Net/Net_vs80.sln index 3471949a7..f2ad39c76 100644 --- a/Net/Net_vs80.sln +++ b/Net/Net_vs80.sln @@ -1,28 +1,28 @@ -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Net", "Net_vs80.vcproj", "{B057A1FE-09F7-465E-B8B5-E1B659051D76}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs80.vcproj", "{D5EFBF27-B934-4B8D-8AE5-6EC00374819C}" - ProjectSection(ProjectDependencies) = postProject - {B057A1FE-09F7-465E-B8B5-E1B659051D76} = {B057A1FE-09F7-465E-B8B5-E1B659051D76} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - debug_shared|Win32 = debug_shared|Win32 - release_shared|Win32 = release_shared|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B057A1FE-09F7-465E-B8B5-E1B659051D76}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {B057A1FE-09F7-465E-B8B5-E1B659051D76}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {B057A1FE-09F7-465E-B8B5-E1B659051D76}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {B057A1FE-09F7-465E-B8B5-E1B659051D76}.release_shared|Win32.Build.0 = release_shared|Win32 - {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.release_shared|Win32.Build.0 = release_shared|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Net", "Net_vs80.vcproj", "{B057A1FE-09F7-465E-B8B5-E1B659051D76}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs80.vcproj", "{D5EFBF27-B934-4B8D-8AE5-6EC00374819C}" + ProjectSection(ProjectDependencies) = postProject + {B057A1FE-09F7-465E-B8B5-E1B659051D76} = {B057A1FE-09F7-465E-B8B5-E1B659051D76} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + debug_shared|Win32 = debug_shared|Win32 + release_shared|Win32 = release_shared|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B057A1FE-09F7-465E-B8B5-E1B659051D76}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {B057A1FE-09F7-465E-B8B5-E1B659051D76}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {B057A1FE-09F7-465E-B8B5-E1B659051D76}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {B057A1FE-09F7-465E-B8B5-E1B659051D76}.release_shared|Win32.Build.0 = release_shared|Win32 + {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {D5EFBF27-B934-4B8D-8AE5-6EC00374819C}.release_shared|Win32.Build.0 = release_shared|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Net/Net_vs80.vcproj b/Net/Net_vs80.vcproj index 7d0c60a56..3a453b11a 100644 --- a/Net/Net_vs80.vcproj +++ b/Net/Net_vs80.vcproj @@ -1,1007 +1,1007 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/include/Poco/Net/DNS.h b/Net/include/Poco/Net/DNS.h index a14248a56..342391cf9 100644 --- a/Net/include/Poco/Net/DNS.h +++ b/Net/include/Poco/Net/DNS.h @@ -1,140 +1,140 @@ -// -// DNS.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/DNS.h#1 $ -// -// Library: Net -// Package: NetCore -// Module: DNS -// -// Definition of the DNS 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_DNS_INCLUDED -#define Net_DNS_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketDefs.h" -#include "Poco/Net/IPAddress.h" -#include "Poco/Net/HostEntry.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API DNS - /// This class provides an interface to the - /// domain name service. - /// - /// An internal DNS cache is used to speed up name lookups. -{ -public: - static const HostEntry& hostByName(const std::string& hostname); - /// Returns a HostEntry object containing the DNS information - /// for the host with the given name. - /// - /// Throws a HostNotFoundException if a host with the given - /// name cannot be found. - /// - /// Throws a NoAddressFoundException if no address can be - /// found for the hostname. - /// - /// Throws a DNSException in case of a general DNS error. - /// - /// Throws an IOException in case of any other error. - - static const HostEntry& hostByAddress(const IPAddress& address); - /// Returns a HostEntry object containing the DNS information - /// for the host with the given IP address. - /// - /// Throws a HostNotFoundException if a host with the given - /// name cannot be found. - /// - /// Throws a DNSException in case of a general DNS error. - /// - /// Throws an IOException in case of any other error. - - static const HostEntry& resolve(const std::string& address); - /// Returns a HostEntry object containing the DNS information - /// for the host with the given IP address or host name. - /// - /// Throws a HostNotFoundException if a host with the given - /// name cannot be found. - /// - /// Throws a NoAddressFoundException if no address can be - /// found for the hostname. - /// - /// Throws a DNSException in case of a general DNS error. - /// - /// Throws an IOException in case of any other error. - - static IPAddress resolveOne(const std::string& address); - /// Convenience method that calls resolve(address) and returns - /// the first address from the HostInfo. - - static const HostEntry& thisHost(); - /// Returns a HostEntry object containing the DNS information - /// for this host. - /// - /// Throws a HostNotFoundException if DNS information - /// for this host cannot be found. - /// - /// Throws a NoAddressFoundException if no address can be - /// found for this host. - /// - /// Throws a DNSException in case of a general DNS error. - /// - /// Throws an IOException in case of any other error. - - static void flushCache(); - /// Flushes the internal DNS cache. - -protected: - static int lastError(); - /// Returns the code of the last error. - - static void error(int code, const std::string& arg); - /// Throws an exception according to the error code. - -private: - typedef std::map DNSCache; - - static DNSCache _cache; - static Poco::FastMutex _mutex; -}; - - -} } // namespace Poco::Net - - -#endif // Net_DNS_INCLUDED +// +// DNS.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/DNS.h#1 $ +// +// Library: Net +// Package: NetCore +// Module: DNS +// +// Definition of the DNS 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_DNS_INCLUDED +#define Net_DNS_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketDefs.h" +#include "Poco/Net/IPAddress.h" +#include "Poco/Net/HostEntry.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API DNS + /// This class provides an interface to the + /// domain name service. + /// + /// An internal DNS cache is used to speed up name lookups. +{ +public: + static const HostEntry& hostByName(const std::string& hostname); + /// Returns a HostEntry object containing the DNS information + /// for the host with the given name. + /// + /// Throws a HostNotFoundException if a host with the given + /// name cannot be found. + /// + /// Throws a NoAddressFoundException if no address can be + /// found for the hostname. + /// + /// Throws a DNSException in case of a general DNS error. + /// + /// Throws an IOException in case of any other error. + + static const HostEntry& hostByAddress(const IPAddress& address); + /// Returns a HostEntry object containing the DNS information + /// for the host with the given IP address. + /// + /// Throws a HostNotFoundException if a host with the given + /// name cannot be found. + /// + /// Throws a DNSException in case of a general DNS error. + /// + /// Throws an IOException in case of any other error. + + static const HostEntry& resolve(const std::string& address); + /// Returns a HostEntry object containing the DNS information + /// for the host with the given IP address or host name. + /// + /// Throws a HostNotFoundException if a host with the given + /// name cannot be found. + /// + /// Throws a NoAddressFoundException if no address can be + /// found for the hostname. + /// + /// Throws a DNSException in case of a general DNS error. + /// + /// Throws an IOException in case of any other error. + + static IPAddress resolveOne(const std::string& address); + /// Convenience method that calls resolve(address) and returns + /// the first address from the HostInfo. + + static const HostEntry& thisHost(); + /// Returns a HostEntry object containing the DNS information + /// for this host. + /// + /// Throws a HostNotFoundException if DNS information + /// for this host cannot be found. + /// + /// Throws a NoAddressFoundException if no address can be + /// found for this host. + /// + /// Throws a DNSException in case of a general DNS error. + /// + /// Throws an IOException in case of any other error. + + static void flushCache(); + /// Flushes the internal DNS cache. + +protected: + static int lastError(); + /// Returns the code of the last error. + + static void error(int code, const std::string& arg); + /// Throws an exception according to the error code. + +private: + typedef std::map DNSCache; + + static DNSCache _cache; + static Poco::FastMutex _mutex; +}; + + +} } // namespace Poco::Net + + +#endif // Net_DNS_INCLUDED diff --git a/Net/include/Poco/Net/DatagramSocket.h b/Net/include/Poco/Net/DatagramSocket.h index 74d1889df..bb6308dff 100644 --- a/Net/include/Poco/Net/DatagramSocket.h +++ b/Net/include/Poco/Net/DatagramSocket.h @@ -1,169 +1,169 @@ -// -// DatagramSocket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/DatagramSocket.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: DatagramSocket -// -// Definition of the DatagramSocket 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_DatagramSocket_INCLUDED -#define Net_DatagramSocket_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/Socket.h" - - -namespace Poco { -namespace Net { - - -class Net_API DatagramSocket: public Socket - /// This class provides an interface to an - /// UDP stream socket. -{ -public: - DatagramSocket(); - /// Creates an unconnected IPv4 datagram socket. - - DatagramSocket(IPAddress::Family family); - /// Creates an unconnected datagram socket. - /// - /// The socket will be created for the - /// given address family. - - DatagramSocket(const SocketAddress& address, bool reuseAddress = false); - /// Creates a datagram socket and binds it - /// to the given address. - /// - /// Depending on the address family, the socket - /// will be either an IPv4 or an IPv6 socket. - - DatagramSocket(const Socket& socket); - /// Creates the DatagramSocket with the SocketImpl - /// from another socket. The SocketImpl must be - /// a DatagramSocketImpl, otherwise an InvalidArgumentException - /// will be thrown. - - ~DatagramSocket(); - /// Destroys the DatagramSocket. - - DatagramSocket& operator = (const Socket& socket); - /// Assignment operator. - /// - /// Releases the socket's SocketImpl and - /// attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - void connect(const SocketAddress& address); - /// Restricts incoming and outgoing - /// packets to the specified address. - /// - /// Cannot be used together with bind(). - - void bind(const SocketAddress& address, bool reuseAddress = false); - /// Bind a local address to the socket. - /// - /// This is usually only done when establishing a server - /// socket. - /// - /// If reuseAddress is true, sets the SO_REUSEADDR - /// socket option. - /// - /// Cannot be used together with connect(). - - int sendBytes(const void* buffer, int length, int flags = 0); - /// Sends the contents of the given buffer through - /// the socket. - /// - /// Returns the number of bytes sent, which may be - /// less than the number of bytes specified. - - int receiveBytes(void* buffer, int length, int flags = 0); - /// Receives data from the socket and stores it - /// in buffer. Up to length bytes are received. - /// - /// Returns the number of bytes received. - - int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0); - /// Sends the contents of the given buffer through - /// the socket to the given address. - /// - /// Returns the number of bytes sent, which may be - /// less than the number of bytes specified. - - int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0); - /// Receives data from the socket and stores it - /// in buffer. Up to length bytes are received. - /// Stores the address of the sender in address. - /// - /// Returns the number of bytes received. - - void setBroadcast(bool flag); - /// Sets the value of the SO_BROADCAST socket option. - /// - /// Setting this flag allows sending datagrams to - /// the broadcast address. - - bool getBroadcast() const; - /// Returns the value of the SO_BROADCAST socket option. - -protected: - DatagramSocket(SocketImpl* pImpl); - /// Creates the Socket and attaches the given SocketImpl. - /// The socket takes owership of the SocketImpl. - /// - /// The SocketImpl must be a StreamSocketImpl, otherwise - /// an InvalidArgumentException will be thrown. -}; - - -// -// inlines -// -inline void DatagramSocket::setBroadcast(bool flag) -{ - impl()->setBroadcast(flag); -} - - -inline bool DatagramSocket::getBroadcast() const -{ - return impl()->getBroadcast(); -} - - -} } // namespace Poco::Net - - -#endif // Net_DatagramSocket_INCLUDED +// +// DatagramSocket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/DatagramSocket.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: DatagramSocket +// +// Definition of the DatagramSocket 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_DatagramSocket_INCLUDED +#define Net_DatagramSocket_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/Socket.h" + + +namespace Poco { +namespace Net { + + +class Net_API DatagramSocket: public Socket + /// This class provides an interface to an + /// UDP stream socket. +{ +public: + DatagramSocket(); + /// Creates an unconnected IPv4 datagram socket. + + DatagramSocket(IPAddress::Family family); + /// Creates an unconnected datagram socket. + /// + /// The socket will be created for the + /// given address family. + + DatagramSocket(const SocketAddress& address, bool reuseAddress = false); + /// Creates a datagram socket and binds it + /// to the given address. + /// + /// Depending on the address family, the socket + /// will be either an IPv4 or an IPv6 socket. + + DatagramSocket(const Socket& socket); + /// Creates the DatagramSocket with the SocketImpl + /// from another socket. The SocketImpl must be + /// a DatagramSocketImpl, otherwise an InvalidArgumentException + /// will be thrown. + + ~DatagramSocket(); + /// Destroys the DatagramSocket. + + DatagramSocket& operator = (const Socket& socket); + /// Assignment operator. + /// + /// Releases the socket's SocketImpl and + /// attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + void connect(const SocketAddress& address); + /// Restricts incoming and outgoing + /// packets to the specified address. + /// + /// Cannot be used together with bind(). + + void bind(const SocketAddress& address, bool reuseAddress = false); + /// Bind a local address to the socket. + /// + /// This is usually only done when establishing a server + /// socket. + /// + /// If reuseAddress is true, sets the SO_REUSEADDR + /// socket option. + /// + /// Cannot be used together with connect(). + + int sendBytes(const void* buffer, int length, int flags = 0); + /// Sends the contents of the given buffer through + /// the socket. + /// + /// Returns the number of bytes sent, which may be + /// less than the number of bytes specified. + + int receiveBytes(void* buffer, int length, int flags = 0); + /// Receives data from the socket and stores it + /// in buffer. Up to length bytes are received. + /// + /// Returns the number of bytes received. + + int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0); + /// Sends the contents of the given buffer through + /// the socket to the given address. + /// + /// Returns the number of bytes sent, which may be + /// less than the number of bytes specified. + + int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0); + /// Receives data from the socket and stores it + /// in buffer. Up to length bytes are received. + /// Stores the address of the sender in address. + /// + /// Returns the number of bytes received. + + void setBroadcast(bool flag); + /// Sets the value of the SO_BROADCAST socket option. + /// + /// Setting this flag allows sending datagrams to + /// the broadcast address. + + bool getBroadcast() const; + /// Returns the value of the SO_BROADCAST socket option. + +protected: + DatagramSocket(SocketImpl* pImpl); + /// Creates the Socket and attaches the given SocketImpl. + /// The socket takes owership of the SocketImpl. + /// + /// The SocketImpl must be a StreamSocketImpl, otherwise + /// an InvalidArgumentException will be thrown. +}; + + +// +// inlines +// +inline void DatagramSocket::setBroadcast(bool flag) +{ + impl()->setBroadcast(flag); +} + + +inline bool DatagramSocket::getBroadcast() const +{ + return impl()->getBroadcast(); +} + + +} } // namespace Poco::Net + + +#endif // Net_DatagramSocket_INCLUDED diff --git a/Net/include/Poco/Net/DatagramSocketImpl.h b/Net/include/Poco/Net/DatagramSocketImpl.h index a03e98671..4d9073c08 100644 --- a/Net/include/Poco/Net/DatagramSocketImpl.h +++ b/Net/include/Poco/Net/DatagramSocketImpl.h @@ -1,81 +1,81 @@ -// -// DatagramSocketImpl.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/DatagramSocketImpl.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: DatagramSocketImpl -// -// Definition of the DatagramSocketImpl 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_DatagramSocketImpl_INCLUDED -#define Net_DatagramSocketImpl_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketImpl.h" - - -namespace Poco { -namespace Net { - - -class Net_API DatagramSocketImpl: public SocketImpl - /// This class implements an UDP socket. -{ -public: - DatagramSocketImpl(); - /// Creates a StreamSocketImpl. - /// - /// If the system supports IPv6, the socket will - /// be an IPv6 socket. Otherwise, it will be - /// an IPv4 socket. - - DatagramSocketImpl(IPAddress::Family family); - /// Creates an unconnected datagram socket. - /// - /// The socket will be created for the - /// given address family. - - DatagramSocketImpl(poco_socket_t sockfd); - /// Creates a StreamSocketImpl using the given native socket. - -protected: - void init(int af); - - ~DatagramSocketImpl(); -}; - - -} } // namespace Poco::Net - - -#endif // Net_DatagramSocketImpl_INCLUDED +// +// DatagramSocketImpl.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/DatagramSocketImpl.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: DatagramSocketImpl +// +// Definition of the DatagramSocketImpl 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_DatagramSocketImpl_INCLUDED +#define Net_DatagramSocketImpl_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketImpl.h" + + +namespace Poco { +namespace Net { + + +class Net_API DatagramSocketImpl: public SocketImpl + /// This class implements an UDP socket. +{ +public: + DatagramSocketImpl(); + /// Creates a StreamSocketImpl. + /// + /// If the system supports IPv6, the socket will + /// be an IPv6 socket. Otherwise, it will be + /// an IPv4 socket. + + DatagramSocketImpl(IPAddress::Family family); + /// Creates an unconnected datagram socket. + /// + /// The socket will be created for the + /// given address family. + + DatagramSocketImpl(poco_socket_t sockfd); + /// Creates a StreamSocketImpl using the given native socket. + +protected: + void init(int af); + + ~DatagramSocketImpl(); +}; + + +} } // namespace Poco::Net + + +#endif // Net_DatagramSocketImpl_INCLUDED diff --git a/Net/include/Poco/Net/DialogSocket.h b/Net/include/Poco/Net/DialogSocket.h index a81452eaa..9a6c88172 100644 --- a/Net/include/Poco/Net/DialogSocket.h +++ b/Net/include/Poco/Net/DialogSocket.h @@ -1,210 +1,210 @@ -// -// DialogSocket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/DialogSocket.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: DialogSocket -// -// Definition of the DialogSocket 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_DialogSocket_INCLUDED -#define Net_DialogSocket_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/StreamSocket.h" - - -namespace Poco { -namespace Net { - - -class Net_API DialogSocket: public StreamSocket - /// DialogSocket is a subclass of StreamSocket that - /// can be used for implementing request-response - /// based client server connections. - /// - /// A request is always a single-line command terminated - /// by CR-LF. - /// - /// A response can either be a single line of text terminated - /// by CR-LF, or multiple lines of text in the format used - /// by the FTP and SMTP protocols. - /// - /// Limited support for the TELNET protocol (RFC 854) is - /// available. -{ -public: - DialogSocket(); - /// Creates an unconnected stream socket. - /// - /// Before sending or receiving data, the socket - /// must be connected with a call to connect(). - - DialogSocket(const SocketAddress& address); - /// Creates a stream socket and connects it to - /// the socket specified by address. - - DialogSocket(const Socket& socket); - /// Creates the DialogSocket with the SocketImpl - /// from another socket. The SocketImpl must be - /// a StreamSocketImpl, otherwise an InvalidArgumentException - /// will be thrown. - - ~DialogSocket(); - /// Destroys the DialogSocket. - - DialogSocket& operator = (const Socket& socket); - /// Assignment operator. - /// - /// Releases the socket's SocketImpl and - /// attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - void sendByte(unsigned char ch); - /// Sends a single byte over the socket connection. - - void sendString(const char* str); - /// Sends the given null-terminated string over - /// the socket connection. - - void sendString(const std::string& str); - /// Sends the given string over the socket connection. - - void sendMessage(const std::string& message); - /// Appends a CR-LF sequence to the message and sends it - /// over the socket connection. - - void sendMessage(const std::string& message, const std::string& arg); - /// Concatenates message and arg, separated by a space, appends a - /// CR-LF sequence, and sends the result over the socket connection. - - void sendMessage(const std::string& message, const std::string& arg1, const std::string& arg2); - /// Concatenates message and args, separated by a space, appends a - /// CR-LF sequence, and sends the result over the socket connection. - - bool receiveMessage(std::string& message); - /// Receives a single-line message, terminated by CR-LF, - /// from the socket connection and appends it to response. - /// - /// Returns true if a message has been read or false if - /// the connection has been closed by the peer. - - int receiveStatusMessage(std::string& message); - /// Receives a single-line or multi-line response from - /// the socket connection. The format must be according to - /// one of the response formats specified in the FTP (RFC 959) - /// or SMTP (RFC 2821) specifications. - /// - /// The first line starts with a 3-digit status code. - /// Following the status code is either a space character (' ' ) - /// (in case of a single-line response) or a minus character ('-') - /// in case of a multi-line response. The following lines can have - /// a three-digit status code followed by a minus-sign and some - /// text, or some arbitrary text only. The last line again begins - /// with a three-digit status code (which must be the same as the - /// one in the first line), followed by a space and some arbitrary - /// text. All lines must be terminated by a CR-LF sequence. - /// - /// The response contains all response lines, separated by a newline - /// character, including the status code. The status code is returned. - /// If the response line does not contain a status code, 0 is returned. - - int get(); - /// Reads one character from the connection. - /// - /// Returns -1 (EOF_CHAR) if no more characters are available. - - int peek(); - /// Returns the character that would be returned by the next call - /// to get(), without actually extracting the character from the - /// buffer. - /// - /// Returns -1 (EOF_CHAR) if no more characters are available. - - void synch(); - /// Sends a TELNET SYNCH signal over the connection. - /// - /// According to RFC 854, a TELNET_DM char is sent - /// via sendUrgent(). - - void sendTelnetCommand(unsigned char command); - /// Sends a TELNET command sequence (TELNET_IAC followed - /// by the given command) over the connection. - - void sendTelnetCommand(unsigned char command, unsigned char arg); - /// Sends a TELNET command sequence (TELNET_IAC followed - /// by the given command, followed by arg) over the connection. - - enum TelnetCodes - { - TELNET_SE = 240, - TELNET_NOP = 241, - TELNET_DM = 242, - TELNET_BRK = 243, - TELNET_IP = 244, - TELNET_AO = 245, - TELNET_AYT = 246, - TELNET_EC = 247, - TELNET_EL = 248, - TELNET_GA = 249, - TELNET_SB = 250, - TELNET_WILL = 251, - TELNET_WONT = 252, - TELNET_DO = 253, - TELNET_DONT = 254, - TELNET_IAC = 255 - }; - -protected: - void allocBuffer(); - void refill(); - bool receiveLine(std::string& line); - int receiveStatusLine(std::string& line); - -private: - enum - { - RECEIVE_BUFFER_SIZE = 1024, - EOF_CHAR = -1 - }; - - char* _pBuffer; - char* _pNext; - char* _pEnd; -}; - - -} } // namespace Poco::Net - - -#endif // Net_DialogSocket_INCLUDED +// +// DialogSocket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/DialogSocket.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: DialogSocket +// +// Definition of the DialogSocket 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_DialogSocket_INCLUDED +#define Net_DialogSocket_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/StreamSocket.h" + + +namespace Poco { +namespace Net { + + +class Net_API DialogSocket: public StreamSocket + /// DialogSocket is a subclass of StreamSocket that + /// can be used for implementing request-response + /// based client server connections. + /// + /// A request is always a single-line command terminated + /// by CR-LF. + /// + /// A response can either be a single line of text terminated + /// by CR-LF, or multiple lines of text in the format used + /// by the FTP and SMTP protocols. + /// + /// Limited support for the TELNET protocol (RFC 854) is + /// available. +{ +public: + DialogSocket(); + /// Creates an unconnected stream socket. + /// + /// Before sending or receiving data, the socket + /// must be connected with a call to connect(). + + DialogSocket(const SocketAddress& address); + /// Creates a stream socket and connects it to + /// the socket specified by address. + + DialogSocket(const Socket& socket); + /// Creates the DialogSocket with the SocketImpl + /// from another socket. The SocketImpl must be + /// a StreamSocketImpl, otherwise an InvalidArgumentException + /// will be thrown. + + ~DialogSocket(); + /// Destroys the DialogSocket. + + DialogSocket& operator = (const Socket& socket); + /// Assignment operator. + /// + /// Releases the socket's SocketImpl and + /// attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + void sendByte(unsigned char ch); + /// Sends a single byte over the socket connection. + + void sendString(const char* str); + /// Sends the given null-terminated string over + /// the socket connection. + + void sendString(const std::string& str); + /// Sends the given string over the socket connection. + + void sendMessage(const std::string& message); + /// Appends a CR-LF sequence to the message and sends it + /// over the socket connection. + + void sendMessage(const std::string& message, const std::string& arg); + /// Concatenates message and arg, separated by a space, appends a + /// CR-LF sequence, and sends the result over the socket connection. + + void sendMessage(const std::string& message, const std::string& arg1, const std::string& arg2); + /// Concatenates message and args, separated by a space, appends a + /// CR-LF sequence, and sends the result over the socket connection. + + bool receiveMessage(std::string& message); + /// Receives a single-line message, terminated by CR-LF, + /// from the socket connection and appends it to response. + /// + /// Returns true if a message has been read or false if + /// the connection has been closed by the peer. + + int receiveStatusMessage(std::string& message); + /// Receives a single-line or multi-line response from + /// the socket connection. The format must be according to + /// one of the response formats specified in the FTP (RFC 959) + /// or SMTP (RFC 2821) specifications. + /// + /// The first line starts with a 3-digit status code. + /// Following the status code is either a space character (' ' ) + /// (in case of a single-line response) or a minus character ('-') + /// in case of a multi-line response. The following lines can have + /// a three-digit status code followed by a minus-sign and some + /// text, or some arbitrary text only. The last line again begins + /// with a three-digit status code (which must be the same as the + /// one in the first line), followed by a space and some arbitrary + /// text. All lines must be terminated by a CR-LF sequence. + /// + /// The response contains all response lines, separated by a newline + /// character, including the status code. The status code is returned. + /// If the response line does not contain a status code, 0 is returned. + + int get(); + /// Reads one character from the connection. + /// + /// Returns -1 (EOF_CHAR) if no more characters are available. + + int peek(); + /// Returns the character that would be returned by the next call + /// to get(), without actually extracting the character from the + /// buffer. + /// + /// Returns -1 (EOF_CHAR) if no more characters are available. + + void synch(); + /// Sends a TELNET SYNCH signal over the connection. + /// + /// According to RFC 854, a TELNET_DM char is sent + /// via sendUrgent(). + + void sendTelnetCommand(unsigned char command); + /// Sends a TELNET command sequence (TELNET_IAC followed + /// by the given command) over the connection. + + void sendTelnetCommand(unsigned char command, unsigned char arg); + /// Sends a TELNET command sequence (TELNET_IAC followed + /// by the given command, followed by arg) over the connection. + + enum TelnetCodes + { + TELNET_SE = 240, + TELNET_NOP = 241, + TELNET_DM = 242, + TELNET_BRK = 243, + TELNET_IP = 244, + TELNET_AO = 245, + TELNET_AYT = 246, + TELNET_EC = 247, + TELNET_EL = 248, + TELNET_GA = 249, + TELNET_SB = 250, + TELNET_WILL = 251, + TELNET_WONT = 252, + TELNET_DO = 253, + TELNET_DONT = 254, + TELNET_IAC = 255 + }; + +protected: + void allocBuffer(); + void refill(); + bool receiveLine(std::string& line); + int receiveStatusLine(std::string& line); + +private: + enum + { + RECEIVE_BUFFER_SIZE = 1024, + EOF_CHAR = -1 + }; + + char* _pBuffer; + char* _pNext; + char* _pEnd; +}; + + +} } // namespace Poco::Net + + +#endif // Net_DialogSocket_INCLUDED diff --git a/Net/include/Poco/Net/FTPClientSession.h b/Net/include/Poco/Net/FTPClientSession.h index 97a916aa9..c19def44f 100644 --- a/Net/include/Poco/Net/FTPClientSession.h +++ b/Net/include/Poco/Net/FTPClientSession.h @@ -1,382 +1,382 @@ -// -// FTPClientSession.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/FTPClientSession.h#1 $ -// -// Library: Net -// Package: FTP -// Module: FTPClientSession -// -// Definition of the FTPClientSession 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_FTPClientSession_INCLUDED -#define Net_FTPClientSession_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/DialogSocket.h" -#include "Poco/Timespan.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class SocketStream; - - -class Net_API FTPClientSession - /// This class implements an File Transfer Protocol - /// (FTP, RFC 959) client. - /// - /// Most of the features of the FTP protocol, as specified - /// in RFC 959, are supported. Not supported are EBCDIC and - /// LOCAL data types and format control and structured files. - /// - /// Also supported are the EPRT and EPSV commands from - /// RFC 1738 (FTP Extensions for IPv6 and NAT). - /// The client will first attempt to use the EPRT and EPSV - /// commands. If the server does not supports these commands, - /// the client will fall back to PORT and PASV. -{ -public: - enum - { - FTP_PORT = 21 - }; - - enum FileType - { - TYPE_TEXT, // TYPE A (ASCII) - TYPE_BINARY // TYPE I (Image) - }; - - explicit FTPClientSession(const StreamSocket& socket); - /// Creates an FTPClientSession using the given - /// connected socket for the control connection. - /// - /// Passive mode will be used for data transfers. - - FTPClientSession(const std::string& host, Poco::UInt16 port = FTP_PORT); - /// Creates an FTPClientSession using a socket connected - /// to the given host and port. - /// - /// Passive mode will be used for data transfers. - - virtual ~FTPClientSession(); - /// Destroys the FTPClientSession. - - void setTimeout(const Poco::Timespan& timeout); - /// Sets the timeout for socket operations. - - Poco::Timespan getTimeout() const; - /// Returns the timeout for socket operations. - - void setPassive(bool flag); - /// Enables (default) or disables FTP passive mode for this session. - - bool getPassive() const; - /// Returns true iff passive mode is enabled for this connection. - - void login(const std::string& username, const std::string& password); - /// Authenticates the user against the FTP server. Must be - /// called before any other commands (except QUIT) can be sent. - /// - /// Sends a USER command followed by a PASS command with the - /// respective arguments to the server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - void close(); - /// Sends a QUIT command and closes the connection to the server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - std::string systemType(); - /// Returns the system type of the FTP server. - /// - /// Sends a SYST command to the server and returns the result. - - void setFileType(FileType type); - /// Sets the file type for transferring files. - /// - /// Sends a TYPE command with a corresponsing argument to the - /// server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - FileType getFileType() const; - /// Returns the file type for transferring files. - - void setWorkingDirectory(const std::string& path); - /// Changes the current working directory on the server. - /// - /// Sends a CWD command with the given path as argument to the - /// server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - std::string getWorkingDirectory(); - /// Returns the current working directory on the server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - void cdup(); - /// Moves one directory up from the current working directory - /// on teh server. - /// - /// Sends a CDUP command to the server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - void rename(const std::string& oldName, const std::string& newName); - /// Renames the file on the server given by oldName to newName. - /// - /// Sends a RNFR command, followed by a RNTO command to the server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - void remove(const std::string& path); - /// Deletes the file specified by path on the server. - /// - /// Sends a DELE command with path as argument to the server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - void createDirectory(const std::string& path); - /// Creates a new directory with the given path on the server. - /// - /// Sends a MKD command with path as argument to the server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - void removeDirectory(const std::string& path); - /// Removes the directory specified by path from the server. - /// - /// Sends a RMD command with path as argument to the server. - /// - /// Throws a FTPException in case of a FTP-specific error, or a - /// NetException in case of a general network communication failure. - - std::istream& beginDownload(const std::string& path); - /// Starts downloading the file with the given name. - /// After all data has been read from the returned stream, - /// endDownload() must be called to finish the download. - /// - /// A stream for reading the file's content is returned. - /// The stream is valid until endDownload() is called. - /// - /// Creates a data connection between the client and the - /// server. If passive mode is on, then the server waits for - /// a connection request from the client. Otherwise, the - /// client waits for a connection request from the server. - /// After establishing the data connection, a SocketStream - /// for transferring the data is created. - /// - /// If ASCII transfer mode is selected, the caller is - /// responsible for converting the received data to - /// the native text file format. - /// The InputLineEndingConverter class from the Foundation - /// library can be used for that purpose. - - void endDownload(); - /// Must be called to complete a download initiated with - /// beginDownload(). - - std::ostream& beginUpload(const std::string& path); - /// Starts uploading the file with the given name. - /// After all data has been written to the returned stream, - /// endUpload() must be called to finish the download. - /// - /// A stream for reading the file's content is returned. - /// The stream is valid until endUpload() is called. - /// - /// Creates a data connection between the client and the - /// server. If passive mode is on, then the server waits for - /// a connection request from the client. Otherwise, the - /// client waits for a connection request from the server. - /// After establishing the data connection, a SocketStream - /// for transferring the data is created. - /// - /// If ASCII transfer mode is selected, the caller is - /// responsible for converting the data to be sent - /// into network (CR-LF line endings) format. - /// The OutputLineEndingConverter class from the Foundation - /// library can be used for that purpose. - - void endUpload(); - /// Must be called to complete an upload initiated with - /// beginUpload(). - - std::istream& beginList(const std::string& path = "", bool extended = false); - /// Starts downloading a directory listing. - /// After all data has been read from the returned stream, - /// endList() must be called to finish the download. - /// - /// A stream for reading the directory data is returned. - /// The stream is valid until endList() is called. - /// - /// Optionally, a path to a directory or file can be specified. - /// According to the FTP prototol, if a path to a filename is - /// given, only information for the specific file is returned. - /// If a path to a directory is given, a listing of that directory - /// is returned. If no path is given, a listing of the current - /// working directory is returned. - /// - /// If extended is false, only a filenames (one per line) are - /// returned. Otherwise, a full directory listing including - /// file attributes is returned. The format of this listing - /// depends on the FTP server. No attempt is made to interpret - /// this data. - /// - /// Creates a data connection between the client and the - /// server. If passive mode is on, then the server waits for - /// a connection request from the client. Otherwise, the - /// client waits for a connection request from the server. - /// After establishing the data connection, a SocketStream - /// for transferring the data is created. - - void endList(); - /// Must be called to complete a directory listing download - /// initiated with beginList(). - - void abort(); - /// Aborts the download or upload currently in progress. - /// - /// Sends a TELNET IP/SYNCH sequence, followed by an ABOR - /// command to the server. - /// - /// A separate call to endDownload() or endUpload() is - /// not necessary. - - int sendCommand(const std::string& command, std::string& response); - /// Sends the given command verbatim to the server - /// and waits for a response. - - int sendCommand(const std::string& command, const std::string& arg, std::string& response); - /// Sends the given command verbatim to the server - /// and waits for a response. - -protected: - enum StatusClass - { - FTP_POSITIVE_PRELIMINARY = 1, - FTP_POSITIVE_COMPLETION = 2, - FTP_POSITIVE_INTERMEDIATE = 3, - FTP_TRANSIENT_NEGATIVE = 4, - FTP_PERMANENT_NEGATIVE = 5 - }; - enum - { - DEFAULT_TIMEOUT = 30000000 // 30 seconds default timeout for socket operations - }; - - static bool isPositivePreliminary(int status); - static bool isPositiveCompletion(int status); - static bool isPositiveIntermediate(int status); - static bool isTransientNegative(int status); - static bool isPermanentNegative(int status); - std::string extractPath(const std::string& response); - StreamSocket establishDataConnection(const std::string& command, const std::string& arg); - StreamSocket activeDataConnection(const std::string& command, const std::string& arg); - StreamSocket passiveDataConnection(const std::string& command, const std::string& arg); - void sendPortCommand(const SocketAddress& addr); - SocketAddress sendPassiveCommand(); - bool sendEPRT(const SocketAddress& addr); - void sendPORT(const SocketAddress& addr); - bool sendEPSV(SocketAddress& addr); - void sendPASV(SocketAddress& addr); - void parseAddress(const std::string& str, SocketAddress& addr); - void parseExtAddress(const std::string& str, SocketAddress& addr); - void endTransfer(); - -private: - FTPClientSession(); - FTPClientSession(const FTPClientSession&); - FTPClientSession& operator = (const FTPClientSession&); - - DialogSocket _controlSocket; - SocketStream* _pDataStream; - bool _passiveMode; - FileType _fileType; - bool _supports1738; - bool _isOpen; - Poco::Timespan _timeout; -}; - - -// -// inlines -// -inline bool FTPClientSession::isPositivePreliminary(int status) -{ - return status/100 == FTP_POSITIVE_PRELIMINARY; -} - - -inline bool FTPClientSession::isPositiveCompletion(int status) -{ - return status/100 == FTP_POSITIVE_COMPLETION; -} - - -inline bool FTPClientSession::isPositiveIntermediate(int status) -{ - return status/100 == FTP_POSITIVE_INTERMEDIATE; -} - - -inline bool FTPClientSession::isTransientNegative(int status) -{ - return status/100 == FTP_TRANSIENT_NEGATIVE; -} - - -inline bool FTPClientSession::isPermanentNegative(int status) -{ - return status/100 == FTP_PERMANENT_NEGATIVE; -} - - -} } // namespace Poco::Net - - -#endif // Net_FTPClientSession_INCLUDED +// +// FTPClientSession.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/FTPClientSession.h#1 $ +// +// Library: Net +// Package: FTP +// Module: FTPClientSession +// +// Definition of the FTPClientSession 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_FTPClientSession_INCLUDED +#define Net_FTPClientSession_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/DialogSocket.h" +#include "Poco/Timespan.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class SocketStream; + + +class Net_API FTPClientSession + /// This class implements an File Transfer Protocol + /// (FTP, RFC 959) client. + /// + /// Most of the features of the FTP protocol, as specified + /// in RFC 959, are supported. Not supported are EBCDIC and + /// LOCAL data types and format control and structured files. + /// + /// Also supported are the EPRT and EPSV commands from + /// RFC 1738 (FTP Extensions for IPv6 and NAT). + /// The client will first attempt to use the EPRT and EPSV + /// commands. If the server does not supports these commands, + /// the client will fall back to PORT and PASV. +{ +public: + enum + { + FTP_PORT = 21 + }; + + enum FileType + { + TYPE_TEXT, // TYPE A (ASCII) + TYPE_BINARY // TYPE I (Image) + }; + + explicit FTPClientSession(const StreamSocket& socket); + /// Creates an FTPClientSession using the given + /// connected socket for the control connection. + /// + /// Passive mode will be used for data transfers. + + FTPClientSession(const std::string& host, Poco::UInt16 port = FTP_PORT); + /// Creates an FTPClientSession using a socket connected + /// to the given host and port. + /// + /// Passive mode will be used for data transfers. + + virtual ~FTPClientSession(); + /// Destroys the FTPClientSession. + + void setTimeout(const Poco::Timespan& timeout); + /// Sets the timeout for socket operations. + + Poco::Timespan getTimeout() const; + /// Returns the timeout for socket operations. + + void setPassive(bool flag); + /// Enables (default) or disables FTP passive mode for this session. + + bool getPassive() const; + /// Returns true iff passive mode is enabled for this connection. + + void login(const std::string& username, const std::string& password); + /// Authenticates the user against the FTP server. Must be + /// called before any other commands (except QUIT) can be sent. + /// + /// Sends a USER command followed by a PASS command with the + /// respective arguments to the server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + void close(); + /// Sends a QUIT command and closes the connection to the server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + std::string systemType(); + /// Returns the system type of the FTP server. + /// + /// Sends a SYST command to the server and returns the result. + + void setFileType(FileType type); + /// Sets the file type for transferring files. + /// + /// Sends a TYPE command with a corresponsing argument to the + /// server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + FileType getFileType() const; + /// Returns the file type for transferring files. + + void setWorkingDirectory(const std::string& path); + /// Changes the current working directory on the server. + /// + /// Sends a CWD command with the given path as argument to the + /// server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + std::string getWorkingDirectory(); + /// Returns the current working directory on the server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + void cdup(); + /// Moves one directory up from the current working directory + /// on teh server. + /// + /// Sends a CDUP command to the server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + void rename(const std::string& oldName, const std::string& newName); + /// Renames the file on the server given by oldName to newName. + /// + /// Sends a RNFR command, followed by a RNTO command to the server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + void remove(const std::string& path); + /// Deletes the file specified by path on the server. + /// + /// Sends a DELE command with path as argument to the server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + void createDirectory(const std::string& path); + /// Creates a new directory with the given path on the server. + /// + /// Sends a MKD command with path as argument to the server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + void removeDirectory(const std::string& path); + /// Removes the directory specified by path from the server. + /// + /// Sends a RMD command with path as argument to the server. + /// + /// Throws a FTPException in case of a FTP-specific error, or a + /// NetException in case of a general network communication failure. + + std::istream& beginDownload(const std::string& path); + /// Starts downloading the file with the given name. + /// After all data has been read from the returned stream, + /// endDownload() must be called to finish the download. + /// + /// A stream for reading the file's content is returned. + /// The stream is valid until endDownload() is called. + /// + /// Creates a data connection between the client and the + /// server. If passive mode is on, then the server waits for + /// a connection request from the client. Otherwise, the + /// client waits for a connection request from the server. + /// After establishing the data connection, a SocketStream + /// for transferring the data is created. + /// + /// If ASCII transfer mode is selected, the caller is + /// responsible for converting the received data to + /// the native text file format. + /// The InputLineEndingConverter class from the Foundation + /// library can be used for that purpose. + + void endDownload(); + /// Must be called to complete a download initiated with + /// beginDownload(). + + std::ostream& beginUpload(const std::string& path); + /// Starts uploading the file with the given name. + /// After all data has been written to the returned stream, + /// endUpload() must be called to finish the download. + /// + /// A stream for reading the file's content is returned. + /// The stream is valid until endUpload() is called. + /// + /// Creates a data connection between the client and the + /// server. If passive mode is on, then the server waits for + /// a connection request from the client. Otherwise, the + /// client waits for a connection request from the server. + /// After establishing the data connection, a SocketStream + /// for transferring the data is created. + /// + /// If ASCII transfer mode is selected, the caller is + /// responsible for converting the data to be sent + /// into network (CR-LF line endings) format. + /// The OutputLineEndingConverter class from the Foundation + /// library can be used for that purpose. + + void endUpload(); + /// Must be called to complete an upload initiated with + /// beginUpload(). + + std::istream& beginList(const std::string& path = "", bool extended = false); + /// Starts downloading a directory listing. + /// After all data has been read from the returned stream, + /// endList() must be called to finish the download. + /// + /// A stream for reading the directory data is returned. + /// The stream is valid until endList() is called. + /// + /// Optionally, a path to a directory or file can be specified. + /// According to the FTP prototol, if a path to a filename is + /// given, only information for the specific file is returned. + /// If a path to a directory is given, a listing of that directory + /// is returned. If no path is given, a listing of the current + /// working directory is returned. + /// + /// If extended is false, only a filenames (one per line) are + /// returned. Otherwise, a full directory listing including + /// file attributes is returned. The format of this listing + /// depends on the FTP server. No attempt is made to interpret + /// this data. + /// + /// Creates a data connection between the client and the + /// server. If passive mode is on, then the server waits for + /// a connection request from the client. Otherwise, the + /// client waits for a connection request from the server. + /// After establishing the data connection, a SocketStream + /// for transferring the data is created. + + void endList(); + /// Must be called to complete a directory listing download + /// initiated with beginList(). + + void abort(); + /// Aborts the download or upload currently in progress. + /// + /// Sends a TELNET IP/SYNCH sequence, followed by an ABOR + /// command to the server. + /// + /// A separate call to endDownload() or endUpload() is + /// not necessary. + + int sendCommand(const std::string& command, std::string& response); + /// Sends the given command verbatim to the server + /// and waits for a response. + + int sendCommand(const std::string& command, const std::string& arg, std::string& response); + /// Sends the given command verbatim to the server + /// and waits for a response. + +protected: + enum StatusClass + { + FTP_POSITIVE_PRELIMINARY = 1, + FTP_POSITIVE_COMPLETION = 2, + FTP_POSITIVE_INTERMEDIATE = 3, + FTP_TRANSIENT_NEGATIVE = 4, + FTP_PERMANENT_NEGATIVE = 5 + }; + enum + { + DEFAULT_TIMEOUT = 30000000 // 30 seconds default timeout for socket operations + }; + + static bool isPositivePreliminary(int status); + static bool isPositiveCompletion(int status); + static bool isPositiveIntermediate(int status); + static bool isTransientNegative(int status); + static bool isPermanentNegative(int status); + std::string extractPath(const std::string& response); + StreamSocket establishDataConnection(const std::string& command, const std::string& arg); + StreamSocket activeDataConnection(const std::string& command, const std::string& arg); + StreamSocket passiveDataConnection(const std::string& command, const std::string& arg); + void sendPortCommand(const SocketAddress& addr); + SocketAddress sendPassiveCommand(); + bool sendEPRT(const SocketAddress& addr); + void sendPORT(const SocketAddress& addr); + bool sendEPSV(SocketAddress& addr); + void sendPASV(SocketAddress& addr); + void parseAddress(const std::string& str, SocketAddress& addr); + void parseExtAddress(const std::string& str, SocketAddress& addr); + void endTransfer(); + +private: + FTPClientSession(); + FTPClientSession(const FTPClientSession&); + FTPClientSession& operator = (const FTPClientSession&); + + DialogSocket _controlSocket; + SocketStream* _pDataStream; + bool _passiveMode; + FileType _fileType; + bool _supports1738; + bool _isOpen; + Poco::Timespan _timeout; +}; + + +// +// inlines +// +inline bool FTPClientSession::isPositivePreliminary(int status) +{ + return status/100 == FTP_POSITIVE_PRELIMINARY; +} + + +inline bool FTPClientSession::isPositiveCompletion(int status) +{ + return status/100 == FTP_POSITIVE_COMPLETION; +} + + +inline bool FTPClientSession::isPositiveIntermediate(int status) +{ + return status/100 == FTP_POSITIVE_INTERMEDIATE; +} + + +inline bool FTPClientSession::isTransientNegative(int status) +{ + return status/100 == FTP_TRANSIENT_NEGATIVE; +} + + +inline bool FTPClientSession::isPermanentNegative(int status) +{ + return status/100 == FTP_PERMANENT_NEGATIVE; +} + + +} } // namespace Poco::Net + + +#endif // Net_FTPClientSession_INCLUDED diff --git a/Net/include/Poco/Net/FTPStreamFactory.h b/Net/include/Poco/Net/FTPStreamFactory.h index a871d6733..e5878408b 100644 --- a/Net/include/Poco/Net/FTPStreamFactory.h +++ b/Net/include/Poco/Net/FTPStreamFactory.h @@ -1,138 +1,138 @@ -// -// FTPStreamFactory.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/FTPStreamFactory.h#1 $ -// -// Library: Net -// Package: FTP -// Module: FTPStreamFactory -// -// Definition of the FTPStreamFactory 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_FTPStreamFactory_INCLUDED -#define Net_FTPStreamFactory_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPSession.h" -#include "Poco/URIStreamFactory.h" - - -namespace Poco { -namespace Net { - - -class Net_API FTPPasswordProvider - /// The base class for all password providers. - /// An instance of a subclass of this class can be - /// registered with the FTPStreamFactory to - /// provide a password -{ -public: - virtual std::string password(const std::string& username, const std::string& host) = 0; - /// Provide the password for the given user on the given host. - -protected: - FTPPasswordProvider(); - virtual ~FTPPasswordProvider(); -}; - - -class Net_API FTPStreamFactory: public Poco::URIStreamFactory - /// An implementation of the URIStreamFactory interface - /// that handles File Transfer Protocol (ftp) URIs. - /// - /// The URI's path may end with an optional type specification - /// in the form (;type=), where is - /// one of a, i or d. If type=a, the file identified by the path - /// is transferred in ASCII (text) mode. If type=i, the file - /// is transferred in Image (binary) mode. If type=d, a directory - /// listing (in NLST format) is returned. This corresponds with - /// the FTP URL format specified in RFC 1738. - /// - /// If the URI does not contain a username and password, the - /// username "anonymous" and the password " -{ -public: - FTPStreamFactory(); - /// Creates the FTPStreamFactory. - - ~FTPStreamFactory(); - /// Destroys the FTPStreamFactory. - - std::istream* open(const Poco::URI& uri); - /// Creates and opens a HTTP stream for the given URI. - /// The URI must be a ftp://... URI. - /// - /// Throws a NetException if anything goes wrong. - - static void setAnonymousPassword(const std::string& password); - /// Sets the password used for anonymous FTP. - /// - /// WARNING: Setting the anonymous password is not - /// thread-safe, so it's best to call this method - /// during application initialization, before the - /// FTPStreamFactory is used for the first time. - - static const std::string& getAnonymousPassword(); - /// Returns the password used for anonymous FTP. - - static void setPasswordProvider(FTPPasswordProvider* pProvider); - /// Sets the FTPPasswordProvider. If NULL is given, - /// no password provider is used. - /// - /// WARNING: Setting the password provider is not - /// thread-safe, so it's best to call this method - /// during application initialization, before the - /// FTPStreamFactory is used for the first time. - - static FTPPasswordProvider* getPasswordProvider(); - /// Returns the FTPPasswordProvider currently in use, - /// or NULL if no one has been set. - - static void registerFactory(); - /// Registers the FTPStreamFactory with the - /// default URIStreamOpener instance. - -protected: - static void splitUserInfo(const std::string& userInfo, std::string& username, std::string& password); - static void getUserInfo(const Poco::URI& uri, std::string& username, std::string& password); - static void getPathAndType(const Poco::URI& uri, std::string& path, char& type); - -private: - static std::string _anonymousPassword; - static FTPPasswordProvider* _pPasswordProvider; -}; - - -} } // namespace Poco::Net - - -#endif // Net_FTPStreamFactory_INCLUDED +// +// FTPStreamFactory.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/FTPStreamFactory.h#1 $ +// +// Library: Net +// Package: FTP +// Module: FTPStreamFactory +// +// Definition of the FTPStreamFactory 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_FTPStreamFactory_INCLUDED +#define Net_FTPStreamFactory_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPSession.h" +#include "Poco/URIStreamFactory.h" + + +namespace Poco { +namespace Net { + + +class Net_API FTPPasswordProvider + /// The base class for all password providers. + /// An instance of a subclass of this class can be + /// registered with the FTPStreamFactory to + /// provide a password +{ +public: + virtual std::string password(const std::string& username, const std::string& host) = 0; + /// Provide the password for the given user on the given host. + +protected: + FTPPasswordProvider(); + virtual ~FTPPasswordProvider(); +}; + + +class Net_API FTPStreamFactory: public Poco::URIStreamFactory + /// An implementation of the URIStreamFactory interface + /// that handles File Transfer Protocol (ftp) URIs. + /// + /// The URI's path may end with an optional type specification + /// in the form (;type=), where is + /// one of a, i or d. If type=a, the file identified by the path + /// is transferred in ASCII (text) mode. If type=i, the file + /// is transferred in Image (binary) mode. If type=d, a directory + /// listing (in NLST format) is returned. This corresponds with + /// the FTP URL format specified in RFC 1738. + /// + /// If the URI does not contain a username and password, the + /// username "anonymous" and the password " +{ +public: + FTPStreamFactory(); + /// Creates the FTPStreamFactory. + + ~FTPStreamFactory(); + /// Destroys the FTPStreamFactory. + + std::istream* open(const Poco::URI& uri); + /// Creates and opens a HTTP stream for the given URI. + /// The URI must be a ftp://... URI. + /// + /// Throws a NetException if anything goes wrong. + + static void setAnonymousPassword(const std::string& password); + /// Sets the password used for anonymous FTP. + /// + /// WARNING: Setting the anonymous password is not + /// thread-safe, so it's best to call this method + /// during application initialization, before the + /// FTPStreamFactory is used for the first time. + + static const std::string& getAnonymousPassword(); + /// Returns the password used for anonymous FTP. + + static void setPasswordProvider(FTPPasswordProvider* pProvider); + /// Sets the FTPPasswordProvider. If NULL is given, + /// no password provider is used. + /// + /// WARNING: Setting the password provider is not + /// thread-safe, so it's best to call this method + /// during application initialization, before the + /// FTPStreamFactory is used for the first time. + + static FTPPasswordProvider* getPasswordProvider(); + /// Returns the FTPPasswordProvider currently in use, + /// or NULL if no one has been set. + + static void registerFactory(); + /// Registers the FTPStreamFactory with the + /// default URIStreamOpener instance. + +protected: + static void splitUserInfo(const std::string& userInfo, std::string& username, std::string& password); + static void getUserInfo(const Poco::URI& uri, std::string& username, std::string& password); + static void getPathAndType(const Poco::URI& uri, std::string& path, char& type); + +private: + static std::string _anonymousPassword; + static FTPPasswordProvider* _pPasswordProvider; +}; + + +} } // namespace Poco::Net + + +#endif // Net_FTPStreamFactory_INCLUDED diff --git a/Net/include/Poco/Net/FilePartSource.h b/Net/include/Poco/Net/FilePartSource.h index 833f1ba4a..ffd24046d 100644 --- a/Net/include/Poco/Net/FilePartSource.h +++ b/Net/include/Poco/Net/FilePartSource.h @@ -1,88 +1,88 @@ -// -// FilePartSource.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/FilePartSource.h#1 $ -// -// Library: Net -// Package: Messages -// Module: FilePartSource -// -// Definition of the FilePartSource 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_FilePartSource_INCLUDED -#define Net_FilePartSource_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/PartSource.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API FilePartSource: public PartSource - /// An implementation of PartSource for - /// plain files. -{ -public: - FilePartSource(const std::string& path); - /// Creates the FilePartSource for the given path. - /// - /// The MIME type is set to application/octet-stream. - /// - /// Throws an OpenFileException if the file cannot be opened. - - FilePartSource(const std::string& path, const std::string& mediaType); - /// Creates the FilePartSource for the given - /// path and MIME type. - /// - /// Throws an OpenFileException if the file cannot be opened. - - ~FilePartSource(); - /// Destroys the FilePartSource. - - std::istream& stream(); - /// Returns a file input stream for the given file. - - const std::string& filename(); - /// Returns the filename portion of the path. - -private: - std::ifstream _istr; - std::string _filename; -}; - - -} } // namespace Poco::Net - - -#endif // Net_FilePartSource_INCLUDED +// +// FilePartSource.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/FilePartSource.h#1 $ +// +// Library: Net +// Package: Messages +// Module: FilePartSource +// +// Definition of the FilePartSource 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_FilePartSource_INCLUDED +#define Net_FilePartSource_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/PartSource.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API FilePartSource: public PartSource + /// An implementation of PartSource for + /// plain files. +{ +public: + FilePartSource(const std::string& path); + /// Creates the FilePartSource for the given path. + /// + /// The MIME type is set to application/octet-stream. + /// + /// Throws an OpenFileException if the file cannot be opened. + + FilePartSource(const std::string& path, const std::string& mediaType); + /// Creates the FilePartSource for the given + /// path and MIME type. + /// + /// Throws an OpenFileException if the file cannot be opened. + + ~FilePartSource(); + /// Destroys the FilePartSource. + + std::istream& stream(); + /// Returns a file input stream for the given file. + + const std::string& filename(); + /// Returns the filename portion of the path. + +private: + std::ifstream _istr; + std::string _filename; +}; + + +} } // namespace Poco::Net + + +#endif // Net_FilePartSource_INCLUDED diff --git a/Net/include/Poco/Net/HTMLForm.h b/Net/include/Poco/Net/HTMLForm.h index 09228dfb3..14a5a87d6 100644 --- a/Net/include/Poco/Net/HTMLForm.h +++ b/Net/include/Poco/Net/HTMLForm.h @@ -1,212 +1,212 @@ -// -// HTMLForm.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTMLForm.h#1 $ -// -// Library: Net -// Package: HTML -// Module: HTMLForm -// -// Definition of the HTMLForm 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_HTMLForm_INCLUDED -#define Net_HTMLForm_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/NameValueCollection.h" -#include -#include -#include - - -namespace Poco { -namespace Net { - - -class HTTPRequest; -class PartHandler; -class PartSource; - - -class Net_API HTMLForm: public NameValueCollection - /// HTMLForm is a helper class for working with HTML forms, - /// both on the client and on the server side. -{ -public: - HTMLForm(); - /// Creates an empty HTMLForm and sets the - /// encoding to "application/x-www-form-urlencoded". - - explicit HTMLForm(const std::string& encoding); - /// Creates an empty HTMLForm that uses - /// the given encoding. - /// - /// Encoding must be either "application/x-www-form-urlencoded" - /// (which is the default) or "multipart/form-data". - - HTMLForm(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler); - /// Creates a HTMLForm from the given HTTP request. - /// - /// Uploaded files are passed to the given PartHandler. - - HTMLForm(const HTTPRequest& request, std::istream& requestBody); - /// Creates a HTMLForm from the given HTTP request. - /// - /// Uploaded files are silently discarded. - - explicit HTMLForm(const HTTPRequest& request); - /// Creates a HTMLForm from the given HTTP request. - /// - /// The request must be a GET request and the form data - /// must be in the query string (URL encoded). - /// - /// For POST requests, you must use one of the constructors - /// taking an additional input stream for the request body. - - ~HTMLForm(); - /// Destroys the HTMLForm. - - void setEncoding(const std::string& encoding); - /// Sets the encoding used for posting the form. - /// - /// Encoding must be either "application/x-www-form-urlencoded" - /// (which is the default) or "multipart/form-data". - - const std::string& getEncoding() const; - /// Returns the encoding used for posting the form. - - void addPart(const std::string& name, PartSource* pSource); - /// Adds an part/attachment (file upload) to the form. - /// - /// The form takes ownership of the PartSource and deletes it - /// when it is no longer needed. - /// - /// The part will only be sent if the encoding - /// set for the form is "multipart/form-data" - - void load(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler); - /// Reads the form data from the given HTTP request. - /// - /// Uploaded files are passed to the given PartHandler. - - void load(const HTTPRequest& request, std::istream& requestBody); - /// Reads the form data from the given HTTP request. - /// - /// Uploaded files are silently discarded. - - void load(const HTTPRequest& request); - /// Reads the form data from the given HTTP request. - /// - /// The request must be a GET request and the form data - /// must be in the query string (URL encoded). - /// - /// For POST requests, you must use one of the overloads - /// taking an additional input stream for the request body. - - void read(std::istream& istr, PartHandler& handler); - /// Reads the form data from the given input stream. - /// - /// The form data read from the stream must be - /// in the encoding specified for the form. - - void prepareSubmit(HTTPRequest& request); - /// Fills out the request object for submitting the form. - /// - /// If the request method is GET, the encoded form is appended to the - /// request URI as query string. Otherwise (the method is - /// POST), the form's content type is set to the form's encoding. - /// The form's parameters must be written to the - /// request body separately, with a call to write. - /// If the request's HTTP version is HTTP/1.0: - /// - persistent connections are disabled - /// - the content transfer encoding is set to identity encoding - /// Otherwise, if the request's HTTP version is HTTP/1.1: - /// - the request's persistent connection state is left unchanged - /// - the content transfer encoding is set to chunked - - void write(std::ostream& ostr, const std::string& boundary); - /// Writes the form data to the given output stream, - /// using the specified encoding. - - void write(std::ostream& ostr); - /// Writes the form data to the given output stream, - /// using the specified encoding. - - const std::string& boundary() const; - /// Returns the MIME boundary used for writing - /// multipart form data. - - static const std::string ENCODING_URL; /// "application/x-www-form-urlencoded" - static const std::string ENCODING_MULTIPART; /// "multipart/form-data" - -protected: - void readUrl(std::istream& istr); - void readMultipart(std::istream& istr, PartHandler& handler); - void writeUrl(std::ostream& ostr); - void writeMultipart(std::ostream& ostr); - -private: - HTMLForm(const HTMLForm&); - HTMLForm& operator = (const HTMLForm&); - - struct Part - { - std::string name; - PartSource* pSource; - }; - - typedef std::vector PartVec; - - std::string _encoding; - std::string _boundary; - PartVec _parts; -}; - - -// -// inlines -// -inline const std::string& HTMLForm::getEncoding() const -{ - return _encoding; -} - - -inline const std::string& HTMLForm::boundary() const -{ - return _boundary; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTMLForm_INCLUDED +// +// HTMLForm.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTMLForm.h#1 $ +// +// Library: Net +// Package: HTML +// Module: HTMLForm +// +// Definition of the HTMLForm 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_HTMLForm_INCLUDED +#define Net_HTMLForm_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/NameValueCollection.h" +#include +#include +#include + + +namespace Poco { +namespace Net { + + +class HTTPRequest; +class PartHandler; +class PartSource; + + +class Net_API HTMLForm: public NameValueCollection + /// HTMLForm is a helper class for working with HTML forms, + /// both on the client and on the server side. +{ +public: + HTMLForm(); + /// Creates an empty HTMLForm and sets the + /// encoding to "application/x-www-form-urlencoded". + + explicit HTMLForm(const std::string& encoding); + /// Creates an empty HTMLForm that uses + /// the given encoding. + /// + /// Encoding must be either "application/x-www-form-urlencoded" + /// (which is the default) or "multipart/form-data". + + HTMLForm(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler); + /// Creates a HTMLForm from the given HTTP request. + /// + /// Uploaded files are passed to the given PartHandler. + + HTMLForm(const HTTPRequest& request, std::istream& requestBody); + /// Creates a HTMLForm from the given HTTP request. + /// + /// Uploaded files are silently discarded. + + explicit HTMLForm(const HTTPRequest& request); + /// Creates a HTMLForm from the given HTTP request. + /// + /// The request must be a GET request and the form data + /// must be in the query string (URL encoded). + /// + /// For POST requests, you must use one of the constructors + /// taking an additional input stream for the request body. + + ~HTMLForm(); + /// Destroys the HTMLForm. + + void setEncoding(const std::string& encoding); + /// Sets the encoding used for posting the form. + /// + /// Encoding must be either "application/x-www-form-urlencoded" + /// (which is the default) or "multipart/form-data". + + const std::string& getEncoding() const; + /// Returns the encoding used for posting the form. + + void addPart(const std::string& name, PartSource* pSource); + /// Adds an part/attachment (file upload) to the form. + /// + /// The form takes ownership of the PartSource and deletes it + /// when it is no longer needed. + /// + /// The part will only be sent if the encoding + /// set for the form is "multipart/form-data" + + void load(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler); + /// Reads the form data from the given HTTP request. + /// + /// Uploaded files are passed to the given PartHandler. + + void load(const HTTPRequest& request, std::istream& requestBody); + /// Reads the form data from the given HTTP request. + /// + /// Uploaded files are silently discarded. + + void load(const HTTPRequest& request); + /// Reads the form data from the given HTTP request. + /// + /// The request must be a GET request and the form data + /// must be in the query string (URL encoded). + /// + /// For POST requests, you must use one of the overloads + /// taking an additional input stream for the request body. + + void read(std::istream& istr, PartHandler& handler); + /// Reads the form data from the given input stream. + /// + /// The form data read from the stream must be + /// in the encoding specified for the form. + + void prepareSubmit(HTTPRequest& request); + /// Fills out the request object for submitting the form. + /// + /// If the request method is GET, the encoded form is appended to the + /// request URI as query string. Otherwise (the method is + /// POST), the form's content type is set to the form's encoding. + /// The form's parameters must be written to the + /// request body separately, with a call to write. + /// If the request's HTTP version is HTTP/1.0: + /// - persistent connections are disabled + /// - the content transfer encoding is set to identity encoding + /// Otherwise, if the request's HTTP version is HTTP/1.1: + /// - the request's persistent connection state is left unchanged + /// - the content transfer encoding is set to chunked + + void write(std::ostream& ostr, const std::string& boundary); + /// Writes the form data to the given output stream, + /// using the specified encoding. + + void write(std::ostream& ostr); + /// Writes the form data to the given output stream, + /// using the specified encoding. + + const std::string& boundary() const; + /// Returns the MIME boundary used for writing + /// multipart form data. + + static const std::string ENCODING_URL; /// "application/x-www-form-urlencoded" + static const std::string ENCODING_MULTIPART; /// "multipart/form-data" + +protected: + void readUrl(std::istream& istr); + void readMultipart(std::istream& istr, PartHandler& handler); + void writeUrl(std::ostream& ostr); + void writeMultipart(std::ostream& ostr); + +private: + HTMLForm(const HTMLForm&); + HTMLForm& operator = (const HTMLForm&); + + struct Part + { + std::string name; + PartSource* pSource; + }; + + typedef std::vector PartVec; + + std::string _encoding; + std::string _boundary; + PartVec _parts; +}; + + +// +// inlines +// +inline const std::string& HTMLForm::getEncoding() const +{ + return _encoding; +} + + +inline const std::string& HTMLForm::boundary() const +{ + return _boundary; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTMLForm_INCLUDED diff --git a/Net/include/Poco/Net/HTTPBasicCredentials.h b/Net/include/Poco/Net/HTTPBasicCredentials.h index e4b8e49d3..8809ae4d1 100644 --- a/Net/include/Poco/Net/HTTPBasicCredentials.h +++ b/Net/include/Poco/Net/HTTPBasicCredentials.h @@ -1,119 +1,119 @@ -// -// HTTPBasicCredentials.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPBasicCredentials.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPBasicCredentials -// -// Definition of the HTTPBasicCredentials 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_HTTPBasicCredentials_INCLUDED -#define Net_HTTPBasicCredentials_INCLUDED - - -#include "Poco/Net/Net.h" - - -namespace Poco { -namespace Net { - - -class HTTPRequest; - - -class Net_API HTTPBasicCredentials - /// This is a utility class for working with - /// HTTP Basic Authentication in HTTPRequest - /// objects. -{ -public: - HTTPBasicCredentials(); - /// Creates an empty HTTPBasicCredentials object. - - HTTPBasicCredentials(const std::string& username, const std::string& password); - /// Creates a HTTPBasicCredentials object with the given username and password. - - explicit HTTPBasicCredentials(const HTTPRequest& request); - /// Creates a HTTPBasicCredentials object with the authentication information - /// from the given request. - /// - /// Throws a NotAuthenticatedException if the request does - /// not contain basic authentication information. - - ~HTTPBasicCredentials(); - /// Destroys the HTTPBasicCredentials. - - void setUsername(const std::string& username); - /// Sets the username. - - const std::string& getUsername() const; - /// Returns the username. - - void setPassword(const std::string& password); - /// Sets the password. - - const std::string& getPassword() const; - /// Returns the password. - - void authenticate(HTTPRequest& request); - /// Adds authentication information to the given HTTPRequest. - - static const std::string SCHEME; - -private: - HTTPBasicCredentials(const HTTPBasicCredentials&); - HTTPBasicCredentials& operator = (const HTTPBasicCredentials); - - std::string _username; - std::string _password; -}; - - -// -// inlines -// -inline const std::string& HTTPBasicCredentials::getUsername() const -{ - return _username; -} - - -inline const std::string& HTTPBasicCredentials::getPassword() const -{ - return _password; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPBasicCredentials_INCLUDED +// +// HTTPBasicCredentials.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPBasicCredentials.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPBasicCredentials +// +// Definition of the HTTPBasicCredentials 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_HTTPBasicCredentials_INCLUDED +#define Net_HTTPBasicCredentials_INCLUDED + + +#include "Poco/Net/Net.h" + + +namespace Poco { +namespace Net { + + +class HTTPRequest; + + +class Net_API HTTPBasicCredentials + /// This is a utility class for working with + /// HTTP Basic Authentication in HTTPRequest + /// objects. +{ +public: + HTTPBasicCredentials(); + /// Creates an empty HTTPBasicCredentials object. + + HTTPBasicCredentials(const std::string& username, const std::string& password); + /// Creates a HTTPBasicCredentials object with the given username and password. + + explicit HTTPBasicCredentials(const HTTPRequest& request); + /// Creates a HTTPBasicCredentials object with the authentication information + /// from the given request. + /// + /// Throws a NotAuthenticatedException if the request does + /// not contain basic authentication information. + + ~HTTPBasicCredentials(); + /// Destroys the HTTPBasicCredentials. + + void setUsername(const std::string& username); + /// Sets the username. + + const std::string& getUsername() const; + /// Returns the username. + + void setPassword(const std::string& password); + /// Sets the password. + + const std::string& getPassword() const; + /// Returns the password. + + void authenticate(HTTPRequest& request); + /// Adds authentication information to the given HTTPRequest. + + static const std::string SCHEME; + +private: + HTTPBasicCredentials(const HTTPBasicCredentials&); + HTTPBasicCredentials& operator = (const HTTPBasicCredentials); + + std::string _username; + std::string _password; +}; + + +// +// inlines +// +inline const std::string& HTTPBasicCredentials::getUsername() const +{ + return _username; +} + + +inline const std::string& HTTPBasicCredentials::getPassword() const +{ + return _password; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPBasicCredentials_INCLUDED diff --git a/Net/include/Poco/Net/HTTPBasicStreamBuf.h b/Net/include/Poco/Net/HTTPBasicStreamBuf.h index e045c3eea..bcd56a909 100644 --- a/Net/include/Poco/Net/HTTPBasicStreamBuf.h +++ b/Net/include/Poco/Net/HTTPBasicStreamBuf.h @@ -1,58 +1,58 @@ -// -// HTTPBasicStreamBuf.h -// -// $Id: //poco/Main/template/class.h#4 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPBasicStreamBuf -// -// Definition of the HTTPBasicStreamBuf 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_HTTPBasicStreamBuf_INCLUDED -#define Net_HTTPBasicStreamBuf_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/BufferedStreamBuf.h" -#include "Poco/Net/HTTPBufferAllocator.h" - - -namespace Poco { -namespace Net { - - -typedef Poco::BasicBufferedStreamBuf, HTTPBufferAllocator> HTTPBasicStreamBuf; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPBasicStreamBuf_INCLUDED +// +// HTTPBasicStreamBuf.h +// +// $Id: //poco/Main/template/class.h#4 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPBasicStreamBuf +// +// Definition of the HTTPBasicStreamBuf 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_HTTPBasicStreamBuf_INCLUDED +#define Net_HTTPBasicStreamBuf_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/BufferedStreamBuf.h" +#include "Poco/Net/HTTPBufferAllocator.h" + + +namespace Poco { +namespace Net { + + +typedef Poco::BasicBufferedStreamBuf, HTTPBufferAllocator> HTTPBasicStreamBuf; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPBasicStreamBuf_INCLUDED diff --git a/Net/include/Poco/Net/HTTPBufferAllocator.h b/Net/include/Poco/Net/HTTPBufferAllocator.h index 63d2fd75a..22d7c8783 100644 --- a/Net/include/Poco/Net/HTTPBufferAllocator.h +++ b/Net/include/Poco/Net/HTTPBufferAllocator.h @@ -1,72 +1,72 @@ -// -// HTTPBufferAllocator.h -// -// $Id: //poco/Main/template/class.h#4 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPBufferAllocator -// -// Definition of the HTTPBufferAllocator 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_HTTPBufferAllocator_INCLUDED -#define Net_HTTPBufferAllocator_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/MemoryPool.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API HTTPBufferAllocator - /// A BufferAllocator for HTTP streams. -{ -public: - static char* allocate(std::streamsize size); - static void deallocate(char* ptr, std::streamsize size); - - enum - { - BUFFER_SIZE = 4096 - }; - -private: - static Poco::MemoryPool _pool; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPBufferAllocator_INCLUDED +// +// HTTPBufferAllocator.h +// +// $Id: //poco/Main/template/class.h#4 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPBufferAllocator +// +// Definition of the HTTPBufferAllocator 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_HTTPBufferAllocator_INCLUDED +#define Net_HTTPBufferAllocator_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/MemoryPool.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API HTTPBufferAllocator + /// A BufferAllocator for HTTP streams. +{ +public: + static char* allocate(std::streamsize size); + static void deallocate(char* ptr, std::streamsize size); + + enum + { + BUFFER_SIZE = 4096 + }; + +private: + static Poco::MemoryPool _pool; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPBufferAllocator_INCLUDED diff --git a/Net/include/Poco/Net/HTTPChunkedStream.h b/Net/include/Poco/Net/HTTPChunkedStream.h index 1697f4488..16ce8b832 100644 --- a/Net/include/Poco/Net/HTTPChunkedStream.h +++ b/Net/include/Poco/Net/HTTPChunkedStream.h @@ -1,125 +1,125 @@ -// -// HTTPChunkedStream.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPChunkedStream.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPChunkedStream -// -// Definition of the HTTPChunkedStream 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_HTTPChunkedStream_INCLUDED -#define Net_HTTPChunkedStream_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPBasicStreamBuf.h" -#include "Poco/MemoryPool.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class HTTPSession; - - -class Net_API HTTPChunkedStreamBuf: public HTTPBasicStreamBuf - /// This is the streambuf class used for reading and writing - /// HTTP message bodies in chunked transfer coding. -{ -public: - typedef HTTPBasicStreamBuf::openmode openmode; - - HTTPChunkedStreamBuf(HTTPSession& session, openmode mode); - ~HTTPChunkedStreamBuf(); - void close(); - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - HTTPSession& _session; - openmode _mode; - std::streamsize _chunk; -}; - - -class Net_API HTTPChunkedIOS: public virtual std::ios - /// The base class for HTTPInputStream. -{ -public: - HTTPChunkedIOS(HTTPSession& session, HTTPChunkedStreamBuf::openmode mode); - ~HTTPChunkedIOS(); - HTTPChunkedStreamBuf* rdbuf(); - -protected: - HTTPChunkedStreamBuf _buf; -}; - - -class Net_API HTTPChunkedInputStream: public HTTPChunkedIOS, public std::istream - /// This class is for internal use by HTTPSession only. -{ -public: - HTTPChunkedInputStream(HTTPSession& session); - ~HTTPChunkedInputStream(); - - void* operator new(size_t size); - void operator delete(void* ptr); - -private: - static Poco::MemoryPool _pool; -}; - - -class Net_API HTTPChunkedOutputStream: public HTTPChunkedIOS, public std::ostream - /// This class is for internal use by HTTPSession only. -{ -public: - HTTPChunkedOutputStream(HTTPSession& session); - ~HTTPChunkedOutputStream(); - - void* operator new(size_t size); - void operator delete(void* ptr); - -private: - static Poco::MemoryPool _pool; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPChunkedStream_INCLUDED +// +// HTTPChunkedStream.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPChunkedStream.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPChunkedStream +// +// Definition of the HTTPChunkedStream 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_HTTPChunkedStream_INCLUDED +#define Net_HTTPChunkedStream_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPBasicStreamBuf.h" +#include "Poco/MemoryPool.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class HTTPSession; + + +class Net_API HTTPChunkedStreamBuf: public HTTPBasicStreamBuf + /// This is the streambuf class used for reading and writing + /// HTTP message bodies in chunked transfer coding. +{ +public: + typedef HTTPBasicStreamBuf::openmode openmode; + + HTTPChunkedStreamBuf(HTTPSession& session, openmode mode); + ~HTTPChunkedStreamBuf(); + void close(); + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + HTTPSession& _session; + openmode _mode; + std::streamsize _chunk; +}; + + +class Net_API HTTPChunkedIOS: public virtual std::ios + /// The base class for HTTPInputStream. +{ +public: + HTTPChunkedIOS(HTTPSession& session, HTTPChunkedStreamBuf::openmode mode); + ~HTTPChunkedIOS(); + HTTPChunkedStreamBuf* rdbuf(); + +protected: + HTTPChunkedStreamBuf _buf; +}; + + +class Net_API HTTPChunkedInputStream: public HTTPChunkedIOS, public std::istream + /// This class is for internal use by HTTPSession only. +{ +public: + HTTPChunkedInputStream(HTTPSession& session); + ~HTTPChunkedInputStream(); + + void* operator new(size_t size); + void operator delete(void* ptr); + +private: + static Poco::MemoryPool _pool; +}; + + +class Net_API HTTPChunkedOutputStream: public HTTPChunkedIOS, public std::ostream + /// This class is for internal use by HTTPSession only. +{ +public: + HTTPChunkedOutputStream(HTTPSession& session); + ~HTTPChunkedOutputStream(); + + void* operator new(size_t size); + void operator delete(void* ptr); + +private: + static Poco::MemoryPool _pool; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPChunkedStream_INCLUDED diff --git a/Net/include/Poco/Net/HTTPClientSession.h b/Net/include/Poco/Net/HTTPClientSession.h index 3af8a7c30..890fe0437 100644 --- a/Net/include/Poco/Net/HTTPClientSession.h +++ b/Net/include/Poco/Net/HTTPClientSession.h @@ -1,263 +1,263 @@ -// -// HTTPClientSession.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPClientSession.h#1 $ -// -// Library: Net -// Package: HTTPClient -// Module: HTTPClientSession -// -// Definition of the HTTPClientSession 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_HTTPClientSession_INCLUDED -#define Net_HTTPClientSession_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPSession.h" -#include "Poco/Net/SocketAddress.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class HTTPRequest; -class HTTPResponse; - - -class Net_API HTTPClientSession: public HTTPSession - /// This class implements the client-side of - /// a HTTP session. - /// - /// To send a HTTP request to a HTTP server, first - /// instantiate a HTTPClientSession object and - /// specify the server's host name and port number. - /// - /// Then create a HTTPRequest object, fill it accordingly, - /// and pass it as argument to the sendRequst() method. - /// - /// sendRequest() will return an output stream that can - /// be used to send the request body, if there is any. - /// - /// After you are done sending the request body, create - /// a HTTPResponse object and pass it to receiveResponse(). - /// - /// This will return an input stream that can be used to - /// read the response body. - /// - /// See RFC 2616 for more - /// information about the HTTP protocol. -{ -public: - HTTPClientSession(); - /// Creates an unconnected HTTPClientSession. - - explicit HTTPClientSession(const StreamSocket& socket); - /// Creates a HTTPClientSession using the given socket. - /// The socket must not be connected. The session - /// takes ownership of the socket. - - explicit HTTPClientSession(const SocketAddress& address); - /// Creates a HTTPClientSession using the given address. - - HTTPClientSession(const std::string& host, Poco::UInt16 port = HTTPSession::HTTP_PORT); - /// Creates a HTTPClientSession using the given host and port. - - virtual ~HTTPClientSession(); - /// Destroys the HTTPClientSession and closes - /// the underlying socket. - - void setHost(const std::string& host); - /// Sets the host name of the target HTTP server. - /// - /// The host must not be changed once there is an - /// open connection to the server. - - const std::string& getHost() const; - /// Returns the host name of the target HTTP server. - - void setPort(Poco::UInt16 port); - /// Sets the port number of the target HTTP server. - /// - /// The port number must not be changed once there is an - /// open connection to the server. - - Poco::UInt16 getPort() const; - /// Returns the port number of the target HTTP server. - - void setProxy(const std::string& host, Poco::UInt16 port = HTTPSession::HTTP_PORT); - /// Sets the proxy host name and port number. - - void setProxyHost(const std::string& host); - /// Sets the host name of the proxy server. - - void setProxyPort(Poco::UInt16 port); - /// Sets the port number of the proxy server. - - const std::string& getProxyHost() const; - /// Returns the proxy host name. - - Poco::UInt16 getProxyPort() const; - /// Returns the proxy port number. - - virtual std::ostream& sendRequest(HTTPRequest& request); - /// Sends the header for the given HTTP request to - /// the server. - /// - /// The HTTPClientSession will set the request's - /// Host and Keep-Alive headers accordingly. - /// - /// The returned output stream can be used to write - /// the request body. The stream is valid until - /// receiveResponse() is called or the session - /// is destroyed. - - virtual std::istream& receiveResponse(HTTPResponse& response); - /// Receives the header for the response to the previous - /// HTTP request. - /// - /// The returned input stream can be used to read - /// the response body. The stream is valid until - /// sendRequest() is called or the session is - /// destroyed. - -protected: - void reconnect(); - /// Connects the underlying socket to the HTTP server. - - int write(const char* buffer, std::streamsize length); - /// Tries to re-connect if keep-alive is on. - - virtual std::string getHostInfo() const; - /// Returns the target host and port number for proxy requests. - - void deleteResponseStream(); - /// Deletes the response stream and sets it to 0. - - void deleteRequestStream(); - /// Deletes the request stream and sets it to 0. - - void setResponseStream(std::istream* pRespStream); - /// Sets the response stream iff _pResponseStream is 0. - - void setRequestStream(std::ostream* pRequestStream); - /// Sets the request stream iff _pRequestStream is 0. - - std::istream* getResponseStream() const; - /// Returns the currently set response stream. Can return 0. - - std::ostream* getRequestStream() const; - /// Returns the currently set request stream. Can return 0. - - void setReconnect(bool recon); - /// Sets _reconnect. - - void setExpectResponseBody(bool expect); - /// Sets _expectResponseBody. - - bool getExpectResponseBody() const; - /// Returns _expectResponseBody. - -private: - std::string _host; - Poco::UInt16 _port; - std::string _proxyHost; - Poco::UInt16 _proxyPort; - bool _reconnect; - bool _expectResponseBody; - std::ostream* _pRequestStream; - std::istream* _pResponseStream; -}; - - -// -// inlines -// -inline const std::string& HTTPClientSession::getHost() const -{ - return _host; -} - - -inline Poco::UInt16 HTTPClientSession::getPort() const -{ - return _port; -} - - -inline const std::string& HTTPClientSession::getProxyHost() const -{ - return _proxyHost; -} - - -inline Poco::UInt16 HTTPClientSession::getProxyPort() const -{ - return _proxyPort; -} - - -inline std::istream* HTTPClientSession::getResponseStream() const -{ - return _pResponseStream; -} - - -inline std::ostream* HTTPClientSession::getRequestStream() const -{ - return _pRequestStream; -} - - -inline void HTTPClientSession::setReconnect(bool recon) -{ - _reconnect = recon; -} - - -inline void HTTPClientSession::setExpectResponseBody(bool expect) -{ - _expectResponseBody = expect; -} - - -inline bool HTTPClientSession::getExpectResponseBody() const -{ - return _expectResponseBody; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPClientSession_INCLUDED +// +// HTTPClientSession.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPClientSession.h#1 $ +// +// Library: Net +// Package: HTTPClient +// Module: HTTPClientSession +// +// Definition of the HTTPClientSession 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_HTTPClientSession_INCLUDED +#define Net_HTTPClientSession_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPSession.h" +#include "Poco/Net/SocketAddress.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class HTTPRequest; +class HTTPResponse; + + +class Net_API HTTPClientSession: public HTTPSession + /// This class implements the client-side of + /// a HTTP session. + /// + /// To send a HTTP request to a HTTP server, first + /// instantiate a HTTPClientSession object and + /// specify the server's host name and port number. + /// + /// Then create a HTTPRequest object, fill it accordingly, + /// and pass it as argument to the sendRequst() method. + /// + /// sendRequest() will return an output stream that can + /// be used to send the request body, if there is any. + /// + /// After you are done sending the request body, create + /// a HTTPResponse object and pass it to receiveResponse(). + /// + /// This will return an input stream that can be used to + /// read the response body. + /// + /// See RFC 2616 for more + /// information about the HTTP protocol. +{ +public: + HTTPClientSession(); + /// Creates an unconnected HTTPClientSession. + + explicit HTTPClientSession(const StreamSocket& socket); + /// Creates a HTTPClientSession using the given socket. + /// The socket must not be connected. The session + /// takes ownership of the socket. + + explicit HTTPClientSession(const SocketAddress& address); + /// Creates a HTTPClientSession using the given address. + + HTTPClientSession(const std::string& host, Poco::UInt16 port = HTTPSession::HTTP_PORT); + /// Creates a HTTPClientSession using the given host and port. + + virtual ~HTTPClientSession(); + /// Destroys the HTTPClientSession and closes + /// the underlying socket. + + void setHost(const std::string& host); + /// Sets the host name of the target HTTP server. + /// + /// The host must not be changed once there is an + /// open connection to the server. + + const std::string& getHost() const; + /// Returns the host name of the target HTTP server. + + void setPort(Poco::UInt16 port); + /// Sets the port number of the target HTTP server. + /// + /// The port number must not be changed once there is an + /// open connection to the server. + + Poco::UInt16 getPort() const; + /// Returns the port number of the target HTTP server. + + void setProxy(const std::string& host, Poco::UInt16 port = HTTPSession::HTTP_PORT); + /// Sets the proxy host name and port number. + + void setProxyHost(const std::string& host); + /// Sets the host name of the proxy server. + + void setProxyPort(Poco::UInt16 port); + /// Sets the port number of the proxy server. + + const std::string& getProxyHost() const; + /// Returns the proxy host name. + + Poco::UInt16 getProxyPort() const; + /// Returns the proxy port number. + + virtual std::ostream& sendRequest(HTTPRequest& request); + /// Sends the header for the given HTTP request to + /// the server. + /// + /// The HTTPClientSession will set the request's + /// Host and Keep-Alive headers accordingly. + /// + /// The returned output stream can be used to write + /// the request body. The stream is valid until + /// receiveResponse() is called or the session + /// is destroyed. + + virtual std::istream& receiveResponse(HTTPResponse& response); + /// Receives the header for the response to the previous + /// HTTP request. + /// + /// The returned input stream can be used to read + /// the response body. The stream is valid until + /// sendRequest() is called or the session is + /// destroyed. + +protected: + void reconnect(); + /// Connects the underlying socket to the HTTP server. + + int write(const char* buffer, std::streamsize length); + /// Tries to re-connect if keep-alive is on. + + virtual std::string getHostInfo() const; + /// Returns the target host and port number for proxy requests. + + void deleteResponseStream(); + /// Deletes the response stream and sets it to 0. + + void deleteRequestStream(); + /// Deletes the request stream and sets it to 0. + + void setResponseStream(std::istream* pRespStream); + /// Sets the response stream iff _pResponseStream is 0. + + void setRequestStream(std::ostream* pRequestStream); + /// Sets the request stream iff _pRequestStream is 0. + + std::istream* getResponseStream() const; + /// Returns the currently set response stream. Can return 0. + + std::ostream* getRequestStream() const; + /// Returns the currently set request stream. Can return 0. + + void setReconnect(bool recon); + /// Sets _reconnect. + + void setExpectResponseBody(bool expect); + /// Sets _expectResponseBody. + + bool getExpectResponseBody() const; + /// Returns _expectResponseBody. + +private: + std::string _host; + Poco::UInt16 _port; + std::string _proxyHost; + Poco::UInt16 _proxyPort; + bool _reconnect; + bool _expectResponseBody; + std::ostream* _pRequestStream; + std::istream* _pResponseStream; +}; + + +// +// inlines +// +inline const std::string& HTTPClientSession::getHost() const +{ + return _host; +} + + +inline Poco::UInt16 HTTPClientSession::getPort() const +{ + return _port; +} + + +inline const std::string& HTTPClientSession::getProxyHost() const +{ + return _proxyHost; +} + + +inline Poco::UInt16 HTTPClientSession::getProxyPort() const +{ + return _proxyPort; +} + + +inline std::istream* HTTPClientSession::getResponseStream() const +{ + return _pResponseStream; +} + + +inline std::ostream* HTTPClientSession::getRequestStream() const +{ + return _pRequestStream; +} + + +inline void HTTPClientSession::setReconnect(bool recon) +{ + _reconnect = recon; +} + + +inline void HTTPClientSession::setExpectResponseBody(bool expect) +{ + _expectResponseBody = expect; +} + + +inline bool HTTPClientSession::getExpectResponseBody() const +{ + return _expectResponseBody; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPClientSession_INCLUDED diff --git a/Net/include/Poco/Net/HTTPCookie.h b/Net/include/Poco/Net/HTTPCookie.h index 40076d292..433fac7ee 100644 --- a/Net/include/Poco/Net/HTTPCookie.h +++ b/Net/include/Poco/Net/HTTPCookie.h @@ -1,230 +1,230 @@ -// -// HTTPCookie.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPCookie.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPCookie -// -// Definition of the HTTPCookie 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_HTTPCookie_INCLUDED -#define Net_HTTPCookie_INCLUDED - - -#include "Poco/Net/Net.h" - - -namespace Poco { -namespace Net { - - -class NameValueCollection; - - -class Net_API HTTPCookie - /// This class represents a HTTP Cookie. - /// - /// A cookie is a small amount of information sent by a Web - /// server to a Web browser, saved by the browser, and later sent back - /// to the server. A cookie's value can uniquely identify a client, so - /// cookies are commonly used for session management. - /// - /// A cookie has a name, a single value, and optional attributes such - /// as a comment, path and domain qualifiers, a maximum age, and a - /// version number. - /// - /// This class supports both the Version 0 (by Netscape) and Version 1 - /// (by RFC 2109) cookie specifications. By default, cookies are created - /// using Version 0 to ensure the best interoperability. -{ -public: - HTTPCookie(); - /// Creates an empty HTTPCookie. - - explicit HTTPCookie(const std::string& name); - /// Creates a cookie with the given name. - /// The cookie never expires. - - explicit HTTPCookie(const NameValueCollection& nvc); - /// Creates a cookie from the given NameValueCollection. - - HTTPCookie(const std::string& name, const std::string& value); - /// Creates a cookie with the given name and value. - /// The cookie never expires. - - HTTPCookie(const HTTPCookie& cookie); - /// Creates the HTTPCookie by copying another one. - - ~HTTPCookie(); - /// Destroys the HTTPCookie. - - HTTPCookie& operator = (const HTTPCookie& cookie); - /// Assigns a cookie. - - void setVersion(int version); - /// Sets the version of the cookie. - /// - /// Version must be either 0 (denoting a Netscape cookie) - /// or 1 (denoting a RFC 2109 cookie). - - int getVersion() const; - /// Returns the version of the cookie, which is - /// either 0 or 1. - - void setName(const std::string& name); - /// Sets the name of the cookie. - - const std::string& getName() const; - /// Returns the name of the cookie. - - void setValue(const std::string& value); - /// Sets the value of the cookie. - /// - /// According to the cookie specification, the - /// size of the value should not exceed 4 Kbytes. - - const std::string& getValue() const; - /// Returns the value of the cookie. - - void setComment(const std::string& comment); - /// Sets the comment for the cookie. - /// - /// Comments are only supported for version 1 cookies. - - const std::string& getComment() const; - /// Returns the comment for the cookie. - - void setDomain(const std::string& domain); - /// Sets the domain for the cookie. - - const std::string& getDomain() const; - /// Returns the domain for the cookie. - - void setPath(const std::string& path); - /// Sets the path for the cookie. - - const std::string& getPath() const; - /// Returns the path for the cookie. - - void setSecure(bool secure); - /// Sets the value of the secure flag for - /// the cookie. - - bool getSecure() const; - /// Returns the value of the secure flag - /// for the cookie. - - void setMaxAge(int maxAge); - /// Sets the maximum age in seconds for - /// the cookie. - /// - /// A value of -1 causes the cookie to - /// never expire on the client. - /// - /// A value of 0 deletes the cookie on - /// the client. - - int getMaxAge() const; - /// Returns the maximum age in seconds for - /// the cookie. - - std::string toString() const; - /// Returns a string representation of the cookie, - /// suitable for use in a Set-Cookie header. - -private: - int _version; - std::string _name; - std::string _value; - std::string _comment; - std::string _domain; - std::string _path; - bool _secure; - int _maxAge; -}; - - -// -// inlines -// -inline int HTTPCookie::getVersion() const -{ - return _version; -} - - -inline const std::string& HTTPCookie::getName() const -{ - return _name; -} - - -inline const std::string& HTTPCookie::getValue() const -{ - return _value; -} - - -inline const std::string& HTTPCookie::getComment() const -{ - return _comment; -} - - -inline const std::string& HTTPCookie::getDomain() const -{ - return _domain; -} - - -inline const std::string& HTTPCookie::getPath() const -{ - return _path; -} - - -inline bool HTTPCookie::getSecure() const -{ - return _secure; -} - - -inline int HTTPCookie::getMaxAge() const -{ - return _maxAge; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPCookie_INCLUDED +// +// HTTPCookie.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPCookie.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPCookie +// +// Definition of the HTTPCookie 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_HTTPCookie_INCLUDED +#define Net_HTTPCookie_INCLUDED + + +#include "Poco/Net/Net.h" + + +namespace Poco { +namespace Net { + + +class NameValueCollection; + + +class Net_API HTTPCookie + /// This class represents a HTTP Cookie. + /// + /// A cookie is a small amount of information sent by a Web + /// server to a Web browser, saved by the browser, and later sent back + /// to the server. A cookie's value can uniquely identify a client, so + /// cookies are commonly used for session management. + /// + /// A cookie has a name, a single value, and optional attributes such + /// as a comment, path and domain qualifiers, a maximum age, and a + /// version number. + /// + /// This class supports both the Version 0 (by Netscape) and Version 1 + /// (by RFC 2109) cookie specifications. By default, cookies are created + /// using Version 0 to ensure the best interoperability. +{ +public: + HTTPCookie(); + /// Creates an empty HTTPCookie. + + explicit HTTPCookie(const std::string& name); + /// Creates a cookie with the given name. + /// The cookie never expires. + + explicit HTTPCookie(const NameValueCollection& nvc); + /// Creates a cookie from the given NameValueCollection. + + HTTPCookie(const std::string& name, const std::string& value); + /// Creates a cookie with the given name and value. + /// The cookie never expires. + + HTTPCookie(const HTTPCookie& cookie); + /// Creates the HTTPCookie by copying another one. + + ~HTTPCookie(); + /// Destroys the HTTPCookie. + + HTTPCookie& operator = (const HTTPCookie& cookie); + /// Assigns a cookie. + + void setVersion(int version); + /// Sets the version of the cookie. + /// + /// Version must be either 0 (denoting a Netscape cookie) + /// or 1 (denoting a RFC 2109 cookie). + + int getVersion() const; + /// Returns the version of the cookie, which is + /// either 0 or 1. + + void setName(const std::string& name); + /// Sets the name of the cookie. + + const std::string& getName() const; + /// Returns the name of the cookie. + + void setValue(const std::string& value); + /// Sets the value of the cookie. + /// + /// According to the cookie specification, the + /// size of the value should not exceed 4 Kbytes. + + const std::string& getValue() const; + /// Returns the value of the cookie. + + void setComment(const std::string& comment); + /// Sets the comment for the cookie. + /// + /// Comments are only supported for version 1 cookies. + + const std::string& getComment() const; + /// Returns the comment for the cookie. + + void setDomain(const std::string& domain); + /// Sets the domain for the cookie. + + const std::string& getDomain() const; + /// Returns the domain for the cookie. + + void setPath(const std::string& path); + /// Sets the path for the cookie. + + const std::string& getPath() const; + /// Returns the path for the cookie. + + void setSecure(bool secure); + /// Sets the value of the secure flag for + /// the cookie. + + bool getSecure() const; + /// Returns the value of the secure flag + /// for the cookie. + + void setMaxAge(int maxAge); + /// Sets the maximum age in seconds for + /// the cookie. + /// + /// A value of -1 causes the cookie to + /// never expire on the client. + /// + /// A value of 0 deletes the cookie on + /// the client. + + int getMaxAge() const; + /// Returns the maximum age in seconds for + /// the cookie. + + std::string toString() const; + /// Returns a string representation of the cookie, + /// suitable for use in a Set-Cookie header. + +private: + int _version; + std::string _name; + std::string _value; + std::string _comment; + std::string _domain; + std::string _path; + bool _secure; + int _maxAge; +}; + + +// +// inlines +// +inline int HTTPCookie::getVersion() const +{ + return _version; +} + + +inline const std::string& HTTPCookie::getName() const +{ + return _name; +} + + +inline const std::string& HTTPCookie::getValue() const +{ + return _value; +} + + +inline const std::string& HTTPCookie::getComment() const +{ + return _comment; +} + + +inline const std::string& HTTPCookie::getDomain() const +{ + return _domain; +} + + +inline const std::string& HTTPCookie::getPath() const +{ + return _path; +} + + +inline bool HTTPCookie::getSecure() const +{ + return _secure; +} + + +inline int HTTPCookie::getMaxAge() const +{ + return _maxAge; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPCookie_INCLUDED diff --git a/Net/include/Poco/Net/HTTPFixedLengthStream.h b/Net/include/Poco/Net/HTTPFixedLengthStream.h index 2dca05c7c..291e62e98 100644 --- a/Net/include/Poco/Net/HTTPFixedLengthStream.h +++ b/Net/include/Poco/Net/HTTPFixedLengthStream.h @@ -1,125 +1,125 @@ -// -// HTTPFixedLengthStream.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPFixedLengthStream.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPFixedLengthStream -// -// Definition of the HTTPFixedLengthStream 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_HTTPFixedLengthStream_INCLUDED -#define Net_HTTPFixedLengthStream_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPBasicStreamBuf.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class HTTPSession; - - -class Net_API HTTPFixedLengthStreamBuf: public HTTPBasicStreamBuf - /// This is the streambuf class used for reading and writing fixed-size - /// HTTP message bodies. - /// - /// At most a given number of bytes are read or written. -{ -public: - typedef HTTPBasicStreamBuf::openmode openmode; - - HTTPFixedLengthStreamBuf(HTTPSession& session, std::streamsize length, openmode mode); - ~HTTPFixedLengthStreamBuf(); - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - HTTPSession& _session; - std::streamsize _length; - std::streamsize _count; -}; - - -class Net_API HTTPFixedLengthIOS: public virtual std::ios - /// The base class for HTTPFixedLengthInputStream. -{ -public: - HTTPFixedLengthIOS(HTTPSession& session, std::streamsize length, HTTPFixedLengthStreamBuf::openmode mode); - ~HTTPFixedLengthIOS(); - HTTPFixedLengthStreamBuf* rdbuf(); - -protected: - HTTPFixedLengthStreamBuf _buf; -}; - - -class Net_API HTTPFixedLengthInputStream: public HTTPFixedLengthIOS, public std::istream - /// This class is for internal use by HTTPSession only. -{ -public: - HTTPFixedLengthInputStream(HTTPSession& session, std::streamsize length); - ~HTTPFixedLengthInputStream(); - - void* operator new(size_t size); - void operator delete(void* ptr); - -private: - static Poco::MemoryPool _pool; -}; - - -class Net_API HTTPFixedLengthOutputStream: public HTTPFixedLengthIOS, public std::ostream - /// This class is for internal use by HTTPSession only. -{ -public: - HTTPFixedLengthOutputStream(HTTPSession& session, std::streamsize length); - ~HTTPFixedLengthOutputStream(); - - void* operator new(size_t size); - void operator delete(void* ptr); - -private: - static Poco::MemoryPool _pool; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPFixedLengthStream_INCLUDED +// +// HTTPFixedLengthStream.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPFixedLengthStream.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPFixedLengthStream +// +// Definition of the HTTPFixedLengthStream 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_HTTPFixedLengthStream_INCLUDED +#define Net_HTTPFixedLengthStream_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPBasicStreamBuf.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class HTTPSession; + + +class Net_API HTTPFixedLengthStreamBuf: public HTTPBasicStreamBuf + /// This is the streambuf class used for reading and writing fixed-size + /// HTTP message bodies. + /// + /// At most a given number of bytes are read or written. +{ +public: + typedef HTTPBasicStreamBuf::openmode openmode; + + HTTPFixedLengthStreamBuf(HTTPSession& session, std::streamsize length, openmode mode); + ~HTTPFixedLengthStreamBuf(); + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + HTTPSession& _session; + std::streamsize _length; + std::streamsize _count; +}; + + +class Net_API HTTPFixedLengthIOS: public virtual std::ios + /// The base class for HTTPFixedLengthInputStream. +{ +public: + HTTPFixedLengthIOS(HTTPSession& session, std::streamsize length, HTTPFixedLengthStreamBuf::openmode mode); + ~HTTPFixedLengthIOS(); + HTTPFixedLengthStreamBuf* rdbuf(); + +protected: + HTTPFixedLengthStreamBuf _buf; +}; + + +class Net_API HTTPFixedLengthInputStream: public HTTPFixedLengthIOS, public std::istream + /// This class is for internal use by HTTPSession only. +{ +public: + HTTPFixedLengthInputStream(HTTPSession& session, std::streamsize length); + ~HTTPFixedLengthInputStream(); + + void* operator new(size_t size); + void operator delete(void* ptr); + +private: + static Poco::MemoryPool _pool; +}; + + +class Net_API HTTPFixedLengthOutputStream: public HTTPFixedLengthIOS, public std::ostream + /// This class is for internal use by HTTPSession only. +{ +public: + HTTPFixedLengthOutputStream(HTTPSession& session, std::streamsize length); + ~HTTPFixedLengthOutputStream(); + + void* operator new(size_t size); + void operator delete(void* ptr); + +private: + static Poco::MemoryPool _pool; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPFixedLengthStream_INCLUDED diff --git a/Net/include/Poco/Net/HTTPHeaderStream.h b/Net/include/Poco/Net/HTTPHeaderStream.h index 72de14ede..4bee6ca76 100644 --- a/Net/include/Poco/Net/HTTPHeaderStream.h +++ b/Net/include/Poco/Net/HTTPHeaderStream.h @@ -1,123 +1,123 @@ -// -// HTTPHeaderStream.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPHeaderStream.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPHeaderStream -// -// Definition of the HTTPHeaderStream 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_HTTPHeaderStream_INCLUDED -#define Net_HTTPHeaderStream_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPBasicStreamBuf.h" -#include "Poco/MemoryPool.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class HTTPSession; - - -class Net_API HTTPHeaderStreamBuf: public HTTPBasicStreamBuf - /// This is the streambuf class used for reading from a HTTP header - /// in a HTTPSession. -{ -public: - typedef HTTPBasicStreamBuf::openmode openmode; - - HTTPHeaderStreamBuf(HTTPSession& session, openmode mode); - ~HTTPHeaderStreamBuf(); - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - HTTPSession& _session; - bool _end; -}; - - -class Net_API HTTPHeaderIOS: public virtual std::ios - /// The base class for HTTPHeaderInputStream. -{ -public: - HTTPHeaderIOS(HTTPSession& session, HTTPHeaderStreamBuf::openmode mode); - ~HTTPHeaderIOS(); - HTTPHeaderStreamBuf* rdbuf(); - -protected: - HTTPHeaderStreamBuf _buf; -}; - - -class Net_API HTTPHeaderInputStream: public HTTPHeaderIOS, public std::istream - /// This class is for internal use by HTTPSession only. -{ -public: - HTTPHeaderInputStream(HTTPSession& session); - ~HTTPHeaderInputStream(); - - void* operator new(size_t size); - void operator delete(void* ptr); - -private: - static Poco::MemoryPool _pool; -}; - - -class Net_API HTTPHeaderOutputStream: public HTTPHeaderIOS, public std::ostream - /// This class is for internal use by HTTPSession only. -{ -public: - HTTPHeaderOutputStream(HTTPSession& session); - ~HTTPHeaderOutputStream(); - - void* operator new(size_t size); - void operator delete(void* ptr); - -private: - static Poco::MemoryPool _pool; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPHeaderStream_INCLUDED +// +// HTTPHeaderStream.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPHeaderStream.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPHeaderStream +// +// Definition of the HTTPHeaderStream 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_HTTPHeaderStream_INCLUDED +#define Net_HTTPHeaderStream_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPBasicStreamBuf.h" +#include "Poco/MemoryPool.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class HTTPSession; + + +class Net_API HTTPHeaderStreamBuf: public HTTPBasicStreamBuf + /// This is the streambuf class used for reading from a HTTP header + /// in a HTTPSession. +{ +public: + typedef HTTPBasicStreamBuf::openmode openmode; + + HTTPHeaderStreamBuf(HTTPSession& session, openmode mode); + ~HTTPHeaderStreamBuf(); + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + HTTPSession& _session; + bool _end; +}; + + +class Net_API HTTPHeaderIOS: public virtual std::ios + /// The base class for HTTPHeaderInputStream. +{ +public: + HTTPHeaderIOS(HTTPSession& session, HTTPHeaderStreamBuf::openmode mode); + ~HTTPHeaderIOS(); + HTTPHeaderStreamBuf* rdbuf(); + +protected: + HTTPHeaderStreamBuf _buf; +}; + + +class Net_API HTTPHeaderInputStream: public HTTPHeaderIOS, public std::istream + /// This class is for internal use by HTTPSession only. +{ +public: + HTTPHeaderInputStream(HTTPSession& session); + ~HTTPHeaderInputStream(); + + void* operator new(size_t size); + void operator delete(void* ptr); + +private: + static Poco::MemoryPool _pool; +}; + + +class Net_API HTTPHeaderOutputStream: public HTTPHeaderIOS, public std::ostream + /// This class is for internal use by HTTPSession only. +{ +public: + HTTPHeaderOutputStream(HTTPSession& session); + ~HTTPHeaderOutputStream(); + + void* operator new(size_t size); + void operator delete(void* ptr); + +private: + static Poco::MemoryPool _pool; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPHeaderStream_INCLUDED diff --git a/Net/include/Poco/Net/HTTPIOStream.h b/Net/include/Poco/Net/HTTPIOStream.h index bfa5236a1..6fd5e879b 100644 --- a/Net/include/Poco/Net/HTTPIOStream.h +++ b/Net/include/Poco/Net/HTTPIOStream.h @@ -1,110 +1,110 @@ -// -// HTTPIOStream.h -// -// $Id: //poco/Main/template/class.h#4 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPIOStream -// -// Definition of the HTTPIOStream 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_HTTPIOStream_INCLUDED -#define Net_HTTPIOStream_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPResponse.h" -#include "Poco/UnbufferedStreamBuf.h" - - -namespace Poco { -namespace Net { - - -class HTTPClientSession; - - -class Net_API HTTPResponseStreamBuf: public Poco::UnbufferedStreamBuf -{ -public: - HTTPResponseStreamBuf(std::istream& istr); - - ~HTTPResponseStreamBuf(); - -private: - int readFromDevice(); - - std::istream& _istr; -}; - - -inline int HTTPResponseStreamBuf::readFromDevice() -{ - return _istr.get(); -} - - -class Net_API HTTPResponseIOS: public virtual std::ios -{ -public: - HTTPResponseIOS(std::istream& istr); - - ~HTTPResponseIOS(); - - HTTPResponseStreamBuf* rdbuf(); - -protected: - HTTPResponseStreamBuf _buf; -}; - - -inline HTTPResponseStreamBuf* HTTPResponseIOS::rdbuf() -{ - return &_buf; -} - - -class Net_API HTTPResponseStream: public HTTPResponseIOS, public std::istream -{ -public: - HTTPResponseStream(std::istream& istr, HTTPClientSession* pSession); - - ~HTTPResponseStream(); - -private: - HTTPClientSession* _pSession; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPIOStream_INCLUDED +// +// HTTPIOStream.h +// +// $Id: //poco/Main/template/class.h#4 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPIOStream +// +// Definition of the HTTPIOStream 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_HTTPIOStream_INCLUDED +#define Net_HTTPIOStream_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPResponse.h" +#include "Poco/UnbufferedStreamBuf.h" + + +namespace Poco { +namespace Net { + + +class HTTPClientSession; + + +class Net_API HTTPResponseStreamBuf: public Poco::UnbufferedStreamBuf +{ +public: + HTTPResponseStreamBuf(std::istream& istr); + + ~HTTPResponseStreamBuf(); + +private: + int readFromDevice(); + + std::istream& _istr; +}; + + +inline int HTTPResponseStreamBuf::readFromDevice() +{ + return _istr.get(); +} + + +class Net_API HTTPResponseIOS: public virtual std::ios +{ +public: + HTTPResponseIOS(std::istream& istr); + + ~HTTPResponseIOS(); + + HTTPResponseStreamBuf* rdbuf(); + +protected: + HTTPResponseStreamBuf _buf; +}; + + +inline HTTPResponseStreamBuf* HTTPResponseIOS::rdbuf() +{ + return &_buf; +} + + +class Net_API HTTPResponseStream: public HTTPResponseIOS, public std::istream +{ +public: + HTTPResponseStream(std::istream& istr, HTTPClientSession* pSession); + + ~HTTPResponseStream(); + +private: + HTTPClientSession* _pSession; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPIOStream_INCLUDED diff --git a/Net/include/Poco/Net/HTTPMessage.h b/Net/include/Poco/Net/HTTPMessage.h index 1f2e924ef..ceb3be349 100644 --- a/Net/include/Poco/Net/HTTPMessage.h +++ b/Net/include/Poco/Net/HTTPMessage.h @@ -1,177 +1,177 @@ -// -// HTTPMessage.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPMessage.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPMessage -// -// Definition of the HTTPMessage 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_HTTPMessage_INCLUDED -#define Net_HTTPMessage_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/MessageHeader.h" - - -namespace Poco { -namespace Net { - - -class MediaType; - - -class Net_API HTTPMessage: public MessageHeader - /// The base class for HTTPRequest and HTTPResponse. - /// - /// Defines the common properties of all HTTP messages. - /// These are version, content length, content type - /// and transfer encoding. -{ -public: - void setVersion(const std::string& version); - /// Sets the HTTP version for this message. - - const std::string& getVersion() const; - /// Returns the HTTP version for this message. - - void setContentLength(int length); - /// Sets the Content-Length header. - /// - /// If length is UNKNOWN_CONTENT_LENGTH, removes - /// the Content-Length header. - - int getContentLength() const; - /// Returns the content length for this message, - /// which may be UNKNOWN_CONTENT_LENGTH if - /// no Content-Length header is present. - - void setTransferEncoding(const std::string& transferEncoding); - /// Sets the transfer encoding for this message. - /// - /// The value should be either IDENTITY_TRANSFER_CODING - /// or CHUNKED_TRANSFER_CODING. - - const std::string& getTransferEncoding() const; - /// Returns the transfer encoding used for this - /// message. - /// - /// Normally, this is the value of the Transfer-Encoding - /// header field. If no such field is present, - /// returns IDENTITY_TRANSFER_CODING. - - void setChunkedTransferEncoding(bool flag); - /// If flag is true, sets the Transfer-Encoding header to - /// chunked. Otherwise, removes the Transfer-Encoding - /// header. - - bool getChunkedTransferEncoding() const; - /// Returns true if the Transfer-Encoding header is set - /// and its value is chunked. - - void setContentType(const std::string& mediaType); - /// Sets the content type for this message. - /// - /// Specify NO_CONTENT_TYPE to remove the - /// Content-Type header. - - void setContentType(const MediaType& mediaType); - /// Sets the content type for this message. - - const std::string& getContentType() const; - /// Returns the content type for this message. - /// - /// If no Content-Type header is present, - /// returns UNKNOWN_CONTENT_TYPE. - - void setKeepAlive(bool keepAlive); - /// Sets the value of the Connection header field. - /// - /// The value is set to "Keep-Alive" if keepAlive is - /// true, or to "Close" otherwise. - - bool getKeepAlive() const; - /// Returns true if - /// * the message has a Connection header field and its value is "Keep-Alive" - /// * the message is a HTTP/1.1 message and not Connection header is set - /// Returns false otherwise. - - static const std::string HTTP_1_0; - static const std::string HTTP_1_1; - - static const std::string IDENTITY_TRANSFER_ENCODING; - static const std::string CHUNKED_TRANSFER_ENCODING; - - static const int UNKNOWN_CONTENT_LENGTH; - static const std::string UNKNOWN_CONTENT_TYPE; - - static const std::string CONTENT_LENGTH; - static const std::string CONTENT_TYPE; - static const std::string TRANSFER_ENCODING; - static const std::string CONNECTION; - - static const std::string CONNECTION_KEEP_ALIVE; - static const std::string CONNECTION_CLOSE; - -protected: - HTTPMessage(); - /// Creates the HTTPMessage with version HTTP/1.0. - - HTTPMessage(const std::string& version); - /// Creates the HTTPMessage and sets - /// the version. - - virtual ~HTTPMessage(); - /// Destroys the HTTPMessage. - -private: - HTTPMessage(const HTTPMessage&); - HTTPMessage& operator = (const HTTPMessage&); - - std::string _version; -}; - - -// -// inlines -// -inline const std::string& HTTPMessage::getVersion() const -{ - return _version; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPMessage_INCLUDED +// +// HTTPMessage.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPMessage.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPMessage +// +// Definition of the HTTPMessage 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_HTTPMessage_INCLUDED +#define Net_HTTPMessage_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/MessageHeader.h" + + +namespace Poco { +namespace Net { + + +class MediaType; + + +class Net_API HTTPMessage: public MessageHeader + /// The base class for HTTPRequest and HTTPResponse. + /// + /// Defines the common properties of all HTTP messages. + /// These are version, content length, content type + /// and transfer encoding. +{ +public: + void setVersion(const std::string& version); + /// Sets the HTTP version for this message. + + const std::string& getVersion() const; + /// Returns the HTTP version for this message. + + void setContentLength(int length); + /// Sets the Content-Length header. + /// + /// If length is UNKNOWN_CONTENT_LENGTH, removes + /// the Content-Length header. + + int getContentLength() const; + /// Returns the content length for this message, + /// which may be UNKNOWN_CONTENT_LENGTH if + /// no Content-Length header is present. + + void setTransferEncoding(const std::string& transferEncoding); + /// Sets the transfer encoding for this message. + /// + /// The value should be either IDENTITY_TRANSFER_CODING + /// or CHUNKED_TRANSFER_CODING. + + const std::string& getTransferEncoding() const; + /// Returns the transfer encoding used for this + /// message. + /// + /// Normally, this is the value of the Transfer-Encoding + /// header field. If no such field is present, + /// returns IDENTITY_TRANSFER_CODING. + + void setChunkedTransferEncoding(bool flag); + /// If flag is true, sets the Transfer-Encoding header to + /// chunked. Otherwise, removes the Transfer-Encoding + /// header. + + bool getChunkedTransferEncoding() const; + /// Returns true if the Transfer-Encoding header is set + /// and its value is chunked. + + void setContentType(const std::string& mediaType); + /// Sets the content type for this message. + /// + /// Specify NO_CONTENT_TYPE to remove the + /// Content-Type header. + + void setContentType(const MediaType& mediaType); + /// Sets the content type for this message. + + const std::string& getContentType() const; + /// Returns the content type for this message. + /// + /// If no Content-Type header is present, + /// returns UNKNOWN_CONTENT_TYPE. + + void setKeepAlive(bool keepAlive); + /// Sets the value of the Connection header field. + /// + /// The value is set to "Keep-Alive" if keepAlive is + /// true, or to "Close" otherwise. + + bool getKeepAlive() const; + /// Returns true if + /// * the message has a Connection header field and its value is "Keep-Alive" + /// * the message is a HTTP/1.1 message and not Connection header is set + /// Returns false otherwise. + + static const std::string HTTP_1_0; + static const std::string HTTP_1_1; + + static const std::string IDENTITY_TRANSFER_ENCODING; + static const std::string CHUNKED_TRANSFER_ENCODING; + + static const int UNKNOWN_CONTENT_LENGTH; + static const std::string UNKNOWN_CONTENT_TYPE; + + static const std::string CONTENT_LENGTH; + static const std::string CONTENT_TYPE; + static const std::string TRANSFER_ENCODING; + static const std::string CONNECTION; + + static const std::string CONNECTION_KEEP_ALIVE; + static const std::string CONNECTION_CLOSE; + +protected: + HTTPMessage(); + /// Creates the HTTPMessage with version HTTP/1.0. + + HTTPMessage(const std::string& version); + /// Creates the HTTPMessage and sets + /// the version. + + virtual ~HTTPMessage(); + /// Destroys the HTTPMessage. + +private: + HTTPMessage(const HTTPMessage&); + HTTPMessage& operator = (const HTTPMessage&); + + std::string _version; +}; + + +// +// inlines +// +inline const std::string& HTTPMessage::getVersion() const +{ + return _version; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPMessage_INCLUDED diff --git a/Net/include/Poco/Net/HTTPRequest.h b/Net/include/Poco/Net/HTTPRequest.h index 1c85c6ef2..dc3e58485 100644 --- a/Net/include/Poco/Net/HTTPRequest.h +++ b/Net/include/Poco/Net/HTTPRequest.h @@ -1,176 +1,176 @@ -// -// HTTPRequest.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPRequest.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPRequest -// -// Definition of the HTTPRequest 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_HTTPRequest_INCLUDED -#define Net_HTTPRequest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPMessage.h" - - -namespace Poco { -namespace Net { - - -class Net_API HTTPRequest: public HTTPMessage - /// This class encapsulates an HTTP request - /// message. - /// - /// In addition to the properties common to - /// all HTTP messages, a HTTP request has - /// a method (e.g. GET, HEAD, POST, etc.) and - /// a request URI. -{ -public: - HTTPRequest(); - /// Creates a GET / HTTP/1.0 HTTP request. - - HTTPRequest(const std::string& version); - /// Creates a GET / HTTP/1.x request with - /// the given version (HTTP/1.0 or HTTP/1.1). - - HTTPRequest(const std::string& method, const std::string& uri); - /// Creates a HTTP/1.0 request with the given method and URI. - - HTTPRequest(const std::string& method, const std::string& uri, const std::string& version); - /// Creates a HTTP request with the given method, URI and version. - - virtual ~HTTPRequest(); - /// Destroys the HTTPRequest. - - void setMethod(const std::string& method); - /// Sets the method. - - const std::string& getMethod() const; - /// Returns the method. - - void setURI(const std::string& uri); - /// Sets the request URI. - - const std::string& getURI() const; - /// Returns the request URI. - - void setHost(const std::string& host); - /// Sets the value of the Host header field. - - void setHost(const std::string& host, Poco::UInt16 port); - /// Sets the value of the Host header field. - - const std::string& getHost() const; - /// Returns the value of the Host header field. - /// - /// Throws a NotFoundException if the request - /// does not have a Host header field. - - void setCookies(const NameValueCollection& cookies); - /// Adds a Cookie header with the names and - /// values from cookies. - - void getCookies(NameValueCollection& cookies) const; - /// Fills cookies with the cookies extracted - /// from the Cookie headers in the request. - - bool hasCredentials() const; - /// Returns true iff the request contains authentication - /// information in the form of an Authorization header. - - void getCredentials(std::string& scheme, std::string& authInfo) const; - /// Returns the authentication scheme and additional authentication - /// information contained in this request. - /// - /// Throws a NotAuthenticatedException if no authentication information - /// is contained in the request. - - void setCredentials(const std::string& scheme, const std::string& authInfo); - /// Sets the authentication scheme and information for - /// this request. - - void write(std::ostream& ostr) const; - /// Writes the HTTP request to the given - /// output stream. - - void read(std::istream& istr); - /// Reads the HTTP request from the - /// given input stream. - - static const std::string HTTP_GET; - static const std::string HTTP_HEAD; - static const std::string HTTP_PUT; - static const std::string HTTP_POST; - static const std::string HTTP_OPTIONS; - static const std::string HTTP_DELETE; - static const std::string HTTP_TRACE; - static const std::string HTTP_CONNECT; - - static const std::string HOST; - static const std::string COOKIE; - static const std::string AUTHORIZATION; - -private: - enum Limits - { - MAX_METHOD_LENGTH = 32, - MAX_URI_LENGTH = 4096, - MAX_VERSION_LENGTH = 8 - }; - - std::string _method; - std::string _uri; -}; - - -// -// inlines -// -inline const std::string& HTTPRequest::getMethod() const -{ - return _method; -} - - -inline const std::string& HTTPRequest::getURI() const -{ - return _uri; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPRequest_INCLUDED +// +// HTTPRequest.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPRequest.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPRequest +// +// Definition of the HTTPRequest 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_HTTPRequest_INCLUDED +#define Net_HTTPRequest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPMessage.h" + + +namespace Poco { +namespace Net { + + +class Net_API HTTPRequest: public HTTPMessage + /// This class encapsulates an HTTP request + /// message. + /// + /// In addition to the properties common to + /// all HTTP messages, a HTTP request has + /// a method (e.g. GET, HEAD, POST, etc.) and + /// a request URI. +{ +public: + HTTPRequest(); + /// Creates a GET / HTTP/1.0 HTTP request. + + HTTPRequest(const std::string& version); + /// Creates a GET / HTTP/1.x request with + /// the given version (HTTP/1.0 or HTTP/1.1). + + HTTPRequest(const std::string& method, const std::string& uri); + /// Creates a HTTP/1.0 request with the given method and URI. + + HTTPRequest(const std::string& method, const std::string& uri, const std::string& version); + /// Creates a HTTP request with the given method, URI and version. + + virtual ~HTTPRequest(); + /// Destroys the HTTPRequest. + + void setMethod(const std::string& method); + /// Sets the method. + + const std::string& getMethod() const; + /// Returns the method. + + void setURI(const std::string& uri); + /// Sets the request URI. + + const std::string& getURI() const; + /// Returns the request URI. + + void setHost(const std::string& host); + /// Sets the value of the Host header field. + + void setHost(const std::string& host, Poco::UInt16 port); + /// Sets the value of the Host header field. + + const std::string& getHost() const; + /// Returns the value of the Host header field. + /// + /// Throws a NotFoundException if the request + /// does not have a Host header field. + + void setCookies(const NameValueCollection& cookies); + /// Adds a Cookie header with the names and + /// values from cookies. + + void getCookies(NameValueCollection& cookies) const; + /// Fills cookies with the cookies extracted + /// from the Cookie headers in the request. + + bool hasCredentials() const; + /// Returns true iff the request contains authentication + /// information in the form of an Authorization header. + + void getCredentials(std::string& scheme, std::string& authInfo) const; + /// Returns the authentication scheme and additional authentication + /// information contained in this request. + /// + /// Throws a NotAuthenticatedException if no authentication information + /// is contained in the request. + + void setCredentials(const std::string& scheme, const std::string& authInfo); + /// Sets the authentication scheme and information for + /// this request. + + void write(std::ostream& ostr) const; + /// Writes the HTTP request to the given + /// output stream. + + void read(std::istream& istr); + /// Reads the HTTP request from the + /// given input stream. + + static const std::string HTTP_GET; + static const std::string HTTP_HEAD; + static const std::string HTTP_PUT; + static const std::string HTTP_POST; + static const std::string HTTP_OPTIONS; + static const std::string HTTP_DELETE; + static const std::string HTTP_TRACE; + static const std::string HTTP_CONNECT; + + static const std::string HOST; + static const std::string COOKIE; + static const std::string AUTHORIZATION; + +private: + enum Limits + { + MAX_METHOD_LENGTH = 32, + MAX_URI_LENGTH = 4096, + MAX_VERSION_LENGTH = 8 + }; + + std::string _method; + std::string _uri; +}; + + +// +// inlines +// +inline const std::string& HTTPRequest::getMethod() const +{ + return _method; +} + + +inline const std::string& HTTPRequest::getURI() const +{ + return _uri; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPRequest_INCLUDED diff --git a/Net/include/Poco/Net/HTTPRequestHandler.h b/Net/include/Poco/Net/HTTPRequestHandler.h index bbbdf6783..16de87873 100644 --- a/Net/include/Poco/Net/HTTPRequestHandler.h +++ b/Net/include/Poco/Net/HTTPRequestHandler.h @@ -1,89 +1,89 @@ -// -// HTTPRequestHandler.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPRequestHandler.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPRequestHandler -// -// Definition of the HTTPRequestHandler 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_HTTPRequestHandler_INCLUDED -#define Net_HTTPRequestHandler_INCLUDED - - -#include "Poco/Net/Net.h" - - -namespace Poco { -namespace Net { - - -class HTTPServerRequest; -class HTTPServerResponse; - - -class Net_API HTTPRequestHandler - /// The abstract base class for HTTPRequestHandlers - /// created by HTTPServer. - /// - /// Derived classes must override the handleRequest() method. - /// Furthermore, a HTTPRequestHandlerFactory must be provided. - /// - /// The handleRequest() method must perform the complete handling - /// of the HTTP request connection. As soon as the handleRequest() - /// method returns, the request handler object is destroyed. - /// - /// A new HTTPRequestHandler object will be created for - /// each new HTTP request that is received by the HTTPServer. -{ -public: - HTTPRequestHandler(); - /// Creates the HTTPRequestHandler. - - virtual ~HTTPRequestHandler(); - /// Destroys the HTTPRequestHandler. - - virtual void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) = 0; - /// Must be overridden by subclasses. - /// - /// Handles the given request. - -private: - HTTPRequestHandler(const HTTPRequestHandler&); - HTTPRequestHandler& operator = (const HTTPRequestHandler&); -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPRequestHandler_INCLUDED +// +// HTTPRequestHandler.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPRequestHandler.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPRequestHandler +// +// Definition of the HTTPRequestHandler 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_HTTPRequestHandler_INCLUDED +#define Net_HTTPRequestHandler_INCLUDED + + +#include "Poco/Net/Net.h" + + +namespace Poco { +namespace Net { + + +class HTTPServerRequest; +class HTTPServerResponse; + + +class Net_API HTTPRequestHandler + /// The abstract base class for HTTPRequestHandlers + /// created by HTTPServer. + /// + /// Derived classes must override the handleRequest() method. + /// Furthermore, a HTTPRequestHandlerFactory must be provided. + /// + /// The handleRequest() method must perform the complete handling + /// of the HTTP request connection. As soon as the handleRequest() + /// method returns, the request handler object is destroyed. + /// + /// A new HTTPRequestHandler object will be created for + /// each new HTTP request that is received by the HTTPServer. +{ +public: + HTTPRequestHandler(); + /// Creates the HTTPRequestHandler. + + virtual ~HTTPRequestHandler(); + /// Destroys the HTTPRequestHandler. + + virtual void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) = 0; + /// Must be overridden by subclasses. + /// + /// Handles the given request. + +private: + HTTPRequestHandler(const HTTPRequestHandler&); + HTTPRequestHandler& operator = (const HTTPRequestHandler&); +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPRequestHandler_INCLUDED diff --git a/Net/include/Poco/Net/HTTPRequestHandlerFactory.h b/Net/include/Poco/Net/HTTPRequestHandlerFactory.h index 8ee666098..e8f43b981 100644 --- a/Net/include/Poco/Net/HTTPRequestHandlerFactory.h +++ b/Net/include/Poco/Net/HTTPRequestHandlerFactory.h @@ -1,80 +1,80 @@ -// -// HTTPRequestHandlerFactory.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPRequestHandlerFactory.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPRequestHandlerFactory -// -// Definition of the HTTPRequestHandlerFactory 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_HTTPRequestHandlerFactory_INCLUDED -#define Net_HTTPRequestHandlerFactory_INCLUDED - - -#include "Poco/Net/Net.h" - - -namespace Poco { -namespace Net { - - -class HTTPServerRequest; -class HTTPRequestHandler; - - -class Net_API HTTPRequestHandlerFactory - /// A factory for HTTPRequestHandler objects. - /// Subclasses must override the createRequstHandler() - /// method. -{ -public: - HTTPRequestHandlerFactory(); - /// Creates the HTTPRequestHandlerFactory. - - virtual ~HTTPRequestHandlerFactory(); - /// Destroys the HTTPRequestHandlerFactory. - - virtual HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) = 0; - /// Must be overridden by sublasses. - /// - /// Creates a new request handler for the given HTTP request. - -private: - HTTPRequestHandlerFactory(const HTTPRequestHandlerFactory&); - HTTPRequestHandlerFactory& operator = (const HTTPRequestHandlerFactory&); -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPRequestHandlerFactory_INCLUDED +// +// HTTPRequestHandlerFactory.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPRequestHandlerFactory.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPRequestHandlerFactory +// +// Definition of the HTTPRequestHandlerFactory 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_HTTPRequestHandlerFactory_INCLUDED +#define Net_HTTPRequestHandlerFactory_INCLUDED + + +#include "Poco/Net/Net.h" + + +namespace Poco { +namespace Net { + + +class HTTPServerRequest; +class HTTPRequestHandler; + + +class Net_API HTTPRequestHandlerFactory + /// A factory for HTTPRequestHandler objects. + /// Subclasses must override the createRequstHandler() + /// method. +{ +public: + HTTPRequestHandlerFactory(); + /// Creates the HTTPRequestHandlerFactory. + + virtual ~HTTPRequestHandlerFactory(); + /// Destroys the HTTPRequestHandlerFactory. + + virtual HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) = 0; + /// Must be overridden by sublasses. + /// + /// Creates a new request handler for the given HTTP request. + +private: + HTTPRequestHandlerFactory(const HTTPRequestHandlerFactory&); + HTTPRequestHandlerFactory& operator = (const HTTPRequestHandlerFactory&); +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPRequestHandlerFactory_INCLUDED diff --git a/Net/include/Poco/Net/HTTPResponse.h b/Net/include/Poco/Net/HTTPResponse.h index 742dfa6e6..8b685a8cc 100644 --- a/Net/include/Poco/Net/HTTPResponse.h +++ b/Net/include/Poco/Net/HTTPResponse.h @@ -1,268 +1,268 @@ -// -// HTTPResponse.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPResponse.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPResponse -// -// Definition of the HTTPResponse 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_HTTPResponse_INCLUDED -#define Net_HTTPResponse_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPMessage.h" -#include "Poco/Net/HTTPCookie.h" -#include "Poco/Timestamp.h" -#include - - -namespace Poco { -namespace Net { - - -class HTTPCookie; - - -class Net_API HTTPResponse: public HTTPMessage - /// This class encapsulates an HTTP response - /// message. - /// - /// In addition to the properties common to - /// all HTTP messages, a HTTP response has - /// status code and a reason phrase. -{ -public: - enum HTTPStatus - { - HTTP_CONTINUE = 100, - HTTP_SWITCHING_PROTOCOLS = 101, - HTTP_OK = 200, - HTTP_CREATED = 201, - HTTP_ACCEPTED = 202, - HTTP_NONAUTHORITATIVE = 203, - HTTP_NO_CONTENT = 204, - HTTP_RESET_CONTENT = 205, - HTTP_PARTIAL_CONTENT = 206, - HTTP_MULTIPLE_CHOICES = 300, - HTTP_MOVED_PERMANENTLY = 301, - HTTP_FOUND = 302, - HTTP_SEE_OTHER = 303, - HTTP_NOT_MODIFIED = 304, - HTTP_USEPROXY = 305, - // UNUSED: 306 - HTTP_TEMPORARY_REDIRECT = 307, - HTTP_BAD_REQUEST = 400, - HTTP_UNAUTHORIZED = 401, - HTTP_PAYMENT_REQUIRED = 402, - HTTP_FORBIDDEN = 403, - HTTP_NOT_FOUND = 404, - HTTP_METHOD_NOT_ALLOWED = 405, - HTTP_NOT_ACCEPTABLE = 406, - HTTP_PROXY_AUTHENTICATION_REQUIRED = 407, - HTTP_REQUEST_TIMEOUT = 408, - HTTP_CONFLICT = 409, - HTTP_GONE = 410, - HTTP_LENGTH_REQUIRED = 411, - HTTP_PRECONDITION_FAILED = 412, - HTTP_REQUESTENTITYTOOLARGE = 413, - HTTP_REQUESTURITOOLONG = 414, - HTTP_UNSUPPORTEDMEDIATYPE = 415, - HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416, - HTTP_EXPECTATION_FAILED = 417, - HTTP_INTERNAL_SERVER_ERROR = 500, - HTTP_NOT_IMPLEMENTED = 501, - HTTP_BAD_GATEWAY = 502, - HTTP_SERVICE_UNAVAILABLE = 503, - HTTP_GATEWAY_TIMEOUT = 504, - HTTP_VERSION_NOT_SUPPORTED = 505 - }; - - HTTPResponse(); - /// Creates the HTTPResponse with OK status. - - HTTPResponse(HTTPStatus status, const std::string& reason); - /// Creates the HTTPResponse with the given status - /// and reason phrase. - - HTTPResponse(const std::string& version, HTTPStatus status, const std::string& reason); - /// Creates the HTTPResponse with the given version, status - /// and reason phrase. - - HTTPResponse(HTTPStatus status); - /// Creates the HTTPResponse with the given status - /// an an appropriate reason phrase. - - HTTPResponse(const std::string& version, HTTPStatus status); - /// Creates the HTTPResponse with the given version, status - /// an an appropriate reason phrase. - - virtual ~HTTPResponse(); - /// Destroys the HTTPResponse. - - void setStatus(HTTPStatus status); - /// Sets the HTTP status code. - /// - /// Does not change the reason phrase. - - HTTPStatus getStatus() const; - /// Returns the HTTP status code. - - void setStatus(const std::string& status); - /// Sets the HTTP status code. - /// - /// The string must contain a valid - /// HTTP numerical status code. - - void setReason(const std::string& reason); - /// Sets the HTTP reason phrase. - - const std::string& getReason() const; - /// Returns the HTTP reason phrase. - - void setStatusAndReason(HTTPStatus status, const std::string& reason); - /// Sets the HTTP status code and reason phrase. - - void setStatusAndReason(HTTPStatus status); - /// Sets the HTTP status code and reason phrase. - /// - /// The reason phrase is set according to the status code. - - void setDate(const Poco::Timestamp& dateTime); - /// Sets the Date header to the given date/time value. - - Poco::Timestamp getDate() const; - /// Returns the value of the Date header. - - void addCookie(const HTTPCookie& cookie); - /// Adds the cookie to the response by - /// adding a Set-Cookie header. - - void getCookies(std::vector& cookies) const; - /// Returns a vector with all the cookies - /// set in the response header. - /// - /// May throw an exception in case of a malformed - /// Set-Cookie header. - - void write(std::ostream& ostr) const; - /// Writes the HTTP response to the given - /// output stream. - - void read(std::istream& istr); - /// Reads the HTTP response from the - /// given input stream. - /// - /// 100 Continue responses are ignored. - - static const std::string& getReasonForStatus(HTTPStatus status); - /// Returns an appropriate reason phrase - /// for the given status code. - - static const std::string HTTP_REASON_CONTINUE; - static const std::string HTTP_REASON_SWITCHING_PROTOCOLS; - static const std::string HTTP_REASON_OK; - static const std::string HTTP_REASON_CREATED; - static const std::string HTTP_REASON_ACCEPTED; - static const std::string HTTP_REASON_NONAUTHORITATIVE; - static const std::string HTTP_REASON_NO_CONTENT; - static const std::string HTTP_REASON_RESET_CONTENT; - static const std::string HTTP_REASON_PARTIAL_CONTENT; - static const std::string HTTP_REASON_MULTIPLE_CHOICES; - static const std::string HTTP_REASON_MOVED_PERMANENTLY; - static const std::string HTTP_REASON_FOUND; - static const std::string HTTP_REASON_SEE_OTHER; - static const std::string HTTP_REASON_NOT_MODIFIED; - static const std::string HTTP_REASON_USEPROXY; - static const std::string HTTP_REASON_TEMPORARY_REDIRECT; - static const std::string HTTP_REASON_BAD_REQUEST; - static const std::string HTTP_REASON_UNAUTHORIZED; - static const std::string HTTP_REASON_PAYMENT_REQUIRED; - static const std::string HTTP_REASON_FORBIDDEN; - static const std::string HTTP_REASON_NOT_FOUND; - static const std::string HTTP_REASON_METHOD_NOT_ALLOWED; - static const std::string HTTP_REASON_NOT_ACCEPTABLE; - static const std::string HTTP_REASON_PROXY_AUTHENTICATION_REQUIRED; - static const std::string HTTP_REASON_REQUEST_TIMEOUT; - static const std::string HTTP_REASON_CONFLICT; - static const std::string HTTP_REASON_GONE; - static const std::string HTTP_REASON_LENGTH_REQUIRED; - static const std::string HTTP_REASON_PRECONDITION_FAILED; - static const std::string HTTP_REASON_REQUESTENTITYTOOLARGE; - static const std::string HTTP_REASON_REQUESTURITOOLONG; - static const std::string HTTP_REASON_UNSUPPORTEDMEDIATYPE; - static const std::string HTTP_REASON_REQUESTED_RANGE_NOT_SATISFIABLE; - static const std::string HTTP_REASON_EXPECTATION_FAILED; - static const std::string HTTP_REASON_INTERNAL_SERVER_ERROR; - static const std::string HTTP_REASON_NOT_IMPLEMENTED; - static const std::string HTTP_REASON_BAD_GATEWAY; - static const std::string HTTP_REASON_SERVICE_UNAVAILABLE; - static const std::string HTTP_REASON_GATEWAY_TIMEOUT; - static const std::string HTTP_REASON_VERSION_NOT_SUPPORTED; - static const std::string HTTP_REASON_UNKNOWN; - - static const std::string DATE; - static const std::string SET_COOKIE; - -private: - enum Limits - { - MAX_VERSION_LENGTH = 8, - MAX_STATUS_LENGTH = 3, - MAX_REASON_LENGTH = 512 - }; - - HTTPStatus _status; - std::string _reason; -}; - - -// -// inlines -// -inline HTTPResponse::HTTPStatus HTTPResponse::getStatus() const -{ - return _status; -} - - -inline const std::string& HTTPResponse::getReason() const -{ - return _reason; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPResponse_INCLUDED +// +// HTTPResponse.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPResponse.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPResponse +// +// Definition of the HTTPResponse 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_HTTPResponse_INCLUDED +#define Net_HTTPResponse_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPMessage.h" +#include "Poco/Net/HTTPCookie.h" +#include "Poco/Timestamp.h" +#include + + +namespace Poco { +namespace Net { + + +class HTTPCookie; + + +class Net_API HTTPResponse: public HTTPMessage + /// This class encapsulates an HTTP response + /// message. + /// + /// In addition to the properties common to + /// all HTTP messages, a HTTP response has + /// status code and a reason phrase. +{ +public: + enum HTTPStatus + { + HTTP_CONTINUE = 100, + HTTP_SWITCHING_PROTOCOLS = 101, + HTTP_OK = 200, + HTTP_CREATED = 201, + HTTP_ACCEPTED = 202, + HTTP_NONAUTHORITATIVE = 203, + HTTP_NO_CONTENT = 204, + HTTP_RESET_CONTENT = 205, + HTTP_PARTIAL_CONTENT = 206, + HTTP_MULTIPLE_CHOICES = 300, + HTTP_MOVED_PERMANENTLY = 301, + HTTP_FOUND = 302, + HTTP_SEE_OTHER = 303, + HTTP_NOT_MODIFIED = 304, + HTTP_USEPROXY = 305, + // UNUSED: 306 + HTTP_TEMPORARY_REDIRECT = 307, + HTTP_BAD_REQUEST = 400, + HTTP_UNAUTHORIZED = 401, + HTTP_PAYMENT_REQUIRED = 402, + HTTP_FORBIDDEN = 403, + HTTP_NOT_FOUND = 404, + HTTP_METHOD_NOT_ALLOWED = 405, + HTTP_NOT_ACCEPTABLE = 406, + HTTP_PROXY_AUTHENTICATION_REQUIRED = 407, + HTTP_REQUEST_TIMEOUT = 408, + HTTP_CONFLICT = 409, + HTTP_GONE = 410, + HTTP_LENGTH_REQUIRED = 411, + HTTP_PRECONDITION_FAILED = 412, + HTTP_REQUESTENTITYTOOLARGE = 413, + HTTP_REQUESTURITOOLONG = 414, + HTTP_UNSUPPORTEDMEDIATYPE = 415, + HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416, + HTTP_EXPECTATION_FAILED = 417, + HTTP_INTERNAL_SERVER_ERROR = 500, + HTTP_NOT_IMPLEMENTED = 501, + HTTP_BAD_GATEWAY = 502, + HTTP_SERVICE_UNAVAILABLE = 503, + HTTP_GATEWAY_TIMEOUT = 504, + HTTP_VERSION_NOT_SUPPORTED = 505 + }; + + HTTPResponse(); + /// Creates the HTTPResponse with OK status. + + HTTPResponse(HTTPStatus status, const std::string& reason); + /// Creates the HTTPResponse with the given status + /// and reason phrase. + + HTTPResponse(const std::string& version, HTTPStatus status, const std::string& reason); + /// Creates the HTTPResponse with the given version, status + /// and reason phrase. + + HTTPResponse(HTTPStatus status); + /// Creates the HTTPResponse with the given status + /// an an appropriate reason phrase. + + HTTPResponse(const std::string& version, HTTPStatus status); + /// Creates the HTTPResponse with the given version, status + /// an an appropriate reason phrase. + + virtual ~HTTPResponse(); + /// Destroys the HTTPResponse. + + void setStatus(HTTPStatus status); + /// Sets the HTTP status code. + /// + /// Does not change the reason phrase. + + HTTPStatus getStatus() const; + /// Returns the HTTP status code. + + void setStatus(const std::string& status); + /// Sets the HTTP status code. + /// + /// The string must contain a valid + /// HTTP numerical status code. + + void setReason(const std::string& reason); + /// Sets the HTTP reason phrase. + + const std::string& getReason() const; + /// Returns the HTTP reason phrase. + + void setStatusAndReason(HTTPStatus status, const std::string& reason); + /// Sets the HTTP status code and reason phrase. + + void setStatusAndReason(HTTPStatus status); + /// Sets the HTTP status code and reason phrase. + /// + /// The reason phrase is set according to the status code. + + void setDate(const Poco::Timestamp& dateTime); + /// Sets the Date header to the given date/time value. + + Poco::Timestamp getDate() const; + /// Returns the value of the Date header. + + void addCookie(const HTTPCookie& cookie); + /// Adds the cookie to the response by + /// adding a Set-Cookie header. + + void getCookies(std::vector& cookies) const; + /// Returns a vector with all the cookies + /// set in the response header. + /// + /// May throw an exception in case of a malformed + /// Set-Cookie header. + + void write(std::ostream& ostr) const; + /// Writes the HTTP response to the given + /// output stream. + + void read(std::istream& istr); + /// Reads the HTTP response from the + /// given input stream. + /// + /// 100 Continue responses are ignored. + + static const std::string& getReasonForStatus(HTTPStatus status); + /// Returns an appropriate reason phrase + /// for the given status code. + + static const std::string HTTP_REASON_CONTINUE; + static const std::string HTTP_REASON_SWITCHING_PROTOCOLS; + static const std::string HTTP_REASON_OK; + static const std::string HTTP_REASON_CREATED; + static const std::string HTTP_REASON_ACCEPTED; + static const std::string HTTP_REASON_NONAUTHORITATIVE; + static const std::string HTTP_REASON_NO_CONTENT; + static const std::string HTTP_REASON_RESET_CONTENT; + static const std::string HTTP_REASON_PARTIAL_CONTENT; + static const std::string HTTP_REASON_MULTIPLE_CHOICES; + static const std::string HTTP_REASON_MOVED_PERMANENTLY; + static const std::string HTTP_REASON_FOUND; + static const std::string HTTP_REASON_SEE_OTHER; + static const std::string HTTP_REASON_NOT_MODIFIED; + static const std::string HTTP_REASON_USEPROXY; + static const std::string HTTP_REASON_TEMPORARY_REDIRECT; + static const std::string HTTP_REASON_BAD_REQUEST; + static const std::string HTTP_REASON_UNAUTHORIZED; + static const std::string HTTP_REASON_PAYMENT_REQUIRED; + static const std::string HTTP_REASON_FORBIDDEN; + static const std::string HTTP_REASON_NOT_FOUND; + static const std::string HTTP_REASON_METHOD_NOT_ALLOWED; + static const std::string HTTP_REASON_NOT_ACCEPTABLE; + static const std::string HTTP_REASON_PROXY_AUTHENTICATION_REQUIRED; + static const std::string HTTP_REASON_REQUEST_TIMEOUT; + static const std::string HTTP_REASON_CONFLICT; + static const std::string HTTP_REASON_GONE; + static const std::string HTTP_REASON_LENGTH_REQUIRED; + static const std::string HTTP_REASON_PRECONDITION_FAILED; + static const std::string HTTP_REASON_REQUESTENTITYTOOLARGE; + static const std::string HTTP_REASON_REQUESTURITOOLONG; + static const std::string HTTP_REASON_UNSUPPORTEDMEDIATYPE; + static const std::string HTTP_REASON_REQUESTED_RANGE_NOT_SATISFIABLE; + static const std::string HTTP_REASON_EXPECTATION_FAILED; + static const std::string HTTP_REASON_INTERNAL_SERVER_ERROR; + static const std::string HTTP_REASON_NOT_IMPLEMENTED; + static const std::string HTTP_REASON_BAD_GATEWAY; + static const std::string HTTP_REASON_SERVICE_UNAVAILABLE; + static const std::string HTTP_REASON_GATEWAY_TIMEOUT; + static const std::string HTTP_REASON_VERSION_NOT_SUPPORTED; + static const std::string HTTP_REASON_UNKNOWN; + + static const std::string DATE; + static const std::string SET_COOKIE; + +private: + enum Limits + { + MAX_VERSION_LENGTH = 8, + MAX_STATUS_LENGTH = 3, + MAX_REASON_LENGTH = 512 + }; + + HTTPStatus _status; + std::string _reason; +}; + + +// +// inlines +// +inline HTTPResponse::HTTPStatus HTTPResponse::getStatus() const +{ + return _status; +} + + +inline const std::string& HTTPResponse::getReason() const +{ + return _reason; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPResponse_INCLUDED diff --git a/Net/include/Poco/Net/HTTPServer.h b/Net/include/Poco/Net/HTTPServer.h index 375990858..ddc129568 100644 --- a/Net/include/Poco/Net/HTTPServer.h +++ b/Net/include/Poco/Net/HTTPServer.h @@ -1,106 +1,106 @@ -// -// HTTPServer.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServer.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPServer -// -// Definition of the HTTPServer 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_HTTPServer_INCLUDED -#define Net_HTTPServer_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/TCPServer.h" - - -namespace Poco { -namespace Net { - - -class HTTPRequestHandlerFactory; -class HTTPServerParams; - - -class Net_API HTTPServer: public TCPServer - /// A subclass of TCPServer that implements a - /// full-featured multithreaded HTTP server. - /// - /// A HTTPRequestHandlerFactory must be supplied. - /// The ServerSocket must be bound and in listening state. - /// - /// To configure various aspects of the server, a HTTPServerParams - /// object can be passed to the constructor. - /// - /// The server supports: - /// - HTTP/1.0 and HTTP/1.1 - /// - automatic handling of persistent connections. - /// - automatic decoding/encoding of request/response message bodies - /// using chunked transfer encoding. - /// - /// Please see the TCPServer class for information about - /// connection and thread handling. - /// - /// See RFC 2616 for more - /// information about the HTTP protocol. -{ -public: - HTTPServer(HTTPRequestHandlerFactory* pFactory, const ServerSocket& socket, HTTPServerParams* pParams); - /// Creates the HTTPServer, using the given ServerSocket. - /// - /// The server takes ownership of the HTTPRequstHandlerFactory - /// and deletes it when it's no longer needed. - /// - /// The server also takes ownership of the HTTPServerParams object. - /// - /// News threads are taken from the default thread pool. - - HTTPServer(HTTPRequestHandlerFactory* pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, HTTPServerParams* pParams); - /// Creates the HTTPServer, using the given ServerSocket. - /// - /// The server takes ownership of the HTTPRequstHandlerFactory - /// and deletes it when it's no longer needed. - /// - /// The server also takes ownership of the HTTPServerParams object. - /// - /// News threads are taken from the given thread pool. - - ~HTTPServer(); - /// Destroys the HTTPServer and its HTTPRequestHandlerFactory. -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPServer_INCLUDED +// +// HTTPServer.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServer.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPServer +// +// Definition of the HTTPServer 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_HTTPServer_INCLUDED +#define Net_HTTPServer_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/TCPServer.h" + + +namespace Poco { +namespace Net { + + +class HTTPRequestHandlerFactory; +class HTTPServerParams; + + +class Net_API HTTPServer: public TCPServer + /// A subclass of TCPServer that implements a + /// full-featured multithreaded HTTP server. + /// + /// A HTTPRequestHandlerFactory must be supplied. + /// The ServerSocket must be bound and in listening state. + /// + /// To configure various aspects of the server, a HTTPServerParams + /// object can be passed to the constructor. + /// + /// The server supports: + /// - HTTP/1.0 and HTTP/1.1 + /// - automatic handling of persistent connections. + /// - automatic decoding/encoding of request/response message bodies + /// using chunked transfer encoding. + /// + /// Please see the TCPServer class for information about + /// connection and thread handling. + /// + /// See RFC 2616 for more + /// information about the HTTP protocol. +{ +public: + HTTPServer(HTTPRequestHandlerFactory* pFactory, const ServerSocket& socket, HTTPServerParams* pParams); + /// Creates the HTTPServer, using the given ServerSocket. + /// + /// The server takes ownership of the HTTPRequstHandlerFactory + /// and deletes it when it's no longer needed. + /// + /// The server also takes ownership of the HTTPServerParams object. + /// + /// News threads are taken from the default thread pool. + + HTTPServer(HTTPRequestHandlerFactory* pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, HTTPServerParams* pParams); + /// Creates the HTTPServer, using the given ServerSocket. + /// + /// The server takes ownership of the HTTPRequstHandlerFactory + /// and deletes it when it's no longer needed. + /// + /// The server also takes ownership of the HTTPServerParams object. + /// + /// News threads are taken from the given thread pool. + + ~HTTPServer(); + /// Destroys the HTTPServer and its HTTPRequestHandlerFactory. +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPServer_INCLUDED diff --git a/Net/include/Poco/Net/HTTPServerConnection.h b/Net/include/Poco/Net/HTTPServerConnection.h index f323fe157..76f26a964 100644 --- a/Net/include/Poco/Net/HTTPServerConnection.h +++ b/Net/include/Poco/Net/HTTPServerConnection.h @@ -1,78 +1,78 @@ -// -// HTTPServerConnection.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerConnection.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPServerConnection -// -// Definition of the HTTPServerConnection 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_HTTPServerConnection_INCLUDED -#define Net_HTTPServerConnection_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/TCPServerConnection.h" - - -namespace Poco { -namespace Net { - - -class HTTPServerParams; -class HTTPRequestHandlerFactory; - - -class Net_API HTTPServerConnection: public TCPServerConnection - /// This subclass of TCPServerConnection handles HTTP - /// connections. -{ -public: - HTTPServerConnection(const StreamSocket& socket, HTTPServerParams* pParams, HTTPRequestHandlerFactory* pFactory); - /// Creates the HTTPServerConnection. - - virtual ~HTTPServerConnection(); - /// Destroys the HTTPServerConnection. - - void run(); - /// Handles all HTTP requests coming in. - -private: - HTTPServerParams* _pParams; - HTTPRequestHandlerFactory* _pFactory; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPServerConnection_INCLUDED +// +// HTTPServerConnection.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerConnection.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPServerConnection +// +// Definition of the HTTPServerConnection 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_HTTPServerConnection_INCLUDED +#define Net_HTTPServerConnection_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/TCPServerConnection.h" + + +namespace Poco { +namespace Net { + + +class HTTPServerParams; +class HTTPRequestHandlerFactory; + + +class Net_API HTTPServerConnection: public TCPServerConnection + /// This subclass of TCPServerConnection handles HTTP + /// connections. +{ +public: + HTTPServerConnection(const StreamSocket& socket, HTTPServerParams* pParams, HTTPRequestHandlerFactory* pFactory); + /// Creates the HTTPServerConnection. + + virtual ~HTTPServerConnection(); + /// Destroys the HTTPServerConnection. + + void run(); + /// Handles all HTTP requests coming in. + +private: + HTTPServerParams* _pParams; + HTTPRequestHandlerFactory* _pFactory; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPServerConnection_INCLUDED diff --git a/Net/include/Poco/Net/HTTPServerConnectionFactory.h b/Net/include/Poco/Net/HTTPServerConnectionFactory.h index b3d93d93d..3446c9653 100644 --- a/Net/include/Poco/Net/HTTPServerConnectionFactory.h +++ b/Net/include/Poco/Net/HTTPServerConnectionFactory.h @@ -1,79 +1,79 @@ -// -// HTTPServerConnectionFactory.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerConnectionFactory.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPServerConnectionFactory -// -// Definition of the HTTPServerConnectionFactory 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_HTTPServerConnectionFactory_INCLUDED -#define Net_HTTPServerConnectionFactory_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/TCPServerConnectionFactory.h" - - -namespace Poco { -namespace Net { - - -class HTTPServerParams; -class HTTPRequestHandlerFactory; - - -class Net_API HTTPServerConnectionFactory: public TCPServerConnectionFactory - /// This implementation of a TCPServerConnectionFactory - /// is used by HTTPServer to create HTTPServerConnection objects. -{ -public: - HTTPServerConnectionFactory(HTTPServerParams* pParams, HTTPRequestHandlerFactory* pFactory); - /// Creates the HTTPServerConnectionFactory. - - ~HTTPServerConnectionFactory(); - /// Destroys the HTTPServerConnectionFactory. - - TCPServerConnection* createConnection(const StreamSocket& socket); - /// Creates an instance of HTTPServerConnection - /// using the given StreamSocket. - -private: - HTTPServerParams* _pParams; - HTTPRequestHandlerFactory* _pFactory; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPServerConnectionFactory_INCLUDED +// +// HTTPServerConnectionFactory.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerConnectionFactory.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPServerConnectionFactory +// +// Definition of the HTTPServerConnectionFactory 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_HTTPServerConnectionFactory_INCLUDED +#define Net_HTTPServerConnectionFactory_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/TCPServerConnectionFactory.h" + + +namespace Poco { +namespace Net { + + +class HTTPServerParams; +class HTTPRequestHandlerFactory; + + +class Net_API HTTPServerConnectionFactory: public TCPServerConnectionFactory + /// This implementation of a TCPServerConnectionFactory + /// is used by HTTPServer to create HTTPServerConnection objects. +{ +public: + HTTPServerConnectionFactory(HTTPServerParams* pParams, HTTPRequestHandlerFactory* pFactory); + /// Creates the HTTPServerConnectionFactory. + + ~HTTPServerConnectionFactory(); + /// Destroys the HTTPServerConnectionFactory. + + TCPServerConnection* createConnection(const StreamSocket& socket); + /// Creates an instance of HTTPServerConnection + /// using the given StreamSocket. + +private: + HTTPServerParams* _pParams; + HTTPRequestHandlerFactory* _pFactory; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPServerConnectionFactory_INCLUDED diff --git a/Net/include/Poco/Net/HTTPServerParams.h b/Net/include/Poco/Net/HTTPServerParams.h index 61f1057c0..a699d4f18 100644 --- a/Net/include/Poco/Net/HTTPServerParams.h +++ b/Net/include/Poco/Net/HTTPServerParams.h @@ -1,174 +1,174 @@ -// -// HTTPServerParams.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerParams.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPServerParams -// -// Definition of the HTTPServerParams 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_HTTPServerParams_INCLUDED -#define Net_HTTPServerParams_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/TCPServerParams.h" - - -namespace Poco { -namespace Net { - - -class Net_API HTTPServerParams: public TCPServerParams - /// This class is used to specify parameters to both the - /// HTTPServer, as well as to HTTPRequestHandler objects. - /// - /// Subclasses may add new parameters to the class. -{ -public: - HTTPServerParams(); - /// Creates the HTTPServerParams. - /// - /// Sets the following default values: - /// - timeout: 60 seconds - /// - keepAlive: true - /// - maxKeepAliveRequests: 0 - /// - keepAliveTimeout: 10 seconds - - void setServerName(const std::string& serverName); - /// Sets the name and port (name:port) that the server uses to identify itself. - /// - /// If this is not set to valid DNS name for your host, server-generated - /// redirections will not work. - - const std::string& getServerName() const; - /// Returns the name and port (name:port) that the server uses to identify itself. - - void setSoftwareVersion(const std::string& softwareVersion); - /// Sets the server software name and version that the server uses to identify - /// itself. If this is set to a non-empty string, the server will - /// automatically include a Server header field with the value given - /// here in every response it sends. - /// - /// The format of the softwareVersion string should be name/version - /// (e.g. MyHTTPServer/1.0). - - const std::string& getSoftwareVersion() const; - /// Returns the server software name and version that the server uses to - /// identify itself. - - void setTimeout(const Poco::Timespan& timeout); - /// Sets the connection timeout for HTTP connections. - - const Poco::Timespan& getTimeout() const; - /// Returns the connection timeout for HTTP connections. - - void setKeepAlive(bool keepAlive); - /// Enables (keepAlive == true) or disables (keepAlive == false) - /// persistent connections. - - bool getKeepAlive() const; - /// Returns true iff persistent connections are enabled. - - 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. - - void setMaxKeepAliveRequests(int maxKeepAliveRequests); - /// Specifies the maximun number of requests allowed - /// during a persistent connection. 0 means unlimited - /// connections. - - int getMaxKeepAliveRequests() const; - /// Returns the maximum number of requests allowed - /// during a persistent connection, or 0 if - /// unlimited connections are allowed. - -protected: - virtual ~HTTPServerParams(); - /// Destroys the HTTPServerParams. - -private: - std::string _serverName; - std::string _softwareVersion; - Poco::Timespan _timeout; - bool _keepAlive; - int _maxKeepAliveRequests; - Poco::Timespan _keepAliveTimeout; -}; - - -// -// inlines -// -inline const std::string& HTTPServerParams::getServerName() const -{ - return _serverName; -} - - -inline const std::string& HTTPServerParams::getSoftwareVersion() const -{ - return _softwareVersion; -} - - -inline const Poco::Timespan& HTTPServerParams::getTimeout() const -{ - return _timeout; -} - - -inline bool HTTPServerParams::getKeepAlive() const -{ - return _keepAlive; -} - - -inline int HTTPServerParams::getMaxKeepAliveRequests() const -{ - return _maxKeepAliveRequests; -} - - -inline const Poco::Timespan& HTTPServerParams::getKeepAliveTimeout() const -{ - return _keepAliveTimeout; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPServerParams_INCLUDED +// +// HTTPServerParams.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerParams.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPServerParams +// +// Definition of the HTTPServerParams 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_HTTPServerParams_INCLUDED +#define Net_HTTPServerParams_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/TCPServerParams.h" + + +namespace Poco { +namespace Net { + + +class Net_API HTTPServerParams: public TCPServerParams + /// This class is used to specify parameters to both the + /// HTTPServer, as well as to HTTPRequestHandler objects. + /// + /// Subclasses may add new parameters to the class. +{ +public: + HTTPServerParams(); + /// Creates the HTTPServerParams. + /// + /// Sets the following default values: + /// - timeout: 60 seconds + /// - keepAlive: true + /// - maxKeepAliveRequests: 0 + /// - keepAliveTimeout: 10 seconds + + void setServerName(const std::string& serverName); + /// Sets the name and port (name:port) that the server uses to identify itself. + /// + /// If this is not set to valid DNS name for your host, server-generated + /// redirections will not work. + + const std::string& getServerName() const; + /// Returns the name and port (name:port) that the server uses to identify itself. + + void setSoftwareVersion(const std::string& softwareVersion); + /// Sets the server software name and version that the server uses to identify + /// itself. If this is set to a non-empty string, the server will + /// automatically include a Server header field with the value given + /// here in every response it sends. + /// + /// The format of the softwareVersion string should be name/version + /// (e.g. MyHTTPServer/1.0). + + const std::string& getSoftwareVersion() const; + /// Returns the server software name and version that the server uses to + /// identify itself. + + void setTimeout(const Poco::Timespan& timeout); + /// Sets the connection timeout for HTTP connections. + + const Poco::Timespan& getTimeout() const; + /// Returns the connection timeout for HTTP connections. + + void setKeepAlive(bool keepAlive); + /// Enables (keepAlive == true) or disables (keepAlive == false) + /// persistent connections. + + bool getKeepAlive() const; + /// Returns true iff persistent connections are enabled. + + 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. + + void setMaxKeepAliveRequests(int maxKeepAliveRequests); + /// Specifies the maximun number of requests allowed + /// during a persistent connection. 0 means unlimited + /// connections. + + int getMaxKeepAliveRequests() const; + /// Returns the maximum number of requests allowed + /// during a persistent connection, or 0 if + /// unlimited connections are allowed. + +protected: + virtual ~HTTPServerParams(); + /// Destroys the HTTPServerParams. + +private: + std::string _serverName; + std::string _softwareVersion; + Poco::Timespan _timeout; + bool _keepAlive; + int _maxKeepAliveRequests; + Poco::Timespan _keepAliveTimeout; +}; + + +// +// inlines +// +inline const std::string& HTTPServerParams::getServerName() const +{ + return _serverName; +} + + +inline const std::string& HTTPServerParams::getSoftwareVersion() const +{ + return _softwareVersion; +} + + +inline const Poco::Timespan& HTTPServerParams::getTimeout() const +{ + return _timeout; +} + + +inline bool HTTPServerParams::getKeepAlive() const +{ + return _keepAlive; +} + + +inline int HTTPServerParams::getMaxKeepAliveRequests() const +{ + return _maxKeepAliveRequests; +} + + +inline const Poco::Timespan& HTTPServerParams::getKeepAliveTimeout() const +{ + return _keepAliveTimeout; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPServerParams_INCLUDED diff --git a/Net/include/Poco/Net/HTTPServerRequest.h b/Net/include/Poco/Net/HTTPServerRequest.h index 0c6b5bd2a..bb1d1ff52 100644 --- a/Net/include/Poco/Net/HTTPServerRequest.h +++ b/Net/include/Poco/Net/HTTPServerRequest.h @@ -1,132 +1,132 @@ -// -// HTTPServerRequest.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerRequest.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPServerRequest -// -// Definition of the HTTPServerRequest 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_HTTPServerRequest_INCLUDED -#define Net_HTTPServerRequest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPRequest.h" -#include "Poco/Net/SocketAddress.h" -#include - - -namespace Poco { -namespace Net { - - -class HTTPServerSession; -class HTTPServerParams; - - -class Net_API HTTPServerRequest: public HTTPRequest - /// This subclass 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(); - /// Destroys the HTTPServerRequest. - - std::istream& stream(); - /// Returns the input stream for reading - /// the request body. - /// - /// The stream is valid until the HTTPServerRequest - /// 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. - -private: - std::istream* _pStream; - HTTPServerParams* _pParams; - SocketAddress _clientAddress; - SocketAddress _serverAddress; -}; - - -// -// 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 - - -#endif // Net_HTTPServerRequest_INCLUDED +// +// HTTPServerRequest.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerRequest.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPServerRequest +// +// Definition of the HTTPServerRequest 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_HTTPServerRequest_INCLUDED +#define Net_HTTPServerRequest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPRequest.h" +#include "Poco/Net/SocketAddress.h" +#include + + +namespace Poco { +namespace Net { + + +class HTTPServerSession; +class HTTPServerParams; + + +class Net_API HTTPServerRequest: public HTTPRequest + /// This subclass 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(); + /// Destroys the HTTPServerRequest. + + std::istream& stream(); + /// Returns the input stream for reading + /// the request body. + /// + /// The stream is valid until the HTTPServerRequest + /// 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. + +private: + std::istream* _pStream; + HTTPServerParams* _pParams; + SocketAddress _clientAddress; + SocketAddress _serverAddress; +}; + + +// +// 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 + + +#endif // Net_HTTPServerRequest_INCLUDED diff --git a/Net/include/Poco/Net/HTTPServerResponse.h b/Net/include/Poco/Net/HTTPServerResponse.h index 8c2a8c500..7c6c9dff4 100644 --- a/Net/include/Poco/Net/HTTPServerResponse.h +++ b/Net/include/Poco/Net/HTTPServerResponse.h @@ -1,122 +1,122 @@ -// -// HTTPServerResponse.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerResponse.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPServerResponse -// -// Definition of the HTTPServerResponse 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_HTTPServerResponse_INCLUDED -#define Net_HTTPServerResponse_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPResponse.h" -#include - - -namespace Poco { -namespace Net { - - -class HTTPServerSession; -class HTTPCookie; - - -class Net_API HTTPServerResponse: public HTTPResponse - /// This subclass of HTTPResponse 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: - HTTPServerResponse(HTTPServerSession& session); - /// Creates the HTTPServerResponse. - - ~HTTPServerResponse(); - /// Destroys the HTTPServerResponse. - - 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() 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() or redirect() - /// has been called. - /// - /// Throws a FileNotFoundException if the file - /// cannot be found, or an OpenFileException if - /// the file cannot be opened. - - 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. - -private: - HTTPServerSession& _session; - std::ostream* _pStream; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPServerResponse_INCLUDED +// +// HTTPServerResponse.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerResponse.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPServerResponse +// +// Definition of the HTTPServerResponse 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_HTTPServerResponse_INCLUDED +#define Net_HTTPServerResponse_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPResponse.h" +#include + + +namespace Poco { +namespace Net { + + +class HTTPServerSession; +class HTTPCookie; + + +class Net_API HTTPServerResponse: public HTTPResponse + /// This subclass of HTTPResponse 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: + HTTPServerResponse(HTTPServerSession& session); + /// Creates the HTTPServerResponse. + + ~HTTPServerResponse(); + /// Destroys the HTTPServerResponse. + + 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() 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() or redirect() + /// has been called. + /// + /// Throws a FileNotFoundException if the file + /// cannot be found, or an OpenFileException if + /// the file cannot be opened. + + 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. + +private: + HTTPServerSession& _session; + std::ostream* _pStream; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPServerResponse_INCLUDED diff --git a/Net/include/Poco/Net/HTTPServerSession.h b/Net/include/Poco/Net/HTTPServerSession.h index 652e91548..4ec18bdda 100644 --- a/Net/include/Poco/Net/HTTPServerSession.h +++ b/Net/include/Poco/Net/HTTPServerSession.h @@ -1,87 +1,87 @@ -// -// HTTPServerSession.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerSession.h#1 $ -// -// Library: Net -// Package: HTTPServer -// Module: HTTPServerSession -// -// Definition of the HTTPServerSession 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_HTTPServerSession_INCLUDED -#define Net_HTTPServerSession_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPSession.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Timespan.h" - - -namespace Poco { -namespace Net { - - -class HTTPServerParams; - - -class Net_API HTTPServerSession: public HTTPSession - /// This class handles the server side of a - /// HTTP session. It is used internally by - /// HTTPServer. -{ -public: - HTTPServerSession(const StreamSocket& socket, HTTPServerParams* pParams); - /// Creates the HTTPServerSession. - - virtual ~HTTPServerSession(); - /// Destroys the HTTPServerSession. - - bool hasMoreRequests(); - /// Returns true if there are requests available. - - SocketAddress clientAddress(); - /// Returns the client's address. - - SocketAddress serverAddress(); - /// Returns the server's address. - -private: - bool _firstRequest; - Poco::Timespan _keepAliveTimeout; - int _maxKeepAliveRequests; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPServerSession_INCLUDED +// +// HTTPServerSession.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPServerSession.h#1 $ +// +// Library: Net +// Package: HTTPServer +// Module: HTTPServerSession +// +// Definition of the HTTPServerSession 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_HTTPServerSession_INCLUDED +#define Net_HTTPServerSession_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPSession.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Timespan.h" + + +namespace Poco { +namespace Net { + + +class HTTPServerParams; + + +class Net_API HTTPServerSession: public HTTPSession + /// This class handles the server side of a + /// HTTP session. It is used internally by + /// HTTPServer. +{ +public: + HTTPServerSession(const StreamSocket& socket, HTTPServerParams* pParams); + /// Creates the HTTPServerSession. + + virtual ~HTTPServerSession(); + /// Destroys the HTTPServerSession. + + bool hasMoreRequests(); + /// Returns true if there are requests available. + + SocketAddress clientAddress(); + /// Returns the client's address. + + SocketAddress serverAddress(); + /// Returns the server's address. + +private: + bool _firstRequest; + Poco::Timespan _keepAliveTimeout; + int _maxKeepAliveRequests; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPServerSession_INCLUDED diff --git a/Net/include/Poco/Net/HTTPSession.h b/Net/include/Poco/Net/HTTPSession.h index 17340c016..8240ad4c5 100644 --- a/Net/include/Poco/Net/HTTPSession.h +++ b/Net/include/Poco/Net/HTTPSession.h @@ -1,214 +1,214 @@ -// -// HTTPSession.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPSession.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPSession -// -// Definition of the HTTPSession 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_HTTPSession_INCLUDED -#define Net_HTTPSession_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Timespan.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API HTTPSession - /// HTTPSession implements basic HTTP session management - /// for both HTTP clients and HTTP servers. - /// - /// HTTPSession implements buffering for HTTP connections, as well - /// as specific support for the various HTTP stream classes. - /// - /// This class can not be instantiated. HTTPClientSession or - /// HTTPServerSession must be used instead. -{ -public: - void setKeepAlive(bool keepAlive); - /// Sets the keep-alive flag for this session. - /// - /// If the keep-alive flag is enabled, persistent - /// HTTP/1.1 connections are supported. - - bool getKeepAlive() const; - /// Returns the value of the keep-alive flag for - /// this session. - - void setTimeout(const Poco::Timespan& timeout); - /// Sets the timeout for the HTTP session. - - Poco::Timespan getTimeout() const; - /// Returns the timeout for the HTTP session. - - bool connected() const; - /// Returns true if the underlying socket is connected. - - void abort(); - /// Aborts a session in progress by shutting down - /// and closing the underlying socket. - - const Poco::Exception* networkException() const; - /// If sending or receiving data over the underlying - /// socket connection resulted in an exception, a - /// pointer to this exception is returned. - /// - /// Otherwise, NULL is returned. - - enum - { - HTTP_PORT = 80 - }; - -protected: - HTTPSession(); - /// Creates a HTTP session using an - /// unconnected stream socket. - - HTTPSession(const StreamSocket& socket); - /// Creates a HTTP session using the - /// given socket. The session takes ownership - /// of the socket and closes it when it's no - /// longer used. - - HTTPSession(const StreamSocket& socket, bool keepAlive); - /// Creates a HTTP session using the - /// given socket. The session takes ownership - /// of the socket and closes it when it's no - /// longer used. - - virtual ~HTTPSession(); - /// Destroys the HTTPSession and closes the - /// underlying socket. - - int get(); - /// Returns the next byte in the buffer. - /// Reads more data from the socket if there are - /// no bytes left in the buffer. - - int peek(); - /// Peeks at the next character in the buffer. - /// Reads more data from the socket if there are - /// no bytes left in the buffer. - - virtual int read(char* buffer, std::streamsize length); - /// Reads up to length bytes. - /// - /// If there is data in the buffer, this data - /// is returned. Otherwise, data is read from - /// the socket to avoid unnecessary buffering. - - virtual int write(const char* buffer, std::streamsize length); - /// Writes data to the socket. - - int receive(char* buffer, int length); - /// Reads up to length bytes. - - StreamSocket& socket(); - /// Returns a reference to the underlying socket. - - void refill(); - /// Refills the internal buffer. - - virtual void connect(const SocketAddress& address); - /// Connects the underlying socket to the given address - /// and sets the socket's receive timeout. - - void close(); - /// Closes the underlying socket. - - void setException(const Poco::Exception& exc); - /// Stores a clone of the exception. - -private: - enum - { - HTTP_DEFAULT_TIMEOUT = 60000000 - }; - - HTTPSession(const HTTPSession&); - HTTPSession& operator = (const HTTPSession&); - - StreamSocket _socket; - char* _pBuffer; - char* _pCurrent; - char* _pEnd; - bool _keepAlive; - Poco::Timespan _timeout; - Poco::Exception* _pException; - - friend class HTTPStreamBuf; - friend class HTTPHeaderStreamBuf; - friend class HTTPFixedLengthStreamBuf; - friend class HTTPChunkedStreamBuf; -}; - - -// -// inlines -// -inline bool HTTPSession::getKeepAlive() const -{ - return _keepAlive; -} - - -inline Poco::Timespan HTTPSession::getTimeout() const -{ - return _timeout; -} - - -inline StreamSocket& HTTPSession::socket() -{ - return _socket; -} - - -inline const Poco::Exception* HTTPSession::networkException() const -{ - return _pException; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPSession_INCLUDED +// +// HTTPSession.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPSession.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPSession +// +// Definition of the HTTPSession 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_HTTPSession_INCLUDED +#define Net_HTTPSession_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Timespan.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API HTTPSession + /// HTTPSession implements basic HTTP session management + /// for both HTTP clients and HTTP servers. + /// + /// HTTPSession implements buffering for HTTP connections, as well + /// as specific support for the various HTTP stream classes. + /// + /// This class can not be instantiated. HTTPClientSession or + /// HTTPServerSession must be used instead. +{ +public: + void setKeepAlive(bool keepAlive); + /// Sets the keep-alive flag for this session. + /// + /// If the keep-alive flag is enabled, persistent + /// HTTP/1.1 connections are supported. + + bool getKeepAlive() const; + /// Returns the value of the keep-alive flag for + /// this session. + + void setTimeout(const Poco::Timespan& timeout); + /// Sets the timeout for the HTTP session. + + Poco::Timespan getTimeout() const; + /// Returns the timeout for the HTTP session. + + bool connected() const; + /// Returns true if the underlying socket is connected. + + void abort(); + /// Aborts a session in progress by shutting down + /// and closing the underlying socket. + + const Poco::Exception* networkException() const; + /// If sending or receiving data over the underlying + /// socket connection resulted in an exception, a + /// pointer to this exception is returned. + /// + /// Otherwise, NULL is returned. + + enum + { + HTTP_PORT = 80 + }; + +protected: + HTTPSession(); + /// Creates a HTTP session using an + /// unconnected stream socket. + + HTTPSession(const StreamSocket& socket); + /// Creates a HTTP session using the + /// given socket. The session takes ownership + /// of the socket and closes it when it's no + /// longer used. + + HTTPSession(const StreamSocket& socket, bool keepAlive); + /// Creates a HTTP session using the + /// given socket. The session takes ownership + /// of the socket and closes it when it's no + /// longer used. + + virtual ~HTTPSession(); + /// Destroys the HTTPSession and closes the + /// underlying socket. + + int get(); + /// Returns the next byte in the buffer. + /// Reads more data from the socket if there are + /// no bytes left in the buffer. + + int peek(); + /// Peeks at the next character in the buffer. + /// Reads more data from the socket if there are + /// no bytes left in the buffer. + + virtual int read(char* buffer, std::streamsize length); + /// Reads up to length bytes. + /// + /// If there is data in the buffer, this data + /// is returned. Otherwise, data is read from + /// the socket to avoid unnecessary buffering. + + virtual int write(const char* buffer, std::streamsize length); + /// Writes data to the socket. + + int receive(char* buffer, int length); + /// Reads up to length bytes. + + StreamSocket& socket(); + /// Returns a reference to the underlying socket. + + void refill(); + /// Refills the internal buffer. + + virtual void connect(const SocketAddress& address); + /// Connects the underlying socket to the given address + /// and sets the socket's receive timeout. + + void close(); + /// Closes the underlying socket. + + void setException(const Poco::Exception& exc); + /// Stores a clone of the exception. + +private: + enum + { + HTTP_DEFAULT_TIMEOUT = 60000000 + }; + + HTTPSession(const HTTPSession&); + HTTPSession& operator = (const HTTPSession&); + + StreamSocket _socket; + char* _pBuffer; + char* _pCurrent; + char* _pEnd; + bool _keepAlive; + Poco::Timespan _timeout; + Poco::Exception* _pException; + + friend class HTTPStreamBuf; + friend class HTTPHeaderStreamBuf; + friend class HTTPFixedLengthStreamBuf; + friend class HTTPChunkedStreamBuf; +}; + + +// +// inlines +// +inline bool HTTPSession::getKeepAlive() const +{ + return _keepAlive; +} + + +inline Poco::Timespan HTTPSession::getTimeout() const +{ + return _timeout; +} + + +inline StreamSocket& HTTPSession::socket() +{ + return _socket; +} + + +inline const Poco::Exception* HTTPSession::networkException() const +{ + return _pException; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPSession_INCLUDED diff --git a/Net/include/Poco/Net/HTTPSessionFactory.h b/Net/include/Poco/Net/HTTPSessionFactory.h index a6aad1f8a..c914fb09e 100644 --- a/Net/include/Poco/Net/HTTPSessionFactory.h +++ b/Net/include/Poco/Net/HTTPSessionFactory.h @@ -1,154 +1,154 @@ -// -// HTTPSessionFactory.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPSessionFactory.h#1 $ -// -// Library: Net -// Package: HTTPClient -// Module: HTTPSessionFactory -// -// Definition of the HTTPSessionFactory 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 Net_HTTPSessionFactoryMgr_INCLUDED -#define Net_HTTPSessionFactoryMgr_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Mutex.h" -#include "Poco/URI.h" -#include "Poco/SingletonHolder.h" -#include "Poco/SharedPtr.h" -#include - - -namespace Poco { -namespace Net { - - -class HTTPSessionInstantiator; -class HTTPClientSession; - - -class Net_API HTTPSessionFactory - /// A factory for HTTPClientSession objects. - /// - /// Given a URI, this class creates a HTTPClientSession - /// (for http) or a HTTPSClientSession (for https) for - /// accessing the URI. - /// - /// The actual work of creating the session is done by - /// HTTPSessionInstantiator objects that must be registered - /// with a HTTPSessionFactory. -{ -public: - HTTPSessionFactory(); - /// Creates the HTTPSessionFactory. - - HTTPSessionFactory(const std::string& proxyHost, Poco::UInt16 proxyPort); - /// Creates the HTTPSessionFactory and sets the proxy host and port. - - ~HTTPSessionFactory(); - /// Destroys the HTTPSessionFactory. - - void registerProtocol(const std::string& protocol, HTTPSessionInstantiator* pSessionInstantiator); - /// Registers the session instantiator for the given protocol. - /// The factory takes ownership of the SessionInstantiator. - /// - /// A protocol can be registered more than once. However, only the instantiator - /// that has been registered first is used. Also, for each call to - /// registerProtocol(), a corresponding call to unregisterProtocol() must - /// be made. - - void unregisterProtocol(const std::string& protocol); - /// Removes the registration of a protocol. - /// - /// Throws a NotFoundException if no instantiator has been registered - /// for the given protocol. - - bool supportsProtocol(const std::string& protocol); - /// Returns true if a session instantiator for the given protocol has been registered. - - HTTPClientSession* createClientSession(const Poco::URI& uri); - /// Creates a client session for the given uri scheme. Throws exception if no factory is registered for the given scheme - - const std::string& proxyHost() const; - /// Returns the proxy host, if one has been set, or an empty string otherwise. - - Poco::UInt16 proxyPort() const; - /// Returns the proxy port number, if one has been set, or zero otherwise. - - void setProxy(const std::string& proxyHost, Poco::UInt16 proxyPort); - /// Sets the proxy host and port number. - - static HTTPSessionFactory& defaultFactory(); - /// Returns the default HTTPSessionFactory. - -private: - struct InstantiatorInfo - { - HTTPSessionInstantiator* pIn; - int cnt; - InstantiatorInfo(HTTPSessionInstantiator* pInst); - // no destructor!!! this is by purpose, don't add one! - }; - - - HTTPSessionFactory(const HTTPSessionFactory&); - HTTPSessionFactory& operator = (const HTTPSessionFactory&); - - typedef std::map Instantiators; - - Instantiators _instantiators; - std::string _proxyHost; - Poco::UInt16 _proxyPort; - - mutable Poco::FastMutex _mutex; -}; - - -// -// inlines -// -inline const std::string& HTTPSessionFactory::proxyHost() const -{ - return _proxyHost; -} - - -inline Poco::UInt16 HTTPSessionFactory::proxyPort() const -{ - return _proxyPort; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPSessionFactoryMgr_INCLUDED +// +// HTTPSessionFactory.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPSessionFactory.h#1 $ +// +// Library: Net +// Package: HTTPClient +// Module: HTTPSessionFactory +// +// Definition of the HTTPSessionFactory 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 Net_HTTPSessionFactoryMgr_INCLUDED +#define Net_HTTPSessionFactoryMgr_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Mutex.h" +#include "Poco/URI.h" +#include "Poco/SingletonHolder.h" +#include "Poco/SharedPtr.h" +#include + + +namespace Poco { +namespace Net { + + +class HTTPSessionInstantiator; +class HTTPClientSession; + + +class Net_API HTTPSessionFactory + /// A factory for HTTPClientSession objects. + /// + /// Given a URI, this class creates a HTTPClientSession + /// (for http) or a HTTPSClientSession (for https) for + /// accessing the URI. + /// + /// The actual work of creating the session is done by + /// HTTPSessionInstantiator objects that must be registered + /// with a HTTPSessionFactory. +{ +public: + HTTPSessionFactory(); + /// Creates the HTTPSessionFactory. + + HTTPSessionFactory(const std::string& proxyHost, Poco::UInt16 proxyPort); + /// Creates the HTTPSessionFactory and sets the proxy host and port. + + ~HTTPSessionFactory(); + /// Destroys the HTTPSessionFactory. + + void registerProtocol(const std::string& protocol, HTTPSessionInstantiator* pSessionInstantiator); + /// Registers the session instantiator for the given protocol. + /// The factory takes ownership of the SessionInstantiator. + /// + /// A protocol can be registered more than once. However, only the instantiator + /// that has been registered first is used. Also, for each call to + /// registerProtocol(), a corresponding call to unregisterProtocol() must + /// be made. + + void unregisterProtocol(const std::string& protocol); + /// Removes the registration of a protocol. + /// + /// Throws a NotFoundException if no instantiator has been registered + /// for the given protocol. + + bool supportsProtocol(const std::string& protocol); + /// Returns true if a session instantiator for the given protocol has been registered. + + HTTPClientSession* createClientSession(const Poco::URI& uri); + /// Creates a client session for the given uri scheme. Throws exception if no factory is registered for the given scheme + + const std::string& proxyHost() const; + /// Returns the proxy host, if one has been set, or an empty string otherwise. + + Poco::UInt16 proxyPort() const; + /// Returns the proxy port number, if one has been set, or zero otherwise. + + void setProxy(const std::string& proxyHost, Poco::UInt16 proxyPort); + /// Sets the proxy host and port number. + + static HTTPSessionFactory& defaultFactory(); + /// Returns the default HTTPSessionFactory. + +private: + struct InstantiatorInfo + { + HTTPSessionInstantiator* pIn; + int cnt; + InstantiatorInfo(HTTPSessionInstantiator* pInst); + // no destructor!!! this is by purpose, don't add one! + }; + + + HTTPSessionFactory(const HTTPSessionFactory&); + HTTPSessionFactory& operator = (const HTTPSessionFactory&); + + typedef std::map Instantiators; + + Instantiators _instantiators; + std::string _proxyHost; + Poco::UInt16 _proxyPort; + + mutable Poco::FastMutex _mutex; +}; + + +// +// inlines +// +inline const std::string& HTTPSessionFactory::proxyHost() const +{ + return _proxyHost; +} + + +inline Poco::UInt16 HTTPSessionFactory::proxyPort() const +{ + return _proxyPort; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPSessionFactoryMgr_INCLUDED diff --git a/Net/include/Poco/Net/HTTPSessionInstantiator.h b/Net/include/Poco/Net/HTTPSessionInstantiator.h index 03c0cbfb6..f2512a827 100644 --- a/Net/include/Poco/Net/HTTPSessionInstantiator.h +++ b/Net/include/Poco/Net/HTTPSessionInstantiator.h @@ -1,116 +1,116 @@ -// -// HTTPSessionInstantiator.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPSessionInstantiator.h#1 $ -// -// Library: Net -// Package: HTTPClient -// Module: HTTPSessionInstantiator -// -// Definition of the HTTPSessionInstantiator 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 Net_HTTPSessionInstantiator_INCLUDED -#define Net_HTTPSessionInstantiator_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPSession.h" -#include "Poco/URI.h" - - -namespace Poco { -namespace Net { - - -class HTTPClientSession; - - -class Net_API HTTPSessionInstantiator - /// A factory for HTTPClientSession objects. - /// - /// Creates a HTTP session for a given URI. - /// A HTTPSessionInstantiator is not used directly. - /// Instances are registered with a HTTPSessionFactory, - /// and used through it. -{ -public: - HTTPSessionInstantiator(); - /// Creates the HTTPSessionInstantiator. - - virtual ~HTTPSessionInstantiator(); - /// Destroys the HTTPSessionInstantiator. - - virtual HTTPClientSession* createClientSession(const Poco::URI& uri); - /// Creates a HTTPClientSession for the given URI. - - static void registerInstantiator(); - /// Registers the instantiator with the global HTTPSessionFactory. - - static void unregisterInstantiator(); - /// Unregisters the factory with the global HTTPSessionFactory. - -protected: - void setProxy(const std::string& host, Poco::UInt16 port); - /// Sets the proxy host and port. - /// Called by HTTPSessionFactory. - - const std::string& proxyHost() const; - /// Returns the proxy post. - - Poco::UInt16 proxyPort() const; - /// Returns the proxy port. - -private: - std::string _proxyHost; - Poco::UInt16 _proxyPort; - - friend class HTTPSessionFactory; -}; - - -// -// inlines -// -inline const std::string& HTTPSessionInstantiator::proxyHost() const -{ - return _proxyHost; -} - - -inline Poco::UInt16 HTTPSessionInstantiator::proxyPort() const -{ - return _proxyPort; -} - - -} } // namespace Poco::Net - - -#endif // Net_HTTPSessionInstantiator_INCLUDED +// +// HTTPSessionInstantiator.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPSessionInstantiator.h#1 $ +// +// Library: Net +// Package: HTTPClient +// Module: HTTPSessionInstantiator +// +// Definition of the HTTPSessionInstantiator 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 Net_HTTPSessionInstantiator_INCLUDED +#define Net_HTTPSessionInstantiator_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPSession.h" +#include "Poco/URI.h" + + +namespace Poco { +namespace Net { + + +class HTTPClientSession; + + +class Net_API HTTPSessionInstantiator + /// A factory for HTTPClientSession objects. + /// + /// Creates a HTTP session for a given URI. + /// A HTTPSessionInstantiator is not used directly. + /// Instances are registered with a HTTPSessionFactory, + /// and used through it. +{ +public: + HTTPSessionInstantiator(); + /// Creates the HTTPSessionInstantiator. + + virtual ~HTTPSessionInstantiator(); + /// Destroys the HTTPSessionInstantiator. + + virtual HTTPClientSession* createClientSession(const Poco::URI& uri); + /// Creates a HTTPClientSession for the given URI. + + static void registerInstantiator(); + /// Registers the instantiator with the global HTTPSessionFactory. + + static void unregisterInstantiator(); + /// Unregisters the factory with the global HTTPSessionFactory. + +protected: + void setProxy(const std::string& host, Poco::UInt16 port); + /// Sets the proxy host and port. + /// Called by HTTPSessionFactory. + + const std::string& proxyHost() const; + /// Returns the proxy post. + + Poco::UInt16 proxyPort() const; + /// Returns the proxy port. + +private: + std::string _proxyHost; + Poco::UInt16 _proxyPort; + + friend class HTTPSessionFactory; +}; + + +// +// inlines +// +inline const std::string& HTTPSessionInstantiator::proxyHost() const +{ + return _proxyHost; +} + + +inline Poco::UInt16 HTTPSessionInstantiator::proxyPort() const +{ + return _proxyPort; +} + + +} } // namespace Poco::Net + + +#endif // Net_HTTPSessionInstantiator_INCLUDED diff --git a/Net/include/Poco/Net/HTTPStream.h b/Net/include/Poco/Net/HTTPStream.h index 76230ac6d..df615da14 100644 --- a/Net/include/Poco/Net/HTTPStream.h +++ b/Net/include/Poco/Net/HTTPStream.h @@ -1,124 +1,124 @@ -// -// HTTPStream.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPStream.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPStream -// -// Definition of the HTTPStream 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_HTTPStream_INCLUDED -#define Net_HTTPStream_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPBasicStreamBuf.h" -#include "Poco/MemoryPool.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class HTTPSession; - - -class Net_API HTTPStreamBuf: public HTTPBasicStreamBuf - /// This is the streambuf class used for reading and writing - /// HTTP message bodies. -{ -public: - typedef HTTPBasicStreamBuf::openmode openmode; - - HTTPStreamBuf(HTTPSession& session, openmode mode); - ~HTTPStreamBuf(); - void close(); - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - HTTPSession& _session; - openmode _mode; -}; - - -class Net_API HTTPIOS: public virtual std::ios - /// The base class for HTTPInputStream. -{ -public: - HTTPIOS(HTTPSession& session, HTTPStreamBuf::openmode mode); - ~HTTPIOS(); - HTTPStreamBuf* rdbuf(); - -protected: - HTTPStreamBuf _buf; -}; - - -class Net_API HTTPInputStream: public HTTPIOS, public std::istream - /// This class is for internal use by HTTPSession only. -{ -public: - HTTPInputStream(HTTPSession& session); - ~HTTPInputStream(); - - void* operator new(size_t size); - void operator delete(void* ptr); - -private: - static Poco::MemoryPool _pool; -}; - - -class Net_API HTTPOutputStream: public HTTPIOS, public std::ostream - /// This class is for internal use by HTTPSession only. -{ -public: - HTTPOutputStream(HTTPSession& session); - ~HTTPOutputStream(); - - void* operator new(size_t size); - void operator delete(void* ptr); - -private: - static Poco::MemoryPool _pool; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPStream_INCLUDED +// +// HTTPStream.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPStream.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPStream +// +// Definition of the HTTPStream 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_HTTPStream_INCLUDED +#define Net_HTTPStream_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPBasicStreamBuf.h" +#include "Poco/MemoryPool.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class HTTPSession; + + +class Net_API HTTPStreamBuf: public HTTPBasicStreamBuf + /// This is the streambuf class used for reading and writing + /// HTTP message bodies. +{ +public: + typedef HTTPBasicStreamBuf::openmode openmode; + + HTTPStreamBuf(HTTPSession& session, openmode mode); + ~HTTPStreamBuf(); + void close(); + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + HTTPSession& _session; + openmode _mode; +}; + + +class Net_API HTTPIOS: public virtual std::ios + /// The base class for HTTPInputStream. +{ +public: + HTTPIOS(HTTPSession& session, HTTPStreamBuf::openmode mode); + ~HTTPIOS(); + HTTPStreamBuf* rdbuf(); + +protected: + HTTPStreamBuf _buf; +}; + + +class Net_API HTTPInputStream: public HTTPIOS, public std::istream + /// This class is for internal use by HTTPSession only. +{ +public: + HTTPInputStream(HTTPSession& session); + ~HTTPInputStream(); + + void* operator new(size_t size); + void operator delete(void* ptr); + +private: + static Poco::MemoryPool _pool; +}; + + +class Net_API HTTPOutputStream: public HTTPIOS, public std::ostream + /// This class is for internal use by HTTPSession only. +{ +public: + HTTPOutputStream(HTTPSession& session); + ~HTTPOutputStream(); + + void* operator new(size_t size); + void operator delete(void* ptr); + +private: + static Poco::MemoryPool _pool; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPStream_INCLUDED diff --git a/Net/include/Poco/Net/HTTPStreamFactory.h b/Net/include/Poco/Net/HTTPStreamFactory.h index 342acbd88..099de726c 100644 --- a/Net/include/Poco/Net/HTTPStreamFactory.h +++ b/Net/include/Poco/Net/HTTPStreamFactory.h @@ -1,101 +1,101 @@ -// -// HTTPStreamFactory.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HTTPStreamFactory.h#1 $ -// -// Library: Net -// Package: HTTP -// Module: HTTPStreamFactory -// -// Definition of the HTTPStreamFactory 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_HTTPStreamFactory_INCLUDED -#define Net_HTTPStreamFactory_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/HTTPSession.h" -#include "Poco/URIStreamFactory.h" - - -namespace Poco { -namespace Net { - - -class Net_API HTTPStreamFactory: public Poco::URIStreamFactory - /// An implementation of the URIStreamFactory interface - /// that handles Hyper-Text Transfer Protocol (http) URIs. -{ -public: - HTTPStreamFactory(); - /// Creates the HTTPStreamFactory. - - HTTPStreamFactory(const std::string& proxyHost, Poco::UInt16 proxyPort = HTTPSession::HTTP_PORT); - /// Creates the HTTPStreamFactory. - /// - /// HTTP connections will use the given proxy. - - virtual ~HTTPStreamFactory(); - /// Destroys the HTTPStreamFactory. - - virtual std::istream* open(const Poco::URI& uri); - /// Creates and opens a HTTP stream for the given URI. - /// The URI must be a http://... URI. - /// - /// Throws a NetException if anything goes wrong. - /// - /// Redirect responses are handled and the redirect - /// location is automatically resolved, as long - /// as the redirect location is still accessible - /// via the HTTP protocol. If a redirection to - /// a non http://... URI is received, a - /// UnsupportedRedirectException exception is thrown. - /// The offending URI can then be obtained via the message() - /// method of UnsupportedRedirectException. - - static void registerFactory(); - /// Registers the HTTPStreamFactory with the - /// default URIStreamOpener instance. - -private: - enum - { - MAX_REDIRECTS = 10 - }; - - std::string _proxyHost; - Poco::UInt16 _proxyPort; -}; - - -} } // namespace Poco::Net - - -#endif // Net_HTTPStreamFactory_INCLUDED +// +// HTTPStreamFactory.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HTTPStreamFactory.h#1 $ +// +// Library: Net +// Package: HTTP +// Module: HTTPStreamFactory +// +// Definition of the HTTPStreamFactory 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_HTTPStreamFactory_INCLUDED +#define Net_HTTPStreamFactory_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/HTTPSession.h" +#include "Poco/URIStreamFactory.h" + + +namespace Poco { +namespace Net { + + +class Net_API HTTPStreamFactory: public Poco::URIStreamFactory + /// An implementation of the URIStreamFactory interface + /// that handles Hyper-Text Transfer Protocol (http) URIs. +{ +public: + HTTPStreamFactory(); + /// Creates the HTTPStreamFactory. + + HTTPStreamFactory(const std::string& proxyHost, Poco::UInt16 proxyPort = HTTPSession::HTTP_PORT); + /// Creates the HTTPStreamFactory. + /// + /// HTTP connections will use the given proxy. + + virtual ~HTTPStreamFactory(); + /// Destroys the HTTPStreamFactory. + + virtual std::istream* open(const Poco::URI& uri); + /// Creates and opens a HTTP stream for the given URI. + /// The URI must be a http://... URI. + /// + /// Throws a NetException if anything goes wrong. + /// + /// Redirect responses are handled and the redirect + /// location is automatically resolved, as long + /// as the redirect location is still accessible + /// via the HTTP protocol. If a redirection to + /// a non http://... URI is received, a + /// UnsupportedRedirectException exception is thrown. + /// The offending URI can then be obtained via the message() + /// method of UnsupportedRedirectException. + + static void registerFactory(); + /// Registers the HTTPStreamFactory with the + /// default URIStreamOpener instance. + +private: + enum + { + MAX_REDIRECTS = 10 + }; + + std::string _proxyHost; + Poco::UInt16 _proxyPort; +}; + + +} } // namespace Poco::Net + + +#endif // Net_HTTPStreamFactory_INCLUDED diff --git a/Net/include/Poco/Net/HostEntry.h b/Net/include/Poco/Net/HostEntry.h index c086160d6..ca1266ae5 100644 --- a/Net/include/Poco/Net/HostEntry.h +++ b/Net/include/Poco/Net/HostEntry.h @@ -1,133 +1,133 @@ -// -// HostEntry.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/HostEntry.h#1 $ -// -// Library: Net -// Package: NetCore -// Module: HostEntry -// -// Definition of the HostEntry 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_HostEntry_INCLUDED -#define Net_HostEntry_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketDefs.h" -#include "Poco/Net/IPAddress.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API HostEntry - /// This class stores information about a host - /// such as host name, alias names and a list - /// of IP addresses. -{ -public: - typedef std::vector AliasList; - typedef std::vector AddressList; - - HostEntry(); - /// Creates an empty HostEntry. - - HostEntry(struct hostent* entry); - /// Creates the HostEntry from the data in a hostent structure. - -#if defined(_WIN32) && defined(POCO_HAVE_IPv6) - HostEntry(struct addrinfo* info); - /// Creates the HostEntry from the data in a Windows addrinfo structure. -#endif - - HostEntry(const HostEntry& entry); - /// Creates the HostEntry by copying another one. - - HostEntry& operator = (const HostEntry& entry); - /// Assigns another HostEntry. - - void swap(HostEntry& hostEntry); - /// Swaps the HostEntry with another one. - - ~HostEntry(); - /// Destroys the HostEntry. - - const std::string& name() const; - /// Returns the canonical host name. - - const AliasList& aliases() const; - /// Returns a vector containing alias names for - /// the host name. - - const AddressList& addresses() const; - /// Returns a vector containing the IPAddresses - /// for the host. - -private: - std::string _name; - AliasList _aliases; - AddressList _addresses; -}; - - -// -// inlines -// -inline const std::string& HostEntry::name() const -{ - return _name; -} - - -inline const HostEntry::AliasList& HostEntry::aliases() const -{ - return _aliases; -} - - -inline const HostEntry::AddressList& HostEntry::addresses() const -{ - return _addresses; -} - - -inline void swap(HostEntry& h1, HostEntry& h2) -{ - h1.swap(h2); -} - - -} } // namespace Poco::Net - - -#endif // Net_HostEntry_INCLUDED +// +// HostEntry.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/HostEntry.h#1 $ +// +// Library: Net +// Package: NetCore +// Module: HostEntry +// +// Definition of the HostEntry 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_HostEntry_INCLUDED +#define Net_HostEntry_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketDefs.h" +#include "Poco/Net/IPAddress.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API HostEntry + /// This class stores information about a host + /// such as host name, alias names and a list + /// of IP addresses. +{ +public: + typedef std::vector AliasList; + typedef std::vector AddressList; + + HostEntry(); + /// Creates an empty HostEntry. + + HostEntry(struct hostent* entry); + /// Creates the HostEntry from the data in a hostent structure. + +#if defined(_WIN32) && defined(POCO_HAVE_IPv6) + HostEntry(struct addrinfo* info); + /// Creates the HostEntry from the data in a Windows addrinfo structure. +#endif + + HostEntry(const HostEntry& entry); + /// Creates the HostEntry by copying another one. + + HostEntry& operator = (const HostEntry& entry); + /// Assigns another HostEntry. + + void swap(HostEntry& hostEntry); + /// Swaps the HostEntry with another one. + + ~HostEntry(); + /// Destroys the HostEntry. + + const std::string& name() const; + /// Returns the canonical host name. + + const AliasList& aliases() const; + /// Returns a vector containing alias names for + /// the host name. + + const AddressList& addresses() const; + /// Returns a vector containing the IPAddresses + /// for the host. + +private: + std::string _name; + AliasList _aliases; + AddressList _addresses; +}; + + +// +// inlines +// +inline const std::string& HostEntry::name() const +{ + return _name; +} + + +inline const HostEntry::AliasList& HostEntry::aliases() const +{ + return _aliases; +} + + +inline const HostEntry::AddressList& HostEntry::addresses() const +{ + return _addresses; +} + + +inline void swap(HostEntry& h1, HostEntry& h2) +{ + h1.swap(h2); +} + + +} } // namespace Poco::Net + + +#endif // Net_HostEntry_INCLUDED diff --git a/Net/include/Poco/Net/ICMPClient.h b/Net/include/Poco/Net/ICMPClient.h index cdb45ac3e..e12c38453 100644 --- a/Net/include/Poco/Net/ICMPClient.h +++ b/Net/include/Poco/Net/ICMPClient.h @@ -1,107 +1,107 @@ -// -// ICMPClient.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ICMPClient.h#1 $ -// -// Library: Net -// Package: ICMP -// Module: ICMPClient -// -// Definition of the ICMPClient 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 Net_ICMPClient_INCLUDED -#define Net_ICMPClient_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/ICMPSocket.h" -#include "Poco/Net/ICMPEventArgs.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/BasicEvent.h" - - -namespace Poco { -namespace Net { - - -class Net_API ICMPClient - /// This class provides ICMP Ping functionality. - /// - /// The events are available when class is instantiated - /// and non-static member functions are called. - /// - /// A "lightweight" alternative is direct (without instantiation) - /// use of static member functions. -{ -public: - mutable Poco::BasicEvent pingBegin; - mutable Poco::BasicEvent pingReply; - mutable Poco::BasicEvent pingError; - mutable Poco::BasicEvent pingEnd; - - explicit ICMPClient(IPAddress::Family family); - /// Creates an ICMP client. - - ~ICMPClient(); - /// Destroys the ICMP client. - - int ping(SocketAddress& address, int repeat = 1) const; - /// Pings the specified address [repeat] times. - /// Notifications are posted for events. - /// - /// Returns the number of valid replies. - - int ping(const std::string& address, int repeat = 1) const; - /// Calls ICMPClient::ping(SocketAddress&, int) and - /// returns the result. - /// - /// Returns the number of valid replies. - - static int ping(SocketAddress& address, IPAddress::Family family, int repeat = 1); - /// Pings the specified address [repeat] times. - /// Notifications are not posted for events. - /// - /// Returns the number of valid replies. - - static int pingIPv4(const std::string& address, int repeat = 1); - /// Calls ICMPClient::ping(SocketAddress&, int) and - /// returns the result. - /// - /// Returns the number of valid replies. - -private: - mutable IPAddress::Family _family; -}; - - -} } // namespace Poco::Net - - -#endif // Net_ICMPClient_INCLUDED +// +// ICMPClient.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ICMPClient.h#1 $ +// +// Library: Net +// Package: ICMP +// Module: ICMPClient +// +// Definition of the ICMPClient 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 Net_ICMPClient_INCLUDED +#define Net_ICMPClient_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/ICMPSocket.h" +#include "Poco/Net/ICMPEventArgs.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/BasicEvent.h" + + +namespace Poco { +namespace Net { + + +class Net_API ICMPClient + /// This class provides ICMP Ping functionality. + /// + /// The events are available when class is instantiated + /// and non-static member functions are called. + /// + /// A "lightweight" alternative is direct (without instantiation) + /// use of static member functions. +{ +public: + mutable Poco::BasicEvent pingBegin; + mutable Poco::BasicEvent pingReply; + mutable Poco::BasicEvent pingError; + mutable Poco::BasicEvent pingEnd; + + explicit ICMPClient(IPAddress::Family family); + /// Creates an ICMP client. + + ~ICMPClient(); + /// Destroys the ICMP client. + + int ping(SocketAddress& address, int repeat = 1) const; + /// Pings the specified address [repeat] times. + /// Notifications are posted for events. + /// + /// Returns the number of valid replies. + + int ping(const std::string& address, int repeat = 1) const; + /// Calls ICMPClient::ping(SocketAddress&, int) and + /// returns the result. + /// + /// Returns the number of valid replies. + + static int ping(SocketAddress& address, IPAddress::Family family, int repeat = 1); + /// Pings the specified address [repeat] times. + /// Notifications are not posted for events. + /// + /// Returns the number of valid replies. + + static int pingIPv4(const std::string& address, int repeat = 1); + /// Calls ICMPClient::ping(SocketAddress&, int) and + /// returns the result. + /// + /// Returns the number of valid replies. + +private: + mutable IPAddress::Family _family; +}; + + +} } // namespace Poco::Net + + +#endif // Net_ICMPClient_INCLUDED diff --git a/Net/include/Poco/Net/ICMPEventArgs.h b/Net/include/Poco/Net/ICMPEventArgs.h index abb9bd286..542144348 100644 --- a/Net/include/Poco/Net/ICMPEventArgs.h +++ b/Net/include/Poco/Net/ICMPEventArgs.h @@ -1,188 +1,188 @@ -// -// ICMPEventArgs.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ICMPEventArgs.h#1 $ -// -// Library: Net -// Package: ICMP -// Module: ICMPEventArgs -// -// Definition 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. -// - - -#ifndef Net_ICMPEventArgs_INCLUDED -#define Net_ICMPEventArgs_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketAddress.h" -#include -#undef min // macros collide with valarray::min() and valarray::max() -#undef max -#include - - -namespace Poco { -namespace Net { - - -class Net_API ICMPEventArgs - /// The purpose of the ICMPEventArgs class is to be used as template parameter - /// to instantiate event members in ICMPClient class. - /// When clients register for an event notification, the reference to the class is - /// passed to the handler function to provide information about the event. -{ -public: - ICMPEventArgs(const SocketAddress& address, int repetitions, int dataSize, int ttl); - /// Creates ICMPEventArgs. - - virtual ~ICMPEventArgs(); - /// Destroys ICMPEventArgs. - - std::string hostName() const; - /// Tries to resolve the target IP address into host name. - /// If unsuccessful, all exceptions are silently ignored and - /// the IP address is returned. - - std::string hostAddress() const; - /// Returns the target IP address. - - int repetitions() const; - /// Returns the number of repetitions for the ping operation. - - int dataSize() const; - /// Returns the packet data size in bytes. - - int ttl() const; - /// Returns time to live. - - int sent() const; - /// Returns the number of packets sent. - - int received() const; - /// Returns the number of packets received. - - int replyTime(int index = -1) const; - /// Returns the reply time for the request specified with index. - /// If index == -1 (default), returns the most recent reply time. - - const std::string& error(int index = -1) const; - /// Returns the error string for the request specified with index. - /// If index == -1 (default), returns the most recent error string. - - int minRTT() const; - /// Returns the minimum round trip time for a sequence of requests. - - int maxRTT() const; - /// Returns the maximum round trip time for a sequence of requests. - - int avgRTT() const; - /// Returns the average round trip time for a sequence of requests. - - float percent() const; - /// Returns the success percentage for a sequence of requests. - -private: - ICMPEventArgs(); - - void setRepetitions(int repetitions); - void setDataSize(int dataSize); - void setTTL(int ttl); - void setReplyTime(int index, int time); - void setError(int index, const std::string& text); - ICMPEventArgs& operator ++ (); - ICMPEventArgs operator ++ (int); - static int zeroVal(int n); - - SocketAddress _address; - int _sent; - int _dataSize; - int _ttl; - std::valarray _rtt; - std::vector _errors; - - friend class ICMPClient; -}; - - -// -// inlines -// -inline int ICMPEventArgs::repetitions() const -{ - return (int) _rtt.size(); -} - - -inline void ICMPEventArgs::setDataSize(int dataSize) -{ - _dataSize = dataSize; -} - - -inline int ICMPEventArgs::dataSize() const -{ - return _dataSize; -} - - -inline void ICMPEventArgs::setTTL(int ttl) -{ - _ttl = ttl; -} - - -inline int ICMPEventArgs::ttl() const -{ - return _ttl; -} - - -inline int ICMPEventArgs::sent() const -{ - return _sent; -} - - -inline int ICMPEventArgs::minRTT() const -{ - return _rtt.min(); -} - - -inline int ICMPEventArgs::maxRTT() const -{ - return _rtt.max(); -} - - -} } // namespace Poco::Net - - -#endif +// +// ICMPEventArgs.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ICMPEventArgs.h#1 $ +// +// Library: Net +// Package: ICMP +// Module: ICMPEventArgs +// +// Definition 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. +// + + +#ifndef Net_ICMPEventArgs_INCLUDED +#define Net_ICMPEventArgs_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketAddress.h" +#include +#undef min // macros collide with valarray::min() and valarray::max() +#undef max +#include + + +namespace Poco { +namespace Net { + + +class Net_API ICMPEventArgs + /// The purpose of the ICMPEventArgs class is to be used as template parameter + /// to instantiate event members in ICMPClient class. + /// When clients register for an event notification, the reference to the class is + /// passed to the handler function to provide information about the event. +{ +public: + ICMPEventArgs(const SocketAddress& address, int repetitions, int dataSize, int ttl); + /// Creates ICMPEventArgs. + + virtual ~ICMPEventArgs(); + /// Destroys ICMPEventArgs. + + std::string hostName() const; + /// Tries to resolve the target IP address into host name. + /// If unsuccessful, all exceptions are silently ignored and + /// the IP address is returned. + + std::string hostAddress() const; + /// Returns the target IP address. + + int repetitions() const; + /// Returns the number of repetitions for the ping operation. + + int dataSize() const; + /// Returns the packet data size in bytes. + + int ttl() const; + /// Returns time to live. + + int sent() const; + /// Returns the number of packets sent. + + int received() const; + /// Returns the number of packets received. + + int replyTime(int index = -1) const; + /// Returns the reply time for the request specified with index. + /// If index == -1 (default), returns the most recent reply time. + + const std::string& error(int index = -1) const; + /// Returns the error string for the request specified with index. + /// If index == -1 (default), returns the most recent error string. + + int minRTT() const; + /// Returns the minimum round trip time for a sequence of requests. + + int maxRTT() const; + /// Returns the maximum round trip time for a sequence of requests. + + int avgRTT() const; + /// Returns the average round trip time for a sequence of requests. + + float percent() const; + /// Returns the success percentage for a sequence of requests. + +private: + ICMPEventArgs(); + + void setRepetitions(int repetitions); + void setDataSize(int dataSize); + void setTTL(int ttl); + void setReplyTime(int index, int time); + void setError(int index, const std::string& text); + ICMPEventArgs& operator ++ (); + ICMPEventArgs operator ++ (int); + static int zeroVal(int n); + + SocketAddress _address; + int _sent; + int _dataSize; + int _ttl; + std::valarray _rtt; + std::vector _errors; + + friend class ICMPClient; +}; + + +// +// inlines +// +inline int ICMPEventArgs::repetitions() const +{ + return (int) _rtt.size(); +} + + +inline void ICMPEventArgs::setDataSize(int dataSize) +{ + _dataSize = dataSize; +} + + +inline int ICMPEventArgs::dataSize() const +{ + return _dataSize; +} + + +inline void ICMPEventArgs::setTTL(int ttl) +{ + _ttl = ttl; +} + + +inline int ICMPEventArgs::ttl() const +{ + return _ttl; +} + + +inline int ICMPEventArgs::sent() const +{ + return _sent; +} + + +inline int ICMPEventArgs::minRTT() const +{ + return _rtt.min(); +} + + +inline int ICMPEventArgs::maxRTT() const +{ + return _rtt.max(); +} + + +} } // namespace Poco::Net + + +#endif diff --git a/Net/include/Poco/Net/ICMPPacket.h b/Net/include/Poco/Net/ICMPPacket.h index 91a101630..ed9eb40a1 100644 --- a/Net/include/Poco/Net/ICMPPacket.h +++ b/Net/include/Poco/Net/ICMPPacket.h @@ -1,111 +1,111 @@ -// -// ICMPPacket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ICMPPacket.h#1 $ -// -// Library: Net -// Package: ICMP -// Module: ICMPPacket -// -// Definition of the ICMPPacket 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 Net_ICMPPacket_INCLUDED -#define Net_ICMPPacket_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Net/Socket.h" -#include "Poco/Net/ICMPPacketImpl.h" - - -namespace Poco { -namespace Net { - - -class Net_API ICMPPacket - /// This class is the ICMP packet abstraction. -{ -public: - ICMPPacket(IPAddress::Family family, int dataSize = 48); - /// Creates an ICMPPacket of specified family. - - ~ICMPPacket(); - /// Destroys the ICMPPacket. - - const Poco::UInt8* packet(); - /// Returns raw ICMP packet. ICMP header and data are included in the returned packet. - - int packetSize() const; - /// Returns the total length of packet (header + data); - - Poco::UInt16 sequence() const; - /// Returns the most recent sequence number generated. - - void setDataSize(int dataSize); - /// Sets data size. - - int getDataSize() const; - /// Returns data size. - - int maxPacketSize() const; - /// Returns the total length of packet (header + data); - - struct timeval time(Poco::UInt8* buffer = 0, int length = 0) const; - /// Returns current epoch time if either buffer or length are equal to zero. - /// Otherwise, it extracts the time value from the supplied buffer and - /// returns the extracted value. - /// - /// Supplied buffer includes IP header, ICMP header and data. - - bool validReplyID(Poco::UInt8* buffer, int length) const; - /// Returns true if the extracted id is recognized - /// (equals the process id). - /// - /// Supplied buffer includes IP header, ICMP header and data. - - std::string errorDescription(Poco::UInt8* buffer, int length); - /// Returns error description string. - /// If supplied buffer contains an ICMP echo reply packet, an - /// empty string is returned indicating the absence of error. - /// - /// Supplied buffer includes IP header, ICMP header and data. - - std::string typeDescription(int typeId); - /// Returns the description of the packet type. - -private: - ICMPPacketImpl* _pImpl; -}; - - -} } // namespace Poco::Net - - -#endif // Net_ICMPPacket_INCLUDED +// +// ICMPPacket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ICMPPacket.h#1 $ +// +// Library: Net +// Package: ICMP +// Module: ICMPPacket +// +// Definition of the ICMPPacket 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 Net_ICMPPacket_INCLUDED +#define Net_ICMPPacket_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Net/Socket.h" +#include "Poco/Net/ICMPPacketImpl.h" + + +namespace Poco { +namespace Net { + + +class Net_API ICMPPacket + /// This class is the ICMP packet abstraction. +{ +public: + ICMPPacket(IPAddress::Family family, int dataSize = 48); + /// Creates an ICMPPacket of specified family. + + ~ICMPPacket(); + /// Destroys the ICMPPacket. + + const Poco::UInt8* packet(); + /// Returns raw ICMP packet. ICMP header and data are included in the returned packet. + + int packetSize() const; + /// Returns the total length of packet (header + data); + + Poco::UInt16 sequence() const; + /// Returns the most recent sequence number generated. + + void setDataSize(int dataSize); + /// Sets data size. + + int getDataSize() const; + /// Returns data size. + + int maxPacketSize() const; + /// Returns the total length of packet (header + data); + + struct timeval time(Poco::UInt8* buffer = 0, int length = 0) const; + /// Returns current epoch time if either buffer or length are equal to zero. + /// Otherwise, it extracts the time value from the supplied buffer and + /// returns the extracted value. + /// + /// Supplied buffer includes IP header, ICMP header and data. + + bool validReplyID(Poco::UInt8* buffer, int length) const; + /// Returns true if the extracted id is recognized + /// (equals the process id). + /// + /// Supplied buffer includes IP header, ICMP header and data. + + std::string errorDescription(Poco::UInt8* buffer, int length); + /// Returns error description string. + /// If supplied buffer contains an ICMP echo reply packet, an + /// empty string is returned indicating the absence of error. + /// + /// Supplied buffer includes IP header, ICMP header and data. + + std::string typeDescription(int typeId); + /// Returns the description of the packet type. + +private: + ICMPPacketImpl* _pImpl; +}; + + +} } // namespace Poco::Net + + +#endif // Net_ICMPPacket_INCLUDED diff --git a/Net/include/Poco/Net/ICMPPacketImpl.h b/Net/include/Poco/Net/ICMPPacketImpl.h index 11c65d50e..615e50b2a 100644 --- a/Net/include/Poco/Net/ICMPPacketImpl.h +++ b/Net/include/Poco/Net/ICMPPacketImpl.h @@ -1,163 +1,163 @@ -// -// ICMPPacketImpl.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ICMPPacketImpl.h#1 $ -// -// Library: Net -// Package: ICMP -// Module: ICMPPacketImpl -// -// Definition of the ICMPPacketImpl 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 Net_ICMPPacketImpl_INCLUDED -#define Net_ICMPPacketImpl_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Net/Socket.h" - - -namespace Poco { -namespace Net { - - -class Net_API ICMPPacketImpl - /// This is the abstract class for ICMP packet implementations. -{ -public: - ICMPPacketImpl(int dataSize = 48); - /// Constructor. Creates an ICMPPacketImpl. - - virtual ~ICMPPacketImpl(); - /// Destructor. - - const Poco::UInt8* packet(bool init = true); - /// Returns raw ICMP packet. - /// ICMP header and data are included in the packet. - /// If init is true, initPacket() is called. - - virtual int packetSize() const = 0; - /// Returns the total size of packet (ICMP header + data) in number of octets. - /// Must be overriden. - - virtual int maxPacketSize() const; - /// Returns the maximum permitted size of packet in number of octets. - - Poco::UInt16 sequence() const; - /// Returns the most recent sequence number generated. - - void setDataSize(int dataSize); - /// Sets data size. - - int getDataSize() const; - /// Returns data size. - - virtual struct timeval time(Poco::UInt8* buffer = 0, int length = 0) const = 0; - /// Returns current epoch time if either argument is equal to zero. - /// Otherwise, it extracts the time value from the supplied buffer. - /// - /// Supplied buffer includes IP header, ICMP header and data. - /// Must be overriden. - - virtual bool validReplyID(unsigned char* buffer, int length) const = 0; - /// Returns true if the extracted id is recognized - /// (i.e. equals the process id). - /// - /// Supplied buffer includes IP header, ICMP header and data. - /// Must be overriden. - - virtual std::string errorDescription(Poco::UInt8* buffer, int length) = 0; - /// Returns error description string. - /// If supplied buffer contains an ICMP echo reply packet, an - /// empty string is returned indicating the absence of error. - /// - /// Supplied buffer includes IP header, ICMP header and data. - /// Must be overriden. - - virtual std::string typeDescription(int typeId) = 0; - /// Returns the description of the packet type. - /// Must be overriden. - - static const Poco::UInt16 MAX_PACKET_SIZE; - static const Poco::UInt16 MAX_SEQ_VALUE; - -protected: - Poco::UInt16 nextSequence(); - /// Increments sequence number and returns the new value. - - void resetSequence(); - /// Resets the sequence to zero. - - virtual void initPacket() = 0; - /// (Re)assembles the packet. - /// Must be overriden. - - Poco::UInt16 checksum(Poco::UInt16 *addr, Poco::Int32 len); - /// Calculates the checksum for supplied buffer. - -private: - Poco::UInt16 _seq; - Poco::UInt8* _pPacket; - int _dataSize; - -}; - - -// -// inlines -// -inline Poco::UInt16 ICMPPacketImpl::sequence() const -{ - return _seq; -} - - -inline Poco::UInt16 ICMPPacketImpl::nextSequence() -{ - return ++_seq; -} - - -inline void ICMPPacketImpl::resetSequence() -{ - _seq = 0; -} - - -inline int ICMPPacketImpl::maxPacketSize() const -{ - return MAX_PACKET_SIZE; -} - - -} } // namespace Poco::Net - - -#endif // Net_ICMPPacketImpl_INCLUDED +// +// ICMPPacketImpl.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ICMPPacketImpl.h#1 $ +// +// Library: Net +// Package: ICMP +// Module: ICMPPacketImpl +// +// Definition of the ICMPPacketImpl 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 Net_ICMPPacketImpl_INCLUDED +#define Net_ICMPPacketImpl_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Net/Socket.h" + + +namespace Poco { +namespace Net { + + +class Net_API ICMPPacketImpl + /// This is the abstract class for ICMP packet implementations. +{ +public: + ICMPPacketImpl(int dataSize = 48); + /// Constructor. Creates an ICMPPacketImpl. + + virtual ~ICMPPacketImpl(); + /// Destructor. + + const Poco::UInt8* packet(bool init = true); + /// Returns raw ICMP packet. + /// ICMP header and data are included in the packet. + /// If init is true, initPacket() is called. + + virtual int packetSize() const = 0; + /// Returns the total size of packet (ICMP header + data) in number of octets. + /// Must be overriden. + + virtual int maxPacketSize() const; + /// Returns the maximum permitted size of packet in number of octets. + + Poco::UInt16 sequence() const; + /// Returns the most recent sequence number generated. + + void setDataSize(int dataSize); + /// Sets data size. + + int getDataSize() const; + /// Returns data size. + + virtual struct timeval time(Poco::UInt8* buffer = 0, int length = 0) const = 0; + /// Returns current epoch time if either argument is equal to zero. + /// Otherwise, it extracts the time value from the supplied buffer. + /// + /// Supplied buffer includes IP header, ICMP header and data. + /// Must be overriden. + + virtual bool validReplyID(unsigned char* buffer, int length) const = 0; + /// Returns true if the extracted id is recognized + /// (i.e. equals the process id). + /// + /// Supplied buffer includes IP header, ICMP header and data. + /// Must be overriden. + + virtual std::string errorDescription(Poco::UInt8* buffer, int length) = 0; + /// Returns error description string. + /// If supplied buffer contains an ICMP echo reply packet, an + /// empty string is returned indicating the absence of error. + /// + /// Supplied buffer includes IP header, ICMP header and data. + /// Must be overriden. + + virtual std::string typeDescription(int typeId) = 0; + /// Returns the description of the packet type. + /// Must be overriden. + + static const Poco::UInt16 MAX_PACKET_SIZE; + static const Poco::UInt16 MAX_SEQ_VALUE; + +protected: + Poco::UInt16 nextSequence(); + /// Increments sequence number and returns the new value. + + void resetSequence(); + /// Resets the sequence to zero. + + virtual void initPacket() = 0; + /// (Re)assembles the packet. + /// Must be overriden. + + Poco::UInt16 checksum(Poco::UInt16 *addr, Poco::Int32 len); + /// Calculates the checksum for supplied buffer. + +private: + Poco::UInt16 _seq; + Poco::UInt8* _pPacket; + int _dataSize; + +}; + + +// +// inlines +// +inline Poco::UInt16 ICMPPacketImpl::sequence() const +{ + return _seq; +} + + +inline Poco::UInt16 ICMPPacketImpl::nextSequence() +{ + return ++_seq; +} + + +inline void ICMPPacketImpl::resetSequence() +{ + _seq = 0; +} + + +inline int ICMPPacketImpl::maxPacketSize() const +{ + return MAX_PACKET_SIZE; +} + + +} } // namespace Poco::Net + + +#endif // Net_ICMPPacketImpl_INCLUDED diff --git a/Net/include/Poco/Net/ICMPSocket.h b/Net/include/Poco/Net/ICMPSocket.h index b1e25b93e..80eb6b002 100644 --- a/Net/include/Poco/Net/ICMPSocket.h +++ b/Net/include/Poco/Net/ICMPSocket.h @@ -1,139 +1,139 @@ -// -// ICMPSocket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ICMPSocket.h#1 $ -// -// Library: Net -// Package: ICMP -// Module: ICMPSocket -// -// Definition of the ICMPSocket 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 Net_ICMPSocket_INCLUDED -#define Net_ICMPSocket_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/Socket.h" - - -namespace Poco { -namespace Net { - - -class Net_API ICMPSocket: public Socket - /// This class provides an interface to an - /// ICMP client socket. -{ -public: - ICMPSocket(IPAddress::Family family, int dataSize = 48, int ttl = 128, int timeout = 500000); - /// Creates an unconnected ICMP socket. - /// - /// The socket will be created for the - /// given address family. - - ICMPSocket(const Socket& socket); - /// Creates the ICMPSocket with the SocketImpl - /// from another socket. The SocketImpl must be - /// a DatagramSocketImpl, otherwise an InvalidArgumentException - /// will be thrown. - - ~ICMPSocket(); - /// Destroys the ICMPSocket. - - ICMPSocket& operator = (const Socket& socket); - /// Assignment operator. - /// - /// Releases the socket's SocketImpl and - /// attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - int sendTo(const SocketAddress& address, int flags = 0); - /// Sends an ICMP request through - /// the socket to the given address. - /// - /// Returns the number of bytes sent. - - int receiveFrom(SocketAddress& address, int flags = 0); - /// Receives data from the socket. - /// Stores the address of the sender in address. - /// - /// Returns the time elapsed since the originating - /// request was sent. - - int dataSize() const; - /// Returns the data size in bytes. - - int ttl() const; - /// Returns the Time-To-Live value. - - int timeout() const; - /// Returns the socket timeout value. - -protected: - ICMPSocket(SocketImpl* pImpl); - /// Creates the Socket and attaches the given SocketImpl. - /// The socket takes owership of the SocketImpl. - /// - /// The SocketImpl must be a ICMPSocketImpl, otherwise - /// an InvalidArgumentException will be thrown. - -private: - int _dataSize; - int _ttl; - int _timeout; -}; - - -// -// inlines -// -inline int ICMPSocket::dataSize() const -{ - return _dataSize; -} - - -inline int ICMPSocket::ttl() const -{ - return _ttl; -} - - -inline int ICMPSocket::timeout() const -{ - return _timeout; -} - - -} } // namespace Poco::Net - - -#endif // Net_ICMPSocket_INCLUDED +// +// ICMPSocket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ICMPSocket.h#1 $ +// +// Library: Net +// Package: ICMP +// Module: ICMPSocket +// +// Definition of the ICMPSocket 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 Net_ICMPSocket_INCLUDED +#define Net_ICMPSocket_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/Socket.h" + + +namespace Poco { +namespace Net { + + +class Net_API ICMPSocket: public Socket + /// This class provides an interface to an + /// ICMP client socket. +{ +public: + ICMPSocket(IPAddress::Family family, int dataSize = 48, int ttl = 128, int timeout = 500000); + /// Creates an unconnected ICMP socket. + /// + /// The socket will be created for the + /// given address family. + + ICMPSocket(const Socket& socket); + /// Creates the ICMPSocket with the SocketImpl + /// from another socket. The SocketImpl must be + /// a DatagramSocketImpl, otherwise an InvalidArgumentException + /// will be thrown. + + ~ICMPSocket(); + /// Destroys the ICMPSocket. + + ICMPSocket& operator = (const Socket& socket); + /// Assignment operator. + /// + /// Releases the socket's SocketImpl and + /// attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + int sendTo(const SocketAddress& address, int flags = 0); + /// Sends an ICMP request through + /// the socket to the given address. + /// + /// Returns the number of bytes sent. + + int receiveFrom(SocketAddress& address, int flags = 0); + /// Receives data from the socket. + /// Stores the address of the sender in address. + /// + /// Returns the time elapsed since the originating + /// request was sent. + + int dataSize() const; + /// Returns the data size in bytes. + + int ttl() const; + /// Returns the Time-To-Live value. + + int timeout() const; + /// Returns the socket timeout value. + +protected: + ICMPSocket(SocketImpl* pImpl); + /// Creates the Socket and attaches the given SocketImpl. + /// The socket takes owership of the SocketImpl. + /// + /// The SocketImpl must be a ICMPSocketImpl, otherwise + /// an InvalidArgumentException will be thrown. + +private: + int _dataSize; + int _ttl; + int _timeout; +}; + + +// +// inlines +// +inline int ICMPSocket::dataSize() const +{ + return _dataSize; +} + + +inline int ICMPSocket::ttl() const +{ + return _ttl; +} + + +inline int ICMPSocket::timeout() const +{ + return _timeout; +} + + +} } // namespace Poco::Net + + +#endif // Net_ICMPSocket_INCLUDED diff --git a/Net/include/Poco/Net/ICMPSocketImpl.h b/Net/include/Poco/Net/ICMPSocketImpl.h index 2d8c2da39..4aabe9168 100644 --- a/Net/include/Poco/Net/ICMPSocketImpl.h +++ b/Net/include/Poco/Net/ICMPSocketImpl.h @@ -1,84 +1,84 @@ -// -// ICMPSocketImpl.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ICMPSocketImpl.h#1 $ -// -// Library: Net -// Package: ICMP -// Module: ICMPSocketImpl -// -// Definition of the ICMPSocketImpl 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 Net_ICMPSocketImpl_INCLUDED -#define Net_ICMPSocketImpl_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/RawSocketImpl.h" -#include "Poco/Net/ICMPPacket.h" -#include "Poco/Timestamp.h" - - -namespace Poco { -namespace Net { - - -class Net_API ICMPSocketImpl: public RawSocketImpl - /// This class implements an ICMP socket. -{ -public: - ICMPSocketImpl(IPAddress::Family family, int dataSize, int ttl, int timeout); - /// Creates an unconnected ICMP socket. - /// - /// The socket will be created for the given address family. - - int sendTo(const void*, int, const SocketAddress& address, int flags = 0); - /// Sends an ICMP request through the socket to the given address. - /// - /// Returns the number of bytes sent. - - int receiveFrom(void*, int, SocketAddress& address, int flags = 0); - /// Receives data from the socket. - /// Stores the address of the sender in address. - /// - /// Returns the time elapsed since the originating request was sent. - -protected: - ~ICMPSocketImpl(); - -private: - ICMPPacket _icmpPacket; -}; - - -} } // namespace Poco::Net - - -#endif // Net_ICMPSocketImpl_INCLUDED +// +// ICMPSocketImpl.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ICMPSocketImpl.h#1 $ +// +// Library: Net +// Package: ICMP +// Module: ICMPSocketImpl +// +// Definition of the ICMPSocketImpl 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 Net_ICMPSocketImpl_INCLUDED +#define Net_ICMPSocketImpl_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/RawSocketImpl.h" +#include "Poco/Net/ICMPPacket.h" +#include "Poco/Timestamp.h" + + +namespace Poco { +namespace Net { + + +class Net_API ICMPSocketImpl: public RawSocketImpl + /// This class implements an ICMP socket. +{ +public: + ICMPSocketImpl(IPAddress::Family family, int dataSize, int ttl, int timeout); + /// Creates an unconnected ICMP socket. + /// + /// The socket will be created for the given address family. + + int sendTo(const void*, int, const SocketAddress& address, int flags = 0); + /// Sends an ICMP request through the socket to the given address. + /// + /// Returns the number of bytes sent. + + int receiveFrom(void*, int, SocketAddress& address, int flags = 0); + /// Receives data from the socket. + /// Stores the address of the sender in address. + /// + /// Returns the time elapsed since the originating request was sent. + +protected: + ~ICMPSocketImpl(); + +private: + ICMPPacket _icmpPacket; +}; + + +} } // namespace Poco::Net + + +#endif // Net_ICMPSocketImpl_INCLUDED diff --git a/Net/include/Poco/Net/ICMPv4PacketImpl.h b/Net/include/Poco/Net/ICMPv4PacketImpl.h index 99ebb0dd3..f3ac25ab8 100644 --- a/Net/include/Poco/Net/ICMPv4PacketImpl.h +++ b/Net/include/Poco/Net/ICMPv4PacketImpl.h @@ -1,186 +1,186 @@ -// -// ICMPv4PacketImpl.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ICMPv4PacketImpl.h#1 $ -// -// Library: Net -// Package: ICMP -// Module: ICMPv4PacketImpl -// -// Definition of the ICMPv4PacketImpl 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 Net_ICMPv4PacketImpl_INCLUDED -#define Net_ICMPv4PacketImpl_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Net/Socket.h" -#include "Poco/Net/ICMPPacketImpl.h" - - -namespace Poco { -namespace Net { - - -class Net_API ICMPv4PacketImpl : public ICMPPacketImpl - /// This class implements the ICMPv4 packet. - /// Parts are based on original ICMP code by - /// Mike Muuss - /// U. S. Army Ballistic Research Laboratory - /// December, 1983 -{ -public: - // ICMPv4 header - struct Header - { - Poco::UInt8 type; // ICMP packet type - Poco::UInt8 code; // Type sub code - Poco::UInt16 checksum; - Poco::UInt16 id; - Poco::UInt16 seq; - }; - - enum MessageType - { - ECHO_REPLY, - ICMP_1, - ICMP_2, - DESTINATION_UNREACHABLE, - SOURCE_QUENCH, - REDIRECT, - ICMP_6, - ICMP_7, - ECHO, - ICMP_9, - ICMP_10, - TIME_EXCEEDED, - PARAMETER_PROBLEM, - TIMESTAMP, - TIMESTAMP_REPLY, - INFORMATION_REQUEST, - INFORMATION_REPLY, - MESSAGE_TYPE_UNKNOWN, // non-standard default, must remain last but one - MESSAGE_TYPE_LENGTH // length indicator, must remain last - }; - - enum DestinationUnreachableCode - { - NET_UNREACHABLE, - HOST_UNREACHABLE, - PROTOCOL_UNREACHABLE, - PORT_UNREACHABLE, - FRAGMENTATION_NEEDED_AND_DF_SET, - SOURCE_ROUTE_FAILED, - DESTINATION_UNREACHABLE_UNKNOWN, // non-standard default, must remain last but one - DESTINATION_UNREACHABLE_LENGTH // length indicator, must remain last - }; - - enum RedirectMessageCode - { - REDIRECT_NETWORK, - REDIRECT_HOST, - REDIRECT_SERVICE_NETWORK, - REDIRECT_SERVICE_HOST, - REDIRECT_MESSAGE_UNKNOWN, // non-standard default, must remain last but one - REDIRECT_MESSAGE_LENGTH // length indicator, must remain last - }; - - enum TimeExceededCode - { - TIME_TO_LIVE, - FRAGMENT_REASSEMBLY, - TIME_EXCEEDED_UNKNOWN, // non-standard default, must remain last but one - TIME_EXCEEDED_LENGTH // length indicator, must remain last - }; - - enum ParameterProblemCode - { - POINTER_INDICATES_THE_ERROR, - PARAMETER_PROBLEM_UNKNOWN, // non-standard default, must remain last but one - PARAMETER_PROBLEM_LENGTH // length indicator, must remain last - }; - - ICMPv4PacketImpl(int dataSize = 48); - /// Constructor. Creates an ICMPv4PacketImpl. - - ~ICMPv4PacketImpl(); - /// Destructor. - - int packetSize() const; - /// Returns the total length of packet (header + data); - - struct timeval time(Poco::UInt8* buffer = 0, int length = 0) const; - /// Returns current epoch time if either buffer or length are equal to zero. - /// Otherwise, it extracts the time value from the supplied buffer. - /// - /// Buffer includes IP header, ICMP header and data. - - bool validReplyID(Poco::UInt8* buffer, int length) const; - /// Returns true if the extracted id is recognized - /// (i.e. equals the process id). - /// - /// Buffer includes IP header, ICMP header and data. - - virtual std::string errorDescription(Poco::UInt8* buffer, int length); - /// Returns error description string. - /// If supplied buffer contains ICMPv4 echo reply packet, an - /// empty string is returned indicating the absence of error. - /// - /// Buffer includes IP header, ICMP header and data. - - virtual std::string typeDescription(int typeId); - /// Returns the description of the packet type. - - static const Poco::UInt16 MAX_PACKET_SIZE; - static const std::string MESSAGE_TYPE[MESSAGE_TYPE_LENGTH]; - static const Poco::UInt8 DESTINATION_UNREACHABLE_TYPE; // 3 - static const Poco::UInt8 SOURCE_QUENCH_TYPE; // 4 - static const Poco::UInt8 REDIRECT_MESSAGE_TYPE; // 5 - static const Poco::UInt8 TIME_EXCEEDED_TYPE; // 11 - static const Poco::UInt8 PARAMETER_PROBLEM_TYPE; // 12 - -private: - void initPacket(); - Header* header(Poco::UInt8* buffer, int length) const; - Poco::UInt8* data(Poco::UInt8* buffer, int length) const; - - static const std::string DESTINATION_UNREACHABLE_CODE[DESTINATION_UNREACHABLE_LENGTH]; - static const std::string REDIRECT_MESSAGE_CODE[REDIRECT_MESSAGE_LENGTH]; - static const std::string TIME_EXCEEDED_CODE[TIME_EXCEEDED_LENGTH]; - static const std::string PARAMETER_PROBLEM_CODE[PARAMETER_PROBLEM_LENGTH]; - - Poco::UInt16 _seq; -}; - - -} } // namespace Poco::Net - - -#endif // Net_ICMPv4PacketImpl_INCLUDED +// +// ICMPv4PacketImpl.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ICMPv4PacketImpl.h#1 $ +// +// Library: Net +// Package: ICMP +// Module: ICMPv4PacketImpl +// +// Definition of the ICMPv4PacketImpl 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 Net_ICMPv4PacketImpl_INCLUDED +#define Net_ICMPv4PacketImpl_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Net/Socket.h" +#include "Poco/Net/ICMPPacketImpl.h" + + +namespace Poco { +namespace Net { + + +class Net_API ICMPv4PacketImpl : public ICMPPacketImpl + /// This class implements the ICMPv4 packet. + /// Parts are based on original ICMP code by + /// Mike Muuss + /// U. S. Army Ballistic Research Laboratory + /// December, 1983 +{ +public: + // ICMPv4 header + struct Header + { + Poco::UInt8 type; // ICMP packet type + Poco::UInt8 code; // Type sub code + Poco::UInt16 checksum; + Poco::UInt16 id; + Poco::UInt16 seq; + }; + + enum MessageType + { + ECHO_REPLY, + ICMP_1, + ICMP_2, + DESTINATION_UNREACHABLE, + SOURCE_QUENCH, + REDIRECT, + ICMP_6, + ICMP_7, + ECHO, + ICMP_9, + ICMP_10, + TIME_EXCEEDED, + PARAMETER_PROBLEM, + TIMESTAMP, + TIMESTAMP_REPLY, + INFORMATION_REQUEST, + INFORMATION_REPLY, + MESSAGE_TYPE_UNKNOWN, // non-standard default, must remain last but one + MESSAGE_TYPE_LENGTH // length indicator, must remain last + }; + + enum DestinationUnreachableCode + { + NET_UNREACHABLE, + HOST_UNREACHABLE, + PROTOCOL_UNREACHABLE, + PORT_UNREACHABLE, + FRAGMENTATION_NEEDED_AND_DF_SET, + SOURCE_ROUTE_FAILED, + DESTINATION_UNREACHABLE_UNKNOWN, // non-standard default, must remain last but one + DESTINATION_UNREACHABLE_LENGTH // length indicator, must remain last + }; + + enum RedirectMessageCode + { + REDIRECT_NETWORK, + REDIRECT_HOST, + REDIRECT_SERVICE_NETWORK, + REDIRECT_SERVICE_HOST, + REDIRECT_MESSAGE_UNKNOWN, // non-standard default, must remain last but one + REDIRECT_MESSAGE_LENGTH // length indicator, must remain last + }; + + enum TimeExceededCode + { + TIME_TO_LIVE, + FRAGMENT_REASSEMBLY, + TIME_EXCEEDED_UNKNOWN, // non-standard default, must remain last but one + TIME_EXCEEDED_LENGTH // length indicator, must remain last + }; + + enum ParameterProblemCode + { + POINTER_INDICATES_THE_ERROR, + PARAMETER_PROBLEM_UNKNOWN, // non-standard default, must remain last but one + PARAMETER_PROBLEM_LENGTH // length indicator, must remain last + }; + + ICMPv4PacketImpl(int dataSize = 48); + /// Constructor. Creates an ICMPv4PacketImpl. + + ~ICMPv4PacketImpl(); + /// Destructor. + + int packetSize() const; + /// Returns the total length of packet (header + data); + + struct timeval time(Poco::UInt8* buffer = 0, int length = 0) const; + /// Returns current epoch time if either buffer or length are equal to zero. + /// Otherwise, it extracts the time value from the supplied buffer. + /// + /// Buffer includes IP header, ICMP header and data. + + bool validReplyID(Poco::UInt8* buffer, int length) const; + /// Returns true if the extracted id is recognized + /// (i.e. equals the process id). + /// + /// Buffer includes IP header, ICMP header and data. + + virtual std::string errorDescription(Poco::UInt8* buffer, int length); + /// Returns error description string. + /// If supplied buffer contains ICMPv4 echo reply packet, an + /// empty string is returned indicating the absence of error. + /// + /// Buffer includes IP header, ICMP header and data. + + virtual std::string typeDescription(int typeId); + /// Returns the description of the packet type. + + static const Poco::UInt16 MAX_PACKET_SIZE; + static const std::string MESSAGE_TYPE[MESSAGE_TYPE_LENGTH]; + static const Poco::UInt8 DESTINATION_UNREACHABLE_TYPE; // 3 + static const Poco::UInt8 SOURCE_QUENCH_TYPE; // 4 + static const Poco::UInt8 REDIRECT_MESSAGE_TYPE; // 5 + static const Poco::UInt8 TIME_EXCEEDED_TYPE; // 11 + static const Poco::UInt8 PARAMETER_PROBLEM_TYPE; // 12 + +private: + void initPacket(); + Header* header(Poco::UInt8* buffer, int length) const; + Poco::UInt8* data(Poco::UInt8* buffer, int length) const; + + static const std::string DESTINATION_UNREACHABLE_CODE[DESTINATION_UNREACHABLE_LENGTH]; + static const std::string REDIRECT_MESSAGE_CODE[REDIRECT_MESSAGE_LENGTH]; + static const std::string TIME_EXCEEDED_CODE[TIME_EXCEEDED_LENGTH]; + static const std::string PARAMETER_PROBLEM_CODE[PARAMETER_PROBLEM_LENGTH]; + + Poco::UInt16 _seq; +}; + + +} } // namespace Poco::Net + + +#endif // Net_ICMPv4PacketImpl_INCLUDED diff --git a/Net/include/Poco/Net/IPAddress.h b/Net/include/Poco/Net/IPAddress.h index 87b22cc33..fa7a4d27f 100644 --- a/Net/include/Poco/Net/IPAddress.h +++ b/Net/include/Poco/Net/IPAddress.h @@ -1,344 +1,344 @@ -// -// IPAddress.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/IPAddress.h#1 $ -// -// Library: Net -// Package: NetCore -// Module: IPAddress -// -// Definition of the IPAddress 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_IPAddress_INCLUDED -#define Net_IPAddress_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketDefs.h" - - -namespace Poco { -namespace Net { - - -class IPAddressImpl; - - -class Net_API IPAddress - /// This class represents an internet (IP) host - /// address. The address can belong either to the - /// IPv4 or the IPv6 address family. - /// - /// Relational operators (==, !=, <, <=, >, >=) are - /// supported. However, you must not interpret any - /// special meaning into the result of these - /// operations, other than that the results are - /// consistent. - /// - /// Especially, an IPv4 address is never equal to - /// an IPv6 address, even if the IPv6 address is - /// IPv4 compatible and the addresses are the same. - /// - /// IPv6 addresses are supported only if the target platform - /// supports IPv6. -{ -public: - enum Family - /// Possible address families for IP addresses. - { - IPv4, - IPv6 - }; - - IPAddress(); - /// Creates a wildcard (zero) IPv4 IPAddress. - - IPAddress(const IPAddress& addr); - /// Creates an IPAddress by copying another one. - - explicit IPAddress(Family family); - /// Creates a wildcard (zero) IPAddress for the - /// given address family. - - explicit IPAddress(const std::string& addr); - /// Creates an IPAddress from the string containing - /// an IP address in presentation format (dotted decimal - /// for IPv4, hex string for IPv6). - /// - /// Depending on the format of addr, either an IPv4 or - /// an IPv6 address is created. - /// - /// See toString() for details on the supported formats. - /// - /// Throws an InvalidAddressException if the address cannot be parsed. - - IPAddress(const std::string& addr, Family family); - /// Creates an IPAddress from the string containing - /// an IP address in presentation format (dotted decimal - /// for IPv4, hex string for IPv6). - - IPAddress(const void* addr, poco_socklen_t length); - /// Creates an IPAddress from a native internet address. - /// A pointer to a in_addr or a in6_addr structure may be - /// passed. - - ~IPAddress(); - /// Destroys the IPAddress. - - IPAddress& operator = (const IPAddress& addr); - /// Assigns an IPAddress. - - void swap(IPAddress& address); - /// Swaps the IPAddress with another one. - - Family family() const; - /// Returns the address family (IPv4 or IPv6) of the address. - - std::string toString() const; - /// Returns a string containing a representation of the address - /// in presentation format. - /// - /// For IPv4 addresses the result will be in dotted-decimal - /// (d.d.d.d) notation. - /// - /// Textual representation of IPv6 address is one of the following forms: - /// - /// The preferred form is x:x:x:x:x:x:x:x, where the 'x's are the hexadecimal - /// values of the eight 16-bit pieces of the address. This is the full form. - /// Example: 1080:0:0:0:8:600:200A:425C - /// - /// It is not necessary to write the leading zeros in an individual field. - /// However, there must be at least one numeral in every field, except as described below. - /// - /// It is common for IPv6 addresses to contain long strings of zero bits. - /// In order to make writing addresses containing zero bits easier, a special syntax is - /// available to compress the zeros. The use of "::" indicates multiple groups of 16-bits of zeros. - /// The "::" can only appear once in an address. The "::" can also be used to compress the leading - /// and/or trailing zeros in an address. Example: 1080::8:600:200A:425C - /// - /// For dealing with IPv4 compatible addresses in a mixed environment, - /// a special syntax is available: x:x:x:x:x:x:d.d.d.d, where the 'x's are the - /// hexadecimal values of the six high-order 16-bit pieces of the address, - /// and the 'd's are the decimal values of the four low-order 8-bit pieces of the - /// standard IPv4 representation address. Example: ::FFFF:192.168.1.120 - - bool isWildcard() const; - /// Returns true iff the address is a wildcard (all zero) - /// address. - - bool isBroadcast() const; - /// Returns true iff the address is a broadcast address. - /// - /// Only IPv4 addresses can be broadcast addresses. In a broadcast - /// address, all bits are one. - /// - /// For a IPv6 address, returns always false. - - bool isLoopback() const; - /// Returns true iff the address is a loopback address. - /// - /// For IPv4, the loopback address is 127.0.0.1. - /// - /// For IPv6, the loopback address is ::1. - - bool isMulticast() const; - /// Returns true iff the address is a multicast address. - /// - /// IPv4 multicast addresses are in the - /// 224.0.0.0 to 239.255.255.255 range - /// (the first four bits have the value 1110). - /// - /// IPv6 multicast addresses are in the - /// FFxx:x:x:x:x:x:x:x range. - - bool isUnicast() const; - /// Returns true iff the address is a unicast address. - /// - /// An address is unicast if it is neither a wildcard, - /// broadcast or multicast address. - - bool isLinkLocal() const; - /// Returns true iff the address is a link local unicast address. - /// - /// IPv4 link local addresses are in the 169.254.0.0/16 range, - /// according to RFC 3927. - /// - /// IPv6 link local addresses have 1111 1110 10 as the first - /// 10 bits, followed by 54 zeros. - - bool isSiteLocal() const; - /// Returns true iff the address is a site local unicast address. - /// - /// IPv4 site local addresses are in on of the 10.0.0.0/24, - /// 192.168.0.0/16 or 172.16.0.0 to 172.31.255.255 ranges. - /// - /// IPv6 site local addresses have 1111 1110 11 as the first - /// 10 bits, followed by 38 zeros. - - bool isIPv4Compatible() const; - /// Returns true iff the address is IPv4 compatible. - /// - /// For IPv4 addresses, this is always true. - /// - /// For IPv6, the address must be in the ::x:x range (the - /// first 96 bits are zero). - - bool isIPv4Mapped() const; - /// Returns true iff the address is an IPv4 mapped IPv6 address. - /// - /// For IPv4 addresses, this is always true. - /// - /// For IPv6, the address must be in the ::FFFF:x:x range. - - bool isWellKnownMC() const; - /// Returns true iff the address is a well-known multicast address. - /// - /// For IPv4, well-known multicast addresses are in the - /// 224.0.0.0/8 range. - /// - /// For IPv6, well-known multicast addresses are in the - /// FF0x:x:x:x:x:x:x:x range. - - bool isNodeLocalMC() const; - /// Returns true iff the address is a node-local multicast address. - /// - /// IPv4 does not support node-local addresses, thus the result is - /// always false for an IPv4 address. - /// - /// For IPv6, node-local multicast addresses are in the - /// FFx1:x:x:x:x:x:x:x range. - - bool isLinkLocalMC() const; - /// Returns true iff the address is a link-local multicast address. - /// - /// For IPv4, link-local multicast addresses are in the - /// 224.0.0.0/24 range. Note that this overlaps with the range for well-known - /// multicast addresses. - /// - /// For IPv6, link-local multicast addresses are in the - /// FFx2:x:x:x:x:x:x:x range. - - bool isSiteLocalMC() const; - /// Returns true iff the address is a site-local multicast address. - /// - /// For IPv4, site local multicast addresses are in the - /// 239.255.0.0/16 range. - /// - /// For IPv6, site-local multicast addresses are in the - /// FFx5:x:x:x:x:x:x:x range. - - bool isOrgLocalMC() const; - /// Returns true iff the address is a organization-local multicast address. - /// - /// For IPv4, organization-local multicast addresses are in the - /// 239.192.0.0/16 range. - /// - /// For IPv6, organization-local multicast addresses are in the - /// FFx8:x:x:x:x:x:x:x range. - - bool isGlobalMC() const; - /// Returns true iff the address is a global multicast address. - /// - /// For IPv4, global multicast addresses are in the - /// 224.0.1.0 to 238.255.255.255 range. - /// - /// For IPv6, global multicast addresses are in the - /// FFxF:x:x:x:x:x:x:x range. - - bool operator == (const IPAddress& addr) const; - bool operator != (const IPAddress& addr) const; - bool operator < (const IPAddress& addr) const; - bool operator <= (const IPAddress& addr) const; - bool operator > (const IPAddress& addr) const; - bool operator >= (const IPAddress& addr) const; - - poco_socklen_t length() const; - /// Returns the length in bytes of the internal socket address structure. - - const void* addr() const; - /// Returns the internal address structure. - - int af() const; - /// Returns the address family (AF_INET or AF_INET6) of the address. - - static IPAddress parse(const std::string& addr); - /// Creates an IPAddress from the string containing - /// an IP address in presentation format (dotted decimal - /// for IPv4, hex string for IPv6). - /// - /// Depending on the format of addr, either an IPv4 or - /// an IPv6 address is created. - /// - /// See toString() for details on the supported formats. - /// - /// Throws an InvalidAddressException if the address cannot be parsed. - - static bool tryParse(const std::string& addr, IPAddress& result); - /// Tries to interpret the given address string as an - /// IP address in presentation format (dotted decimal - /// for IPv4, hex string for IPv6). - /// - /// Returns true and stores the IPAddress in result if the - /// string contains a valid address. - /// - /// Returns false and leaves result unchanged otherwise. - - enum - { - MAX_ADDRESS_LENGTH = -#if defined(POCO_HAVE_IPv6) - sizeof(struct in6_addr) -#else - sizeof(struct in_addr) -#endif - /// Maximum length in bytes of a socket address. - }; - -protected: - void init(IPAddressImpl* pImpl); - -private: - IPAddressImpl* _pImpl; -}; - - -// -// inlines -// -inline void swap(IPAddress& a1, IPAddress& a2) -{ - a1.swap(a2); -} - - -} } // namespace Poco::Net - - -#endif // Net_IPAddress_INCLUDED +// +// IPAddress.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/IPAddress.h#1 $ +// +// Library: Net +// Package: NetCore +// Module: IPAddress +// +// Definition of the IPAddress 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_IPAddress_INCLUDED +#define Net_IPAddress_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketDefs.h" + + +namespace Poco { +namespace Net { + + +class IPAddressImpl; + + +class Net_API IPAddress + /// This class represents an internet (IP) host + /// address. The address can belong either to the + /// IPv4 or the IPv6 address family. + /// + /// Relational operators (==, !=, <, <=, >, >=) are + /// supported. However, you must not interpret any + /// special meaning into the result of these + /// operations, other than that the results are + /// consistent. + /// + /// Especially, an IPv4 address is never equal to + /// an IPv6 address, even if the IPv6 address is + /// IPv4 compatible and the addresses are the same. + /// + /// IPv6 addresses are supported only if the target platform + /// supports IPv6. +{ +public: + enum Family + /// Possible address families for IP addresses. + { + IPv4, + IPv6 + }; + + IPAddress(); + /// Creates a wildcard (zero) IPv4 IPAddress. + + IPAddress(const IPAddress& addr); + /// Creates an IPAddress by copying another one. + + explicit IPAddress(Family family); + /// Creates a wildcard (zero) IPAddress for the + /// given address family. + + explicit IPAddress(const std::string& addr); + /// Creates an IPAddress from the string containing + /// an IP address in presentation format (dotted decimal + /// for IPv4, hex string for IPv6). + /// + /// Depending on the format of addr, either an IPv4 or + /// an IPv6 address is created. + /// + /// See toString() for details on the supported formats. + /// + /// Throws an InvalidAddressException if the address cannot be parsed. + + IPAddress(const std::string& addr, Family family); + /// Creates an IPAddress from the string containing + /// an IP address in presentation format (dotted decimal + /// for IPv4, hex string for IPv6). + + IPAddress(const void* addr, poco_socklen_t length); + /// Creates an IPAddress from a native internet address. + /// A pointer to a in_addr or a in6_addr structure may be + /// passed. + + ~IPAddress(); + /// Destroys the IPAddress. + + IPAddress& operator = (const IPAddress& addr); + /// Assigns an IPAddress. + + void swap(IPAddress& address); + /// Swaps the IPAddress with another one. + + Family family() const; + /// Returns the address family (IPv4 or IPv6) of the address. + + std::string toString() const; + /// Returns a string containing a representation of the address + /// in presentation format. + /// + /// For IPv4 addresses the result will be in dotted-decimal + /// (d.d.d.d) notation. + /// + /// Textual representation of IPv6 address is one of the following forms: + /// + /// The preferred form is x:x:x:x:x:x:x:x, where the 'x's are the hexadecimal + /// values of the eight 16-bit pieces of the address. This is the full form. + /// Example: 1080:0:0:0:8:600:200A:425C + /// + /// It is not necessary to write the leading zeros in an individual field. + /// However, there must be at least one numeral in every field, except as described below. + /// + /// It is common for IPv6 addresses to contain long strings of zero bits. + /// In order to make writing addresses containing zero bits easier, a special syntax is + /// available to compress the zeros. The use of "::" indicates multiple groups of 16-bits of zeros. + /// The "::" can only appear once in an address. The "::" can also be used to compress the leading + /// and/or trailing zeros in an address. Example: 1080::8:600:200A:425C + /// + /// For dealing with IPv4 compatible addresses in a mixed environment, + /// a special syntax is available: x:x:x:x:x:x:d.d.d.d, where the 'x's are the + /// hexadecimal values of the six high-order 16-bit pieces of the address, + /// and the 'd's are the decimal values of the four low-order 8-bit pieces of the + /// standard IPv4 representation address. Example: ::FFFF:192.168.1.120 + + bool isWildcard() const; + /// Returns true iff the address is a wildcard (all zero) + /// address. + + bool isBroadcast() const; + /// Returns true iff the address is a broadcast address. + /// + /// Only IPv4 addresses can be broadcast addresses. In a broadcast + /// address, all bits are one. + /// + /// For a IPv6 address, returns always false. + + bool isLoopback() const; + /// Returns true iff the address is a loopback address. + /// + /// For IPv4, the loopback address is 127.0.0.1. + /// + /// For IPv6, the loopback address is ::1. + + bool isMulticast() const; + /// Returns true iff the address is a multicast address. + /// + /// IPv4 multicast addresses are in the + /// 224.0.0.0 to 239.255.255.255 range + /// (the first four bits have the value 1110). + /// + /// IPv6 multicast addresses are in the + /// FFxx:x:x:x:x:x:x:x range. + + bool isUnicast() const; + /// Returns true iff the address is a unicast address. + /// + /// An address is unicast if it is neither a wildcard, + /// broadcast or multicast address. + + bool isLinkLocal() const; + /// Returns true iff the address is a link local unicast address. + /// + /// IPv4 link local addresses are in the 169.254.0.0/16 range, + /// according to RFC 3927. + /// + /// IPv6 link local addresses have 1111 1110 10 as the first + /// 10 bits, followed by 54 zeros. + + bool isSiteLocal() const; + /// Returns true iff the address is a site local unicast address. + /// + /// IPv4 site local addresses are in on of the 10.0.0.0/24, + /// 192.168.0.0/16 or 172.16.0.0 to 172.31.255.255 ranges. + /// + /// IPv6 site local addresses have 1111 1110 11 as the first + /// 10 bits, followed by 38 zeros. + + bool isIPv4Compatible() const; + /// Returns true iff the address is IPv4 compatible. + /// + /// For IPv4 addresses, this is always true. + /// + /// For IPv6, the address must be in the ::x:x range (the + /// first 96 bits are zero). + + bool isIPv4Mapped() const; + /// Returns true iff the address is an IPv4 mapped IPv6 address. + /// + /// For IPv4 addresses, this is always true. + /// + /// For IPv6, the address must be in the ::FFFF:x:x range. + + bool isWellKnownMC() const; + /// Returns true iff the address is a well-known multicast address. + /// + /// For IPv4, well-known multicast addresses are in the + /// 224.0.0.0/8 range. + /// + /// For IPv6, well-known multicast addresses are in the + /// FF0x:x:x:x:x:x:x:x range. + + bool isNodeLocalMC() const; + /// Returns true iff the address is a node-local multicast address. + /// + /// IPv4 does not support node-local addresses, thus the result is + /// always false for an IPv4 address. + /// + /// For IPv6, node-local multicast addresses are in the + /// FFx1:x:x:x:x:x:x:x range. + + bool isLinkLocalMC() const; + /// Returns true iff the address is a link-local multicast address. + /// + /// For IPv4, link-local multicast addresses are in the + /// 224.0.0.0/24 range. Note that this overlaps with the range for well-known + /// multicast addresses. + /// + /// For IPv6, link-local multicast addresses are in the + /// FFx2:x:x:x:x:x:x:x range. + + bool isSiteLocalMC() const; + /// Returns true iff the address is a site-local multicast address. + /// + /// For IPv4, site local multicast addresses are in the + /// 239.255.0.0/16 range. + /// + /// For IPv6, site-local multicast addresses are in the + /// FFx5:x:x:x:x:x:x:x range. + + bool isOrgLocalMC() const; + /// Returns true iff the address is a organization-local multicast address. + /// + /// For IPv4, organization-local multicast addresses are in the + /// 239.192.0.0/16 range. + /// + /// For IPv6, organization-local multicast addresses are in the + /// FFx8:x:x:x:x:x:x:x range. + + bool isGlobalMC() const; + /// Returns true iff the address is a global multicast address. + /// + /// For IPv4, global multicast addresses are in the + /// 224.0.1.0 to 238.255.255.255 range. + /// + /// For IPv6, global multicast addresses are in the + /// FFxF:x:x:x:x:x:x:x range. + + bool operator == (const IPAddress& addr) const; + bool operator != (const IPAddress& addr) const; + bool operator < (const IPAddress& addr) const; + bool operator <= (const IPAddress& addr) const; + bool operator > (const IPAddress& addr) const; + bool operator >= (const IPAddress& addr) const; + + poco_socklen_t length() const; + /// Returns the length in bytes of the internal socket address structure. + + const void* addr() const; + /// Returns the internal address structure. + + int af() const; + /// Returns the address family (AF_INET or AF_INET6) of the address. + + static IPAddress parse(const std::string& addr); + /// Creates an IPAddress from the string containing + /// an IP address in presentation format (dotted decimal + /// for IPv4, hex string for IPv6). + /// + /// Depending on the format of addr, either an IPv4 or + /// an IPv6 address is created. + /// + /// See toString() for details on the supported formats. + /// + /// Throws an InvalidAddressException if the address cannot be parsed. + + static bool tryParse(const std::string& addr, IPAddress& result); + /// Tries to interpret the given address string as an + /// IP address in presentation format (dotted decimal + /// for IPv4, hex string for IPv6). + /// + /// Returns true and stores the IPAddress in result if the + /// string contains a valid address. + /// + /// Returns false and leaves result unchanged otherwise. + + enum + { + MAX_ADDRESS_LENGTH = +#if defined(POCO_HAVE_IPv6) + sizeof(struct in6_addr) +#else + sizeof(struct in_addr) +#endif + /// Maximum length in bytes of a socket address. + }; + +protected: + void init(IPAddressImpl* pImpl); + +private: + IPAddressImpl* _pImpl; +}; + + +// +// inlines +// +inline void swap(IPAddress& a1, IPAddress& a2) +{ + a1.swap(a2); +} + + +} } // namespace Poco::Net + + +#endif // Net_IPAddress_INCLUDED diff --git a/Net/include/Poco/Net/MailMessage.h b/Net/include/Poco/Net/MailMessage.h index 2de8f1dae..0169f85ed 100644 --- a/Net/include/Poco/Net/MailMessage.h +++ b/Net/include/Poco/Net/MailMessage.h @@ -1,254 +1,254 @@ -// -// MailMessage.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/MailMessage.h#2 $ -// -// Library: Net -// Package: Mail -// Module: MailMessage -// -// Definition of the MailMessage 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_MailMessage_INCLUDED -#define Net_MailMessage_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/MessageHeader.h" -#include "Poco/Net/MailRecipient.h" -#include "Poco/Timestamp.h" -#include - - -namespace Poco { -namespace Net { - - -class MediaType; -class PartSource; -class PartHandler; -class MultipartWriter; - - -class Net_API MailMessage: public MessageHeader - /// This class represents an e-mail message for - /// use with the SMTPClientSession and POPClientSession - /// classes. - /// - /// MailMessage supports both old-style plain text messages, - /// as well as MIME multipart mail messages with attachments. - /// - /// For multi-part messages, the following content transfer - /// encodings are supported: 7bit, 8bit, quoted-printable - /// and base64. -{ -public: - typedef std::vector Recipients; - - enum ContentDisposition - { - CONTENT_INLINE, - CONTENT_ATTACHMENT - }; - - enum ContentTransferEncoding - { - ENCODING_7BIT, - ENCODING_8BIT, - ENCODING_QUOTED_PRINTABLE, - ENCODING_BASE64 - }; - - MailMessage(); - /// Creates an empty MailMessage. - - virtual ~MailMessage(); - /// Destroys the MailMessage. - - void addRecipient(const MailRecipient& recipient); - /// Adds a recipient for the message. - - const Recipients& recipients() const; - /// Returns the recipients of the message. - - void setSubject(const std::string& subject); - /// Sets the subject of the message. - - const std::string& getSubject() const; - /// Returns the subject of the message. - - void setSender(const std::string& sender); - /// Sets the sender of the message (which - /// ends up in the From header field). - - const std::string& getSender() const; - /// Returns the sender of the message (taken - /// from the From header field). - - void setContent(const std::string& content, ContentTransferEncoding encoding = ENCODING_QUOTED_PRINTABLE); - /// Sets the content of the mail message. - /// - /// If the content transfer encoding is ENCODING_7BIT or - /// ENCODING_8BIT, the content string must be formatted - /// according to the rules of an internet email message. - /// - /// The message will be sent as a single-part - /// message. - - const std::string& getContent() const; - /// Returns the content of the mail message. - /// - /// A content will only be returned for single-part - /// messages. The content of multi-part mail messages - /// will be reported through the registered PartHandler. - - void setContentType(const std::string& mediaType); - /// Sets the content type for the message. - - void setContentType(const MediaType& mediaType); - /// Sets the content type for the message. - - const std::string& getContentType() const; - /// Returns the content type for the message. - - void setDate(const Poco::Timestamp& dateTime); - /// Sets the Date header to the given date/time value. - - Poco::Timestamp getDate() const; - /// Returns the value of the Date header. - - bool isMultipart() const; - /// Returns true iff the message is a multipart message. - - void addPart(const std::string& name, PartSource* pSource, ContentDisposition disposition, ContentTransferEncoding encoding); - /// Adds a part/attachment to the mail message. - /// - /// The MailMessage takes ownership of the PartSource and deletes it - /// when it is no longer needed. - /// - /// The MailMessage will be converted to a multipart message - /// if it is not already one. - - void addContent(PartSource* pSource, ContentTransferEncoding encoding = ENCODING_QUOTED_PRINTABLE); - /// Adds a part to the mail message by calling - /// addPart("", pSource, CONTENT_INLINE, encoding); - - void addAttachment(const std::string& name, PartSource* pSource, ContentTransferEncoding encoding = ENCODING_BASE64); - /// Adds an attachment to the mail message by calling - /// addPart(name, pSource, CONTENT_ATTACHMENT, encoding); - - void read(std::istream& istr, PartHandler& handler); - /// Reads the MailMessage from the given input stream. - /// - /// If the message has multiple parts, the parts - /// are reported to the PartHandler. If the message - /// is not a multi-part message, the content is stored - /// in a string available by calling getContent(). - - void read(std::istream& istr); - /// Reads the MailMessage from the given input stream. - /// - /// The raw message (including all MIME parts) is stored - /// in a string and available by calling getContent(). - - void write(std::ostream& ostr) const; - /// Writes the mail message to the given output stream. - -protected: - struct Part - { - std::string name; - PartSource* pSource; - ContentDisposition disposition; - ContentTransferEncoding encoding; - }; - typedef std::vector PartVec; - - void makeMultipart(); - void writeHeader(const MessageHeader& header, std::ostream& ostr) const; - void writeMultipart(MessageHeader& header, std::ostream& ostr) const; - void writePart(MultipartWriter& writer, const Part& part) const; - void writeEncoded(std::istream& istr, std::ostream& ostr, ContentTransferEncoding encoding) const; - void setRecipientHeaders(MessageHeader& headers) const; - void readHeader(std::istream& istr); - void readMultipart(std::istream& istr, PartHandler& handler); - void readPart(std::istream& istr, const MessageHeader& header, PartHandler& handler); - void handlePart(std::istream& istr, const MessageHeader& header, PartHandler& handler); - static const std::string& contentTransferEncodingToString(ContentTransferEncoding encoding); - static int lineLength(const std::string& str); - static void appendRecipient(const MailRecipient& recipient, std::string& str); - - static const std::string HEADER_SUBJECT; - static const std::string HEADER_FROM; - static const std::string HEADER_TO; - static const std::string HEADER_CC; - static const std::string HEADER_BCC; - static const std::string HEADER_DATE; - static const std::string HEADER_CONTENT_TYPE; - static const std::string HEADER_CONTENT_TRANSFER_ENCODING; - static const std::string HEADER_CONTENT_DISPOSITION; - static const std::string HEADER_MIME_VERSION; - static const std::string EMPTY_HEADER; - static const std::string TEXT_PLAIN; - static const std::string CTE_7BIT; - static const std::string CTE_8BIT; - static const std::string CTE_QUOTED_PRINTABLE; - static const std::string CTE_BASE64; - -private: - MailMessage(const MailMessage&); - MailMessage& operator = (const MailMessage&); - - Recipients _recipients; - PartVec _parts; - std::string _content; - ContentTransferEncoding _encoding; -}; - - -// -// inlines -// -inline const MailMessage::Recipients& MailMessage::recipients() const -{ - return _recipients; -} - - -inline const std::string& MailMessage::getContent() const -{ - return _content; -} - - -} } // namespace Poco::Net - - -#endif // Net_MailMessage_INCLUDED +// +// MailMessage.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/MailMessage.h#2 $ +// +// Library: Net +// Package: Mail +// Module: MailMessage +// +// Definition of the MailMessage 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_MailMessage_INCLUDED +#define Net_MailMessage_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/MessageHeader.h" +#include "Poco/Net/MailRecipient.h" +#include "Poco/Timestamp.h" +#include + + +namespace Poco { +namespace Net { + + +class MediaType; +class PartSource; +class PartHandler; +class MultipartWriter; + + +class Net_API MailMessage: public MessageHeader + /// This class represents an e-mail message for + /// use with the SMTPClientSession and POPClientSession + /// classes. + /// + /// MailMessage supports both old-style plain text messages, + /// as well as MIME multipart mail messages with attachments. + /// + /// For multi-part messages, the following content transfer + /// encodings are supported: 7bit, 8bit, quoted-printable + /// and base64. +{ +public: + typedef std::vector Recipients; + + enum ContentDisposition + { + CONTENT_INLINE, + CONTENT_ATTACHMENT + }; + + enum ContentTransferEncoding + { + ENCODING_7BIT, + ENCODING_8BIT, + ENCODING_QUOTED_PRINTABLE, + ENCODING_BASE64 + }; + + MailMessage(); + /// Creates an empty MailMessage. + + virtual ~MailMessage(); + /// Destroys the MailMessage. + + void addRecipient(const MailRecipient& recipient); + /// Adds a recipient for the message. + + const Recipients& recipients() const; + /// Returns the recipients of the message. + + void setSubject(const std::string& subject); + /// Sets the subject of the message. + + const std::string& getSubject() const; + /// Returns the subject of the message. + + void setSender(const std::string& sender); + /// Sets the sender of the message (which + /// ends up in the From header field). + + const std::string& getSender() const; + /// Returns the sender of the message (taken + /// from the From header field). + + void setContent(const std::string& content, ContentTransferEncoding encoding = ENCODING_QUOTED_PRINTABLE); + /// Sets the content of the mail message. + /// + /// If the content transfer encoding is ENCODING_7BIT or + /// ENCODING_8BIT, the content string must be formatted + /// according to the rules of an internet email message. + /// + /// The message will be sent as a single-part + /// message. + + const std::string& getContent() const; + /// Returns the content of the mail message. + /// + /// A content will only be returned for single-part + /// messages. The content of multi-part mail messages + /// will be reported through the registered PartHandler. + + void setContentType(const std::string& mediaType); + /// Sets the content type for the message. + + void setContentType(const MediaType& mediaType); + /// Sets the content type for the message. + + const std::string& getContentType() const; + /// Returns the content type for the message. + + void setDate(const Poco::Timestamp& dateTime); + /// Sets the Date header to the given date/time value. + + Poco::Timestamp getDate() const; + /// Returns the value of the Date header. + + bool isMultipart() const; + /// Returns true iff the message is a multipart message. + + void addPart(const std::string& name, PartSource* pSource, ContentDisposition disposition, ContentTransferEncoding encoding); + /// Adds a part/attachment to the mail message. + /// + /// The MailMessage takes ownership of the PartSource and deletes it + /// when it is no longer needed. + /// + /// The MailMessage will be converted to a multipart message + /// if it is not already one. + + void addContent(PartSource* pSource, ContentTransferEncoding encoding = ENCODING_QUOTED_PRINTABLE); + /// Adds a part to the mail message by calling + /// addPart("", pSource, CONTENT_INLINE, encoding); + + void addAttachment(const std::string& name, PartSource* pSource, ContentTransferEncoding encoding = ENCODING_BASE64); + /// Adds an attachment to the mail message by calling + /// addPart(name, pSource, CONTENT_ATTACHMENT, encoding); + + void read(std::istream& istr, PartHandler& handler); + /// Reads the MailMessage from the given input stream. + /// + /// If the message has multiple parts, the parts + /// are reported to the PartHandler. If the message + /// is not a multi-part message, the content is stored + /// in a string available by calling getContent(). + + void read(std::istream& istr); + /// Reads the MailMessage from the given input stream. + /// + /// The raw message (including all MIME parts) is stored + /// in a string and available by calling getContent(). + + void write(std::ostream& ostr) const; + /// Writes the mail message to the given output stream. + +protected: + struct Part + { + std::string name; + PartSource* pSource; + ContentDisposition disposition; + ContentTransferEncoding encoding; + }; + typedef std::vector PartVec; + + void makeMultipart(); + void writeHeader(const MessageHeader& header, std::ostream& ostr) const; + void writeMultipart(MessageHeader& header, std::ostream& ostr) const; + void writePart(MultipartWriter& writer, const Part& part) const; + void writeEncoded(std::istream& istr, std::ostream& ostr, ContentTransferEncoding encoding) const; + void setRecipientHeaders(MessageHeader& headers) const; + void readHeader(std::istream& istr); + void readMultipart(std::istream& istr, PartHandler& handler); + void readPart(std::istream& istr, const MessageHeader& header, PartHandler& handler); + void handlePart(std::istream& istr, const MessageHeader& header, PartHandler& handler); + static const std::string& contentTransferEncodingToString(ContentTransferEncoding encoding); + static int lineLength(const std::string& str); + static void appendRecipient(const MailRecipient& recipient, std::string& str); + + static const std::string HEADER_SUBJECT; + static const std::string HEADER_FROM; + static const std::string HEADER_TO; + static const std::string HEADER_CC; + static const std::string HEADER_BCC; + static const std::string HEADER_DATE; + static const std::string HEADER_CONTENT_TYPE; + static const std::string HEADER_CONTENT_TRANSFER_ENCODING; + static const std::string HEADER_CONTENT_DISPOSITION; + static const std::string HEADER_MIME_VERSION; + static const std::string EMPTY_HEADER; + static const std::string TEXT_PLAIN; + static const std::string CTE_7BIT; + static const std::string CTE_8BIT; + static const std::string CTE_QUOTED_PRINTABLE; + static const std::string CTE_BASE64; + +private: + MailMessage(const MailMessage&); + MailMessage& operator = (const MailMessage&); + + Recipients _recipients; + PartVec _parts; + std::string _content; + ContentTransferEncoding _encoding; +}; + + +// +// inlines +// +inline const MailMessage::Recipients& MailMessage::recipients() const +{ + return _recipients; +} + + +inline const std::string& MailMessage::getContent() const +{ + return _content; +} + + +} } // namespace Poco::Net + + +#endif // Net_MailMessage_INCLUDED diff --git a/Net/include/Poco/Net/MailRecipient.h b/Net/include/Poco/Net/MailRecipient.h index aaa4cb0ed..f5d161786 100644 --- a/Net/include/Poco/Net/MailRecipient.h +++ b/Net/include/Poco/Net/MailRecipient.h @@ -1,142 +1,142 @@ -// -// MailRecipient.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/MailRecipient.h#1 $ -// -// Library: Net -// Package: Mail -// Module: MailRecipient -// -// Definition of the MailRecipient 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_MailRecipient_INCLUDED -#define Net_MailRecipient_INCLUDED - - -#include "Poco/Net/Net.h" - - -namespace Poco { -namespace Net { - - -class Net_API MailRecipient - /// The recipient of an e-mail message. - /// - /// A recipient has a type (primary recipient, - /// carbon-copy recipient, blind-carbon-copy - /// recipient), an e-mail address and an optional - /// real name. -{ -public: - enum RecipientType - { - PRIMARY_RECIPIENT, - CC_RECIPIENT, - BCC_RECIPIENT - }; - - MailRecipient(); - /// Creates an empty MailRecipient. - - MailRecipient(const MailRecipient& recipient); - /// Creates a MailRecipient by copying another one. - - MailRecipient(RecipientType type, const std::string& address); - /// Creates a MailRecipient of the given type. - - MailRecipient(RecipientType type, const std::string& address, const std::string& realName); - /// Creates a MailRecipient of the given type. - - ~MailRecipient(); - /// Destroys the MailRecipient. - - MailRecipient& operator = (const MailRecipient& recipient); - /// Assigns another recipient. - - void swap(MailRecipient& recipient); - /// Exchanges the content of two recipients. - - RecipientType getType() const; - /// Returns the type of the recipient. - - void setType(RecipientType type); - /// Sets the type of the recipient. - - const std::string& getAddress() const; - /// Returns the address of the recipient. - - void setAddress(const std::string& address); - /// Sets the address of the recipient. - - const std::string& getRealName() const; - /// Returns the real name of the recipient. - - void setRealName(const std::string& realName); - /// Sets the real name of the recipient. - -private: - std::string _address; - std::string _realName; - RecipientType _type; -}; - - -// -// inlines -// -inline MailRecipient::RecipientType MailRecipient::getType() const -{ - return _type; -} - - -inline const std::string& MailRecipient::getAddress() const -{ - return _address; -} - - -inline const std::string& MailRecipient::getRealName() const -{ - return _realName; -} - - -inline void swap(MailRecipient& r1, MailRecipient& r2) -{ - r1.swap(r2); -} - - -} } // namespace Poco::Net - - -#endif // Net_MailRecipient_INCLUDED +// +// MailRecipient.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/MailRecipient.h#1 $ +// +// Library: Net +// Package: Mail +// Module: MailRecipient +// +// Definition of the MailRecipient 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_MailRecipient_INCLUDED +#define Net_MailRecipient_INCLUDED + + +#include "Poco/Net/Net.h" + + +namespace Poco { +namespace Net { + + +class Net_API MailRecipient + /// The recipient of an e-mail message. + /// + /// A recipient has a type (primary recipient, + /// carbon-copy recipient, blind-carbon-copy + /// recipient), an e-mail address and an optional + /// real name. +{ +public: + enum RecipientType + { + PRIMARY_RECIPIENT, + CC_RECIPIENT, + BCC_RECIPIENT + }; + + MailRecipient(); + /// Creates an empty MailRecipient. + + MailRecipient(const MailRecipient& recipient); + /// Creates a MailRecipient by copying another one. + + MailRecipient(RecipientType type, const std::string& address); + /// Creates a MailRecipient of the given type. + + MailRecipient(RecipientType type, const std::string& address, const std::string& realName); + /// Creates a MailRecipient of the given type. + + ~MailRecipient(); + /// Destroys the MailRecipient. + + MailRecipient& operator = (const MailRecipient& recipient); + /// Assigns another recipient. + + void swap(MailRecipient& recipient); + /// Exchanges the content of two recipients. + + RecipientType getType() const; + /// Returns the type of the recipient. + + void setType(RecipientType type); + /// Sets the type of the recipient. + + const std::string& getAddress() const; + /// Returns the address of the recipient. + + void setAddress(const std::string& address); + /// Sets the address of the recipient. + + const std::string& getRealName() const; + /// Returns the real name of the recipient. + + void setRealName(const std::string& realName); + /// Sets the real name of the recipient. + +private: + std::string _address; + std::string _realName; + RecipientType _type; +}; + + +// +// inlines +// +inline MailRecipient::RecipientType MailRecipient::getType() const +{ + return _type; +} + + +inline const std::string& MailRecipient::getAddress() const +{ + return _address; +} + + +inline const std::string& MailRecipient::getRealName() const +{ + return _realName; +} + + +inline void swap(MailRecipient& r1, MailRecipient& r2) +{ + r1.swap(r2); +} + + +} } // namespace Poco::Net + + +#endif // Net_MailRecipient_INCLUDED diff --git a/Net/include/Poco/Net/MailStream.h b/Net/include/Poco/Net/MailStream.h index 618d26926..542721428 100644 --- a/Net/include/Poco/Net/MailStream.h +++ b/Net/include/Poco/Net/MailStream.h @@ -1,168 +1,168 @@ -// -// MailStream.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/MailStream.h#1 $ -// -// Library: Net -// Package: Mail -// Module: MailStream -// -// Definition of the MailStream 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_MailStream_INCLUDED -#define Net_MailStream_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/UnbufferedStreamBuf.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class Net_API MailStreamBuf: public Poco::UnbufferedStreamBuf - /// The sole purpose of this stream buffer is to replace - /// a "\r\n.\r\n" character sequence with a "\r\n..\r\n" sequence for - /// output streams and vice-versa for input streams. - /// - /// This is used when sending mail messages to SMTP servers, or - /// receiving mail messages from POP servers. - /// - /// See RFC 2181 (Simple Mail Transfer Protocol) and RFC 1939 - /// (Post Office Protocol - Version 3) for more information. -{ -public: - MailStreamBuf(std::istream& istr); - /// Creates the MailStreamBuf and connects it - /// to the given input stream. - - MailStreamBuf(std::ostream& ostr); - /// Creates the MailStreamBuf and connects it - /// to the given output stream. - - ~MailStreamBuf(); - /// Destroys the MailStreamBuf. - - void close(); - /// Writes the terminating period, followed by - /// CR-LF. - -protected: - int readFromDevice(); - int writeToDevice(char c); - int readOne(); - -private: - enum State - { - ST_DATA, - ST_CR, - ST_CR_LF, - ST_CR_LF_DOT, - ST_CR_LF_DOT_DOT, - ST_CR_LF_DOT_CR, - ST_CR_LF_DOT_CR_LF - }; - - std::istream* _pIstr; - std::ostream* _pOstr; - std::string _buffer; - State _state; -}; - - -class Net_API MailIOS: public virtual std::ios - /// The base class for MailInputStream and MailOutputStream. - /// - /// This class provides common methods and is also needed to ensure - /// the correct initialization order of the stream buffer and base classes. -{ -public: - MailIOS(std::istream& istr); - /// Creates the MailIOS and connects it - /// to the given input stream. - - MailIOS(std::ostream& ostr); - /// Creates the MailIOS and connects it - /// to the given output stream. - - ~MailIOS(); - /// Destroys the stream. - - void close(); - /// Writes the terminating period, followed by - /// CR-LF. - - MailStreamBuf* rdbuf(); - /// Returns a pointer to the underlying streambuf. - -protected: - MailStreamBuf _buf; -}; - - -class Net_API MailInputStream: public MailIOS, public std::istream - /// This class is used for reading E-Mail messages from a - /// POP3 server. All occurences of "\r\n..\r\n" are replaced with - /// "\r\n.\r\n". The first occurence of "\r\n.\r\n" denotes the end - /// of the stream. -{ -public: - MailInputStream(std::istream& istr); - /// Creates the MailInputStream and connects it - /// to the given input stream. - - ~MailInputStream(); - /// Destroys the MailInputStream. -}; - - -class Net_API MailOutputStream: public MailIOS, public std::ostream - /// This class is used for writing E-Mail messages to a - /// SMTP server. All occurences of "\r\n.\r\n" are replaced with - /// "\r\n..\r\n". -{ -public: - MailOutputStream(std::ostream& ostr); - /// Creates the MailOutputStream and connects it - /// to the given input stream. - - ~MailOutputStream(); - /// Destroys the MailOutputStream. -}; - - -} } // namespace Poco::Net - - -#endif // Net_MailStream_INCLUDED +// +// MailStream.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/MailStream.h#1 $ +// +// Library: Net +// Package: Mail +// Module: MailStream +// +// Definition of the MailStream 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_MailStream_INCLUDED +#define Net_MailStream_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/UnbufferedStreamBuf.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class Net_API MailStreamBuf: public Poco::UnbufferedStreamBuf + /// The sole purpose of this stream buffer is to replace + /// a "\r\n.\r\n" character sequence with a "\r\n..\r\n" sequence for + /// output streams and vice-versa for input streams. + /// + /// This is used when sending mail messages to SMTP servers, or + /// receiving mail messages from POP servers. + /// + /// See RFC 2181 (Simple Mail Transfer Protocol) and RFC 1939 + /// (Post Office Protocol - Version 3) for more information. +{ +public: + MailStreamBuf(std::istream& istr); + /// Creates the MailStreamBuf and connects it + /// to the given input stream. + + MailStreamBuf(std::ostream& ostr); + /// Creates the MailStreamBuf and connects it + /// to the given output stream. + + ~MailStreamBuf(); + /// Destroys the MailStreamBuf. + + void close(); + /// Writes the terminating period, followed by + /// CR-LF. + +protected: + int readFromDevice(); + int writeToDevice(char c); + int readOne(); + +private: + enum State + { + ST_DATA, + ST_CR, + ST_CR_LF, + ST_CR_LF_DOT, + ST_CR_LF_DOT_DOT, + ST_CR_LF_DOT_CR, + ST_CR_LF_DOT_CR_LF + }; + + std::istream* _pIstr; + std::ostream* _pOstr; + std::string _buffer; + State _state; +}; + + +class Net_API MailIOS: public virtual std::ios + /// The base class for MailInputStream and MailOutputStream. + /// + /// This class provides common methods and is also needed to ensure + /// the correct initialization order of the stream buffer and base classes. +{ +public: + MailIOS(std::istream& istr); + /// Creates the MailIOS and connects it + /// to the given input stream. + + MailIOS(std::ostream& ostr); + /// Creates the MailIOS and connects it + /// to the given output stream. + + ~MailIOS(); + /// Destroys the stream. + + void close(); + /// Writes the terminating period, followed by + /// CR-LF. + + MailStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + MailStreamBuf _buf; +}; + + +class Net_API MailInputStream: public MailIOS, public std::istream + /// This class is used for reading E-Mail messages from a + /// POP3 server. All occurences of "\r\n..\r\n" are replaced with + /// "\r\n.\r\n". The first occurence of "\r\n.\r\n" denotes the end + /// of the stream. +{ +public: + MailInputStream(std::istream& istr); + /// Creates the MailInputStream and connects it + /// to the given input stream. + + ~MailInputStream(); + /// Destroys the MailInputStream. +}; + + +class Net_API MailOutputStream: public MailIOS, public std::ostream + /// This class is used for writing E-Mail messages to a + /// SMTP server. All occurences of "\r\n.\r\n" are replaced with + /// "\r\n..\r\n". +{ +public: + MailOutputStream(std::ostream& ostr); + /// Creates the MailOutputStream and connects it + /// to the given input stream. + + ~MailOutputStream(); + /// Destroys the MailOutputStream. +}; + + +} } // namespace Poco::Net + + +#endif // Net_MailStream_INCLUDED diff --git a/Net/include/Poco/Net/MediaType.h b/Net/include/Poco/Net/MediaType.h index 245a7f87e..6b97a9d2f 100644 --- a/Net/include/Poco/Net/MediaType.h +++ b/Net/include/Poco/Net/MediaType.h @@ -1,170 +1,170 @@ -// -// MediaType.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/MediaType.h#1 $ -// -// Library: Net -// Package: Messages -// Module: MediaType -// -// Definition of the MediaType 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_MediaType_INCLUDED -#define Net_MediaType_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/NameValueCollection.h" - - -namespace Poco { -namespace Net { - - -class Net_API MediaType - /// This class represents a MIME media type, consisting of - /// a top-level type, a subtype and an optional set of - /// parameters. - /// - /// The implementation conforms with RFC 2045 and RFC 2046. -{ -public: - MediaType(const std::string& mediaType); - /// Creates the MediaType from the given string, which - /// must have the format /{;=}. - - MediaType(const std::string& type, const std::string& subType); - /// Creates the MediaType, using the given type and subtype. - - MediaType(const MediaType& mediaType); - /// Creates a MediaType from another one. - - ~MediaType(); - /// Destroys the MediaType. - - MediaType& operator = (const MediaType& mediaType); - /// Assigns another media type. - - MediaType& operator = (const std::string& mediaType); - /// Assigns another media type. - - void swap(MediaType& mediaType); - /// Swaps the MediaType with another one. - - void setType(const std::string& type); - /// Sets the top-level type. - - const std::string& getType() const; - /// Returns the top-level type. - - void setSubType(const std::string& subType); - /// Sets the sub type. - - const std::string& getSubType() const; - /// Returns the sub type. - - void setParameter(const std::string& name, const std::string& value); - /// Sets the parameter with the given name. - - const std::string& getParameter(const std::string& name) const; - /// Returns the parameter with the given name. - /// - /// Throws a NotFoundException if the parameter does not exist. - - bool hasParameter(const std::string& name) const; - /// Returns true iff a parameter with the given name exists. - - void removeParameter(const std::string& name); - /// Removes the parameter with the given name. - - const NameValueCollection& parameters() const; - /// Returns the parameters. - - std::string toString() const; - /// Returns the string representation of the media type - /// which is /{;=} - - bool matches(const MediaType& mediaType) const; - /// Returns true iff the type and subtype match - /// the type and subtype of the given media type. - /// Matching is case insensitive. - - bool matches(const std::string& type, const std::string& subType) const; - /// Returns true iff the type and subtype match - /// the given type and subtype. - /// Matching is case insensitive. - - bool matches(const std::string& type) const; - /// Returns true iff the type matches the given type. - /// Matching is case insensitive. - -protected: - void parse(const std::string& mediaType); - -private: - MediaType(); - - std::string _type; - std::string _subType; - NameValueCollection _parameters; -}; - - -// -// inlines -// -inline const std::string& MediaType::getType() const -{ - return _type; -} - - -inline const std::string& MediaType::getSubType() const -{ - return _subType; -} - - -inline const NameValueCollection& MediaType::parameters() const -{ - return _parameters; -} - - -inline void swap(MediaType& m1, MediaType& m2) -{ - m1.swap(m2); -} - - -} } // namespace Poco::Net - - -#endif // Net_MediaType_INCLUDED +// +// MediaType.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/MediaType.h#1 $ +// +// Library: Net +// Package: Messages +// Module: MediaType +// +// Definition of the MediaType 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_MediaType_INCLUDED +#define Net_MediaType_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/NameValueCollection.h" + + +namespace Poco { +namespace Net { + + +class Net_API MediaType + /// This class represents a MIME media type, consisting of + /// a top-level type, a subtype and an optional set of + /// parameters. + /// + /// The implementation conforms with RFC 2045 and RFC 2046. +{ +public: + MediaType(const std::string& mediaType); + /// Creates the MediaType from the given string, which + /// must have the format /{;=}. + + MediaType(const std::string& type, const std::string& subType); + /// Creates the MediaType, using the given type and subtype. + + MediaType(const MediaType& mediaType); + /// Creates a MediaType from another one. + + ~MediaType(); + /// Destroys the MediaType. + + MediaType& operator = (const MediaType& mediaType); + /// Assigns another media type. + + MediaType& operator = (const std::string& mediaType); + /// Assigns another media type. + + void swap(MediaType& mediaType); + /// Swaps the MediaType with another one. + + void setType(const std::string& type); + /// Sets the top-level type. + + const std::string& getType() const; + /// Returns the top-level type. + + void setSubType(const std::string& subType); + /// Sets the sub type. + + const std::string& getSubType() const; + /// Returns the sub type. + + void setParameter(const std::string& name, const std::string& value); + /// Sets the parameter with the given name. + + const std::string& getParameter(const std::string& name) const; + /// Returns the parameter with the given name. + /// + /// Throws a NotFoundException if the parameter does not exist. + + bool hasParameter(const std::string& name) const; + /// Returns true iff a parameter with the given name exists. + + void removeParameter(const std::string& name); + /// Removes the parameter with the given name. + + const NameValueCollection& parameters() const; + /// Returns the parameters. + + std::string toString() const; + /// Returns the string representation of the media type + /// which is /{;=} + + bool matches(const MediaType& mediaType) const; + /// Returns true iff the type and subtype match + /// the type and subtype of the given media type. + /// Matching is case insensitive. + + bool matches(const std::string& type, const std::string& subType) const; + /// Returns true iff the type and subtype match + /// the given type and subtype. + /// Matching is case insensitive. + + bool matches(const std::string& type) const; + /// Returns true iff the type matches the given type. + /// Matching is case insensitive. + +protected: + void parse(const std::string& mediaType); + +private: + MediaType(); + + std::string _type; + std::string _subType; + NameValueCollection _parameters; +}; + + +// +// inlines +// +inline const std::string& MediaType::getType() const +{ + return _type; +} + + +inline const std::string& MediaType::getSubType() const +{ + return _subType; +} + + +inline const NameValueCollection& MediaType::parameters() const +{ + return _parameters; +} + + +inline void swap(MediaType& m1, MediaType& m2) +{ + m1.swap(m2); +} + + +} } // namespace Poco::Net + + +#endif // Net_MediaType_INCLUDED diff --git a/Net/include/Poco/Net/MessageHeader.h b/Net/include/Poco/Net/MessageHeader.h index c0c949c79..ce3813d2f 100644 --- a/Net/include/Poco/Net/MessageHeader.h +++ b/Net/include/Poco/Net/MessageHeader.h @@ -1,157 +1,157 @@ -// -// MessageHeader.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/MessageHeader.h#1 $ -// -// Library: Net -// Package: Messages -// Module: MessageHeader -// -// Definition of the MessageHeader 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_MessageHeader_INCLUDED -#define Net_MessageHeader_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/NameValueCollection.h" -#include -#include -#include - - -namespace Poco { -namespace Net { - - -class Net_API MessageHeader: public NameValueCollection - /// A collection of name-value pairs that are used in - /// various internet protocols like HTTP and SMTP. - /// - /// The name is case-insensitive. - /// - /// There can be more than one name-value pair with the - /// same name. - /// - /// MessageHeader supports writing and reading the - /// header data in RFC 2822 format. -{ -public: - MessageHeader(); - /// Creates the MessageHeader. - - MessageHeader(const MessageHeader& messageHeader); - /// Creates the MessageHeader by copying - /// another one. - - virtual ~MessageHeader(); - /// Destroys the MessageHeader. - - MessageHeader& operator = (const MessageHeader& messageHeader); - /// Assigns the content of another MessageHeader. - - virtual void write(std::ostream& ostr) const; - /// Writes the message header to the given output stream. - /// - /// The format is one name-value pair per line, with - /// name and value separated by a colon and lines - /// delimited by a carriage return and a linefeed - /// character. See RFC 2822 for details. - - virtual void read(std::istream& istr); - /// Reads the message header from the given input stream. - /// - /// See write() for the expected format. - /// Also supported is folding of field content, according - /// to section 2.2.3 of RFC 2822. - /// - /// Reading stops at the first empty line (a line only - /// containing \r\n or \n), as well as at the end of - /// the stream. - /// - /// Some basic sanity checking of the input stream is - /// performed. - /// - /// Throws a MessageException if the input stream is - /// malformed. - - static void splitElements(const std::string& s, std::vector& elements, bool ignoreEmpty = true); - /// Splits the given string into separate elements. Elements are expected - /// to be separated by commas. - /// - /// For example, the string - /// text/plain; q=0.5, text/html, text/x-dvi; q=0.8 - /// is split into the elements - /// text/plain; q=0.5 - /// text/html - /// text/x-dvi; q=0.8 - /// - /// Commas enclosed in double quotes do not split elements. - /// - /// If ignoreEmpty is true, empty elements are not returned. - - static void splitParameters(const std::string& s, std::string& value, NameValueCollection& parameters); - /// Splits the given string into a value and a collection of parameters. - /// Parameters are expected to be separated by semicolons. - /// - /// Enclosing quotes of parameter values are removed. - /// - /// For example, the string - /// multipart/mixed; boundary="MIME_boundary_01234567" - /// is split into the value - /// multipart/mixed - /// and the parameter - /// boundary -> MIME_boundary_01234567 - - static void splitParameters(const std::string::const_iterator& begin, const std::string::const_iterator& end, NameValueCollection& parameters); - /// Splits the given string into a collection of parameters. - /// Parameters are expected to be separated by semicolons. - /// - /// Enclosing quotes of parameter values are removed. - - static void quote(const std::string& value, std::string& result, bool allowSpace = false); - /// Checks if the value must be quoted. If so, the value is - /// appended to result, enclosed in double-quotes. - /// Otherwise. the value is appended to result as-is. - -private: - enum Limits - /// Limits for basic sanity checks when reading a header - { - MAX_NAME_LENGTH = 256, - MAX_VALUE_LENGTH = 4096 - }; -}; - - -} } // namespace Poco::Net - - -#endif // Net_MessageHeader_INCLUDED +// +// MessageHeader.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/MessageHeader.h#1 $ +// +// Library: Net +// Package: Messages +// Module: MessageHeader +// +// Definition of the MessageHeader 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_MessageHeader_INCLUDED +#define Net_MessageHeader_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/NameValueCollection.h" +#include +#include +#include + + +namespace Poco { +namespace Net { + + +class Net_API MessageHeader: public NameValueCollection + /// A collection of name-value pairs that are used in + /// various internet protocols like HTTP and SMTP. + /// + /// The name is case-insensitive. + /// + /// There can be more than one name-value pair with the + /// same name. + /// + /// MessageHeader supports writing and reading the + /// header data in RFC 2822 format. +{ +public: + MessageHeader(); + /// Creates the MessageHeader. + + MessageHeader(const MessageHeader& messageHeader); + /// Creates the MessageHeader by copying + /// another one. + + virtual ~MessageHeader(); + /// Destroys the MessageHeader. + + MessageHeader& operator = (const MessageHeader& messageHeader); + /// Assigns the content of another MessageHeader. + + virtual void write(std::ostream& ostr) const; + /// Writes the message header to the given output stream. + /// + /// The format is one name-value pair per line, with + /// name and value separated by a colon and lines + /// delimited by a carriage return and a linefeed + /// character. See RFC 2822 for details. + + virtual void read(std::istream& istr); + /// Reads the message header from the given input stream. + /// + /// See write() for the expected format. + /// Also supported is folding of field content, according + /// to section 2.2.3 of RFC 2822. + /// + /// Reading stops at the first empty line (a line only + /// containing \r\n or \n), as well as at the end of + /// the stream. + /// + /// Some basic sanity checking of the input stream is + /// performed. + /// + /// Throws a MessageException if the input stream is + /// malformed. + + static void splitElements(const std::string& s, std::vector& elements, bool ignoreEmpty = true); + /// Splits the given string into separate elements. Elements are expected + /// to be separated by commas. + /// + /// For example, the string + /// text/plain; q=0.5, text/html, text/x-dvi; q=0.8 + /// is split into the elements + /// text/plain; q=0.5 + /// text/html + /// text/x-dvi; q=0.8 + /// + /// Commas enclosed in double quotes do not split elements. + /// + /// If ignoreEmpty is true, empty elements are not returned. + + static void splitParameters(const std::string& s, std::string& value, NameValueCollection& parameters); + /// Splits the given string into a value and a collection of parameters. + /// Parameters are expected to be separated by semicolons. + /// + /// Enclosing quotes of parameter values are removed. + /// + /// For example, the string + /// multipart/mixed; boundary="MIME_boundary_01234567" + /// is split into the value + /// multipart/mixed + /// and the parameter + /// boundary -> MIME_boundary_01234567 + + static void splitParameters(const std::string::const_iterator& begin, const std::string::const_iterator& end, NameValueCollection& parameters); + /// Splits the given string into a collection of parameters. + /// Parameters are expected to be separated by semicolons. + /// + /// Enclosing quotes of parameter values are removed. + + static void quote(const std::string& value, std::string& result, bool allowSpace = false); + /// Checks if the value must be quoted. If so, the value is + /// appended to result, enclosed in double-quotes. + /// Otherwise. the value is appended to result as-is. + +private: + enum Limits + /// Limits for basic sanity checks when reading a header + { + MAX_NAME_LENGTH = 256, + MAX_VALUE_LENGTH = 4096 + }; +}; + + +} } // namespace Poco::Net + + +#endif // Net_MessageHeader_INCLUDED diff --git a/Net/include/Poco/Net/MulticastSocket.h b/Net/include/Poco/Net/MulticastSocket.h index 7f908de15..1440e19e9 100644 --- a/Net/include/Poco/Net/MulticastSocket.h +++ b/Net/include/Poco/Net/MulticastSocket.h @@ -1,138 +1,138 @@ -// -// MulticastSocket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/MulticastSocket.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: MulticastSocket -// -// Definition of the MulticastSocket 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_MulticastSocket_INCLUDED -#define Net_MulticastSocket_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/DatagramSocket.h" -#include "Poco/Net/NetworkInterface.h" - - -namespace Poco { -namespace Net { - - -class Net_API MulticastSocket: public DatagramSocket - /// A MulticastSocket is a special DatagramSocket - /// that can be used to send packets to and receive - /// packets from multicast groups. -{ -public: - MulticastSocket(); - /// Creates the MulticastSocket. - - MulticastSocket(IPAddress::Family family); - /// Creates an unconnected datagram socket. - /// - /// The socket will be created for the - /// given address family. - - MulticastSocket(const SocketAddress& address, bool reuseAddress = false); - /// Creates a datagram socket and binds it - /// to the given address. - /// - /// Depending on the address family, the socket - /// will be either an IPv4 or an IPv6 socket. - - MulticastSocket(const Socket& socket); - /// Creates the DatagramSocket with the SocketImpl - /// from another socket. The SocketImpl must be - /// a DatagramSocketImpl, otherwise an InvalidArgumentException - /// will be thrown. - - ~MulticastSocket(); - /// Destroys the DatagramSocket. - - MulticastSocket& operator = (const Socket& socket); - /// Assignment operator. - /// - /// Releases the socket's SocketImpl and - /// attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - void setInterface(const NetworkInterface& interface); - /// Sets the interface used for sending multicast packets. - /// - /// To select the default interface, specify an empty - /// interface. - /// - /// This is done by setting the IP_MULTICAST_IF/IPV6_MULTICAST_IF - /// socket option. - - NetworkInterface getInterface() const; - /// Returns the interface used for sending multicast packets. - - void setLoopback(bool flag); - /// Enable or disable loopback for multicast packets. - /// - /// Sets the value of the IP_MULTICAST_LOOP/IPV6_MULTICAST_LOOP - /// socket option. - - bool getLoopback() const; - /// Returns true iff loopback for multicast packets is enabled, - /// false otherwise. - - void setTimeToLive(unsigned value); - /// Specifies the TTL/hop limit for outgoing packets. - /// - /// Sets the value of the IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS - /// socket option. - - unsigned getTimeToLive() const; - /// Returns the TTL/hop limit for outgoing packets. - - void joinGroup(const IPAddress& groupAddress); - /// Joins the specified multicast group at the default interface. - - void joinGroup(const IPAddress& groupAddress, const NetworkInterface& interface); - /// Joins the specified multicast group at the given interface. - - void leaveGroup(const IPAddress& groupAddress); - /// Leaves the specified multicast group at the default interface. - - void leaveGroup(const IPAddress& groupAddress, const NetworkInterface& interface); - /// Leaves the specified multicast group at the given interface. -}; - - -} } // namespace Poco::Net - - -#endif // Net_MulticastSocket_INCLUDED +// +// MulticastSocket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/MulticastSocket.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: MulticastSocket +// +// Definition of the MulticastSocket 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_MulticastSocket_INCLUDED +#define Net_MulticastSocket_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/DatagramSocket.h" +#include "Poco/Net/NetworkInterface.h" + + +namespace Poco { +namespace Net { + + +class Net_API MulticastSocket: public DatagramSocket + /// A MulticastSocket is a special DatagramSocket + /// that can be used to send packets to and receive + /// packets from multicast groups. +{ +public: + MulticastSocket(); + /// Creates the MulticastSocket. + + MulticastSocket(IPAddress::Family family); + /// Creates an unconnected datagram socket. + /// + /// The socket will be created for the + /// given address family. + + MulticastSocket(const SocketAddress& address, bool reuseAddress = false); + /// Creates a datagram socket and binds it + /// to the given address. + /// + /// Depending on the address family, the socket + /// will be either an IPv4 or an IPv6 socket. + + MulticastSocket(const Socket& socket); + /// Creates the DatagramSocket with the SocketImpl + /// from another socket. The SocketImpl must be + /// a DatagramSocketImpl, otherwise an InvalidArgumentException + /// will be thrown. + + ~MulticastSocket(); + /// Destroys the DatagramSocket. + + MulticastSocket& operator = (const Socket& socket); + /// Assignment operator. + /// + /// Releases the socket's SocketImpl and + /// attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + void setInterface(const NetworkInterface& interface); + /// Sets the interface used for sending multicast packets. + /// + /// To select the default interface, specify an empty + /// interface. + /// + /// This is done by setting the IP_MULTICAST_IF/IPV6_MULTICAST_IF + /// socket option. + + NetworkInterface getInterface() const; + /// Returns the interface used for sending multicast packets. + + void setLoopback(bool flag); + /// Enable or disable loopback for multicast packets. + /// + /// Sets the value of the IP_MULTICAST_LOOP/IPV6_MULTICAST_LOOP + /// socket option. + + bool getLoopback() const; + /// Returns true iff loopback for multicast packets is enabled, + /// false otherwise. + + void setTimeToLive(unsigned value); + /// Specifies the TTL/hop limit for outgoing packets. + /// + /// Sets the value of the IP_MULTICAST_TTL/IPV6_MULTICAST_HOPS + /// socket option. + + unsigned getTimeToLive() const; + /// Returns the TTL/hop limit for outgoing packets. + + void joinGroup(const IPAddress& groupAddress); + /// Joins the specified multicast group at the default interface. + + void joinGroup(const IPAddress& groupAddress, const NetworkInterface& interface); + /// Joins the specified multicast group at the given interface. + + void leaveGroup(const IPAddress& groupAddress); + /// Leaves the specified multicast group at the default interface. + + void leaveGroup(const IPAddress& groupAddress, const NetworkInterface& interface); + /// Leaves the specified multicast group at the given interface. +}; + + +} } // namespace Poco::Net + + +#endif // Net_MulticastSocket_INCLUDED diff --git a/Net/include/Poco/Net/MultipartReader.h b/Net/include/Poco/Net/MultipartReader.h index 805166c27..652fc9643 100644 --- a/Net/include/Poco/Net/MultipartReader.h +++ b/Net/include/Poco/Net/MultipartReader.h @@ -1,182 +1,182 @@ -// -// MultipartReader.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/MultipartReader.h#2 $ -// -// Library: Net -// Package: Messages -// Module: MultipartReader -// -// Definition of the MultipartReader 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_MultipartReader_INCLUDED -#define Net_MultipartReader_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/BufferedStreamBuf.h" -#include - - -namespace Poco { -namespace Net { - - -class MessageHeader; - - -class Net_API MultipartStreamBuf: public Poco::BufferedStreamBuf - /// This is the streambuf class used for reading from a multipart message stream. -{ -public: - MultipartStreamBuf(std::istream& istr, const std::string& boundary); - ~MultipartStreamBuf(); - bool lastPart() const; - -protected: - int readFromDevice(char* buffer, std::streamsize length); - -private: - enum - { - STREAM_BUFFER_SIZE = 1024 - }; - - std::istream& _istr; - std::string _boundary; - bool _lastPart; -}; - - -class Net_API MultipartIOS: public virtual std::ios - /// The base class for MultipartInputStream. -{ -public: - MultipartIOS(std::istream& istr, const std::string& boundary); - ~MultipartIOS(); - MultipartStreamBuf* rdbuf(); - bool lastPart() const; - -protected: - MultipartStreamBuf _buf; -}; - - -class Net_API MultipartInputStream: public MultipartIOS, public std::istream - /// This class is for internal use by MultipartReader only. -{ -public: - MultipartInputStream(std::istream& istr, const std::string& boundary); - ~MultipartInputStream(); -}; - - - -class Net_API MultipartReader - /// This class is used to split a MIME multipart - /// message into its single parts. - /// - /// The format of multipart messages is described - /// in section 7.2 of RFC 1341. - /// - /// To split a multipart message into its parts, - /// do the following: - /// - Create a MultipartReader object, passing it - /// an input stream and optionally a boundary string. - /// - while hasNextPart() returns true, call nextPart() - /// and read the part from stream(). - /// - /// Always ensure that you read all data from the part - /// stream, otherwise the MultipartReader will fail to - /// find the next part. -{ -public: - explicit MultipartReader(std::istream& istr); - /// Creates the MultipartReader and attaches it to the - /// given input stream. - /// - /// The boundary string is determined from the input - /// stream. The message must not contain a preamble - /// preceding the first encapsulation boundary. - - MultipartReader(std::istream& istr, const std::string& boundary); - /// Creates the MultipartReader and attaches it to the - /// given input stream. The given boundary string is - /// used to find message boundaries. - - ~MultipartReader(); - /// Destroys the MultipartReader. - - void nextPart(MessageHeader& messageHeader); - /// Moves to the next part in the message and stores the - /// part's header fields in messageHeader. - /// - /// Throws an MultipartException if there are no more parts - /// available, or if no boundary line can be found in - /// the input stream. - - bool hasNextPart(); - /// Returns true iff more parts are available. - /// - /// Before the first call to nextPart(), returns - /// always true. - - std::istream& stream() const; - /// Returns a reference to the reader's stream that - /// can be used to read the current part. - /// - /// The returned reference will be valid until - /// nextPart() is called or the MultipartReader - /// object is destroyed. - - const std::string& boundary() const; - /// Returns the multipart boundary used by this reader. - -protected: - void findFirstBoundary(); - void guessBoundary(); - void parseHeader(MessageHeader& messageHeader); - bool readLine(std::string& line, std::string::size_type n); - -private: - MultipartReader(); - MultipartReader(const MultipartReader&); - MultipartReader& operator = (const MultipartReader&); - - std::istream& _istr; - std::string _boundary; - MultipartInputStream* _pMPI; -}; - - -} } // namespace Poco::Net - - -#endif // Net_MultipartReader_INCLUDED +// +// MultipartReader.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/MultipartReader.h#2 $ +// +// Library: Net +// Package: Messages +// Module: MultipartReader +// +// Definition of the MultipartReader 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_MultipartReader_INCLUDED +#define Net_MultipartReader_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/BufferedStreamBuf.h" +#include + + +namespace Poco { +namespace Net { + + +class MessageHeader; + + +class Net_API MultipartStreamBuf: public Poco::BufferedStreamBuf + /// This is the streambuf class used for reading from a multipart message stream. +{ +public: + MultipartStreamBuf(std::istream& istr, const std::string& boundary); + ~MultipartStreamBuf(); + bool lastPart() const; + +protected: + int readFromDevice(char* buffer, std::streamsize length); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024 + }; + + std::istream& _istr; + std::string _boundary; + bool _lastPart; +}; + + +class Net_API MultipartIOS: public virtual std::ios + /// The base class for MultipartInputStream. +{ +public: + MultipartIOS(std::istream& istr, const std::string& boundary); + ~MultipartIOS(); + MultipartStreamBuf* rdbuf(); + bool lastPart() const; + +protected: + MultipartStreamBuf _buf; +}; + + +class Net_API MultipartInputStream: public MultipartIOS, public std::istream + /// This class is for internal use by MultipartReader only. +{ +public: + MultipartInputStream(std::istream& istr, const std::string& boundary); + ~MultipartInputStream(); +}; + + + +class Net_API MultipartReader + /// This class is used to split a MIME multipart + /// message into its single parts. + /// + /// The format of multipart messages is described + /// in section 7.2 of RFC 1341. + /// + /// To split a multipart message into its parts, + /// do the following: + /// - Create a MultipartReader object, passing it + /// an input stream and optionally a boundary string. + /// - while hasNextPart() returns true, call nextPart() + /// and read the part from stream(). + /// + /// Always ensure that you read all data from the part + /// stream, otherwise the MultipartReader will fail to + /// find the next part. +{ +public: + explicit MultipartReader(std::istream& istr); + /// Creates the MultipartReader and attaches it to the + /// given input stream. + /// + /// The boundary string is determined from the input + /// stream. The message must not contain a preamble + /// preceding the first encapsulation boundary. + + MultipartReader(std::istream& istr, const std::string& boundary); + /// Creates the MultipartReader and attaches it to the + /// given input stream. The given boundary string is + /// used to find message boundaries. + + ~MultipartReader(); + /// Destroys the MultipartReader. + + void nextPart(MessageHeader& messageHeader); + /// Moves to the next part in the message and stores the + /// part's header fields in messageHeader. + /// + /// Throws an MultipartException if there are no more parts + /// available, or if no boundary line can be found in + /// the input stream. + + bool hasNextPart(); + /// Returns true iff more parts are available. + /// + /// Before the first call to nextPart(), returns + /// always true. + + std::istream& stream() const; + /// Returns a reference to the reader's stream that + /// can be used to read the current part. + /// + /// The returned reference will be valid until + /// nextPart() is called or the MultipartReader + /// object is destroyed. + + const std::string& boundary() const; + /// Returns the multipart boundary used by this reader. + +protected: + void findFirstBoundary(); + void guessBoundary(); + void parseHeader(MessageHeader& messageHeader); + bool readLine(std::string& line, std::string::size_type n); + +private: + MultipartReader(); + MultipartReader(const MultipartReader&); + MultipartReader& operator = (const MultipartReader&); + + std::istream& _istr; + std::string _boundary; + MultipartInputStream* _pMPI; +}; + + +} } // namespace Poco::Net + + +#endif // Net_MultipartReader_INCLUDED diff --git a/Net/include/Poco/Net/MultipartWriter.h b/Net/include/Poco/Net/MultipartWriter.h index 8b07110c4..14829a67f 100644 --- a/Net/include/Poco/Net/MultipartWriter.h +++ b/Net/include/Poco/Net/MultipartWriter.h @@ -1,130 +1,130 @@ -// -// MultipartWriter.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/MultipartWriter.h#1 $ -// -// Library: Net -// Package: Messages -// Module: MultipartWriter -// -// Definition of the MultipartWriter 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_MultipartWriter_INCLUDED -#define Net_MultipartWriter_INCLUDED - - -#include "Poco/Net/Net.h" -#include - - -namespace Poco { -namespace Net { - - -class MessageHeader; - - -class Net_API MultipartWriter - /// This class is used to write MIME multipart - /// messages to an output stream. - /// - /// The format of multipart messages is described - /// in section 7.2 of RFC 1341. - /// - /// To create a multipart message, first create - /// a MultipartWriter object. - /// Then, for each part, call nextPart() and - /// write the content to the output stream. - /// Repeat for all parts. - /// After the last part has been written, - /// call close() to finish the multipart message. -{ -public: - explicit MultipartWriter(std::ostream& ostr); - /// Creates the MultipartWriter, using the - /// given output stream. - /// - /// Creates a random boundary string. - - MultipartWriter(std::ostream& ostr, const std::string& boundary); - /// Creates the MultipartWriter, using the - /// given output stream and boundary string. - - ~MultipartWriter(); - /// Destroys the MultipartWriter. - - void nextPart(const MessageHeader& header); - /// Opens a new message part and writes - /// the message boundary string, followed - /// by the message header to the stream. - - void close(); - /// Closes the multipart message and writes - /// the terminating boundary string. - /// - /// Does not close the underlying stream. - - std::ostream& stream(); - /// Returns the writer's stream. - - const std::string& boundary() const; - /// Returns the multipart boundary used by this writer. - - static std::string createBoundary(); - /// Creates a random boundary string. - /// - /// The string always has the form - /// MIME_boundary_XXXXXXXXXXXX, where - /// XXXXXXXXXXXX is a random hexadecimal - /// number. - -private: - MultipartWriter(); - MultipartWriter(const MultipartWriter&); - MultipartWriter& operator = (const MultipartWriter&); - - std::ostream& _ostr; - std::string _boundary; -}; - - -// -// inlines -// -inline std::ostream& MultipartWriter::stream() -{ - return _ostr; -} - - -} } // namespace Poco::Net - - -#endif // Net_MultipartWriter_INCLUDED +// +// MultipartWriter.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/MultipartWriter.h#1 $ +// +// Library: Net +// Package: Messages +// Module: MultipartWriter +// +// Definition of the MultipartWriter 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_MultipartWriter_INCLUDED +#define Net_MultipartWriter_INCLUDED + + +#include "Poco/Net/Net.h" +#include + + +namespace Poco { +namespace Net { + + +class MessageHeader; + + +class Net_API MultipartWriter + /// This class is used to write MIME multipart + /// messages to an output stream. + /// + /// The format of multipart messages is described + /// in section 7.2 of RFC 1341. + /// + /// To create a multipart message, first create + /// a MultipartWriter object. + /// Then, for each part, call nextPart() and + /// write the content to the output stream. + /// Repeat for all parts. + /// After the last part has been written, + /// call close() to finish the multipart message. +{ +public: + explicit MultipartWriter(std::ostream& ostr); + /// Creates the MultipartWriter, using the + /// given output stream. + /// + /// Creates a random boundary string. + + MultipartWriter(std::ostream& ostr, const std::string& boundary); + /// Creates the MultipartWriter, using the + /// given output stream and boundary string. + + ~MultipartWriter(); + /// Destroys the MultipartWriter. + + void nextPart(const MessageHeader& header); + /// Opens a new message part and writes + /// the message boundary string, followed + /// by the message header to the stream. + + void close(); + /// Closes the multipart message and writes + /// the terminating boundary string. + /// + /// Does not close the underlying stream. + + std::ostream& stream(); + /// Returns the writer's stream. + + const std::string& boundary() const; + /// Returns the multipart boundary used by this writer. + + static std::string createBoundary(); + /// Creates a random boundary string. + /// + /// The string always has the form + /// MIME_boundary_XXXXXXXXXXXX, where + /// XXXXXXXXXXXX is a random hexadecimal + /// number. + +private: + MultipartWriter(); + MultipartWriter(const MultipartWriter&); + MultipartWriter& operator = (const MultipartWriter&); + + std::ostream& _ostr; + std::string _boundary; +}; + + +// +// inlines +// +inline std::ostream& MultipartWriter::stream() +{ + return _ostr; +} + + +} } // namespace Poco::Net + + +#endif // Net_MultipartWriter_INCLUDED diff --git a/Net/include/Poco/Net/NameValueCollection.h b/Net/include/Poco/Net/NameValueCollection.h index 8b6c1cca1..e589a70d9 100644 --- a/Net/include/Poco/Net/NameValueCollection.h +++ b/Net/include/Poco/Net/NameValueCollection.h @@ -1,155 +1,155 @@ -// -// NameValueCollection.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/NameValueCollection.h#1 $ -// -// Library: Net -// Package: Messages -// Module: NameValueCollection -// -// Definition of the NameValueCollection 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_NameValueCollection_INCLUDED -#define Net_NameValueCollection_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/String.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API NameValueCollection - /// A collection of name-value pairs that are used in - /// various internet protocols like HTTP and SMTP. - /// - /// The name is case-insensitive. - /// - /// There can be more than one name-value pair with the - /// same name. -{ -public: - struct ILT - { - bool operator() (const std::string& s1, const std::string& s2) const - { - return Poco::icompare(s1, s2) < 0; - } - }; - - typedef std::multimap HeaderMap; - typedef HeaderMap::iterator Iterator; - typedef HeaderMap::const_iterator ConstIterator; - - NameValueCollection(); - /// Creates an empty NameValueCollection. - - NameValueCollection(const NameValueCollection& nvc); - /// Creates a NameValueCollection by copying another one. - - virtual ~NameValueCollection(); - /// Destroys the NameValueCollection. - - NameValueCollection& operator = (const NameValueCollection& nvc); - /// Assigns the name-value pairs of another NameValueCollection to this one. - - void swap(NameValueCollection& nvc); - /// Swaps the NameValueCollection with another one. - - const std::string& operator [] (const std::string& name) const; - /// Returns the value of the (first) name-value pair with the given name. - /// - /// Throws a NotFoundException if the name-value pair does not exist. - - void set(const std::string& name, const std::string& value); - /// Sets the value of the (first) name-value pair with the given name. - - void add(const std::string& name, const std::string& value); - /// Adds a new name-value pair with the given name and value. - - const std::string& get(const std::string& name) const; - /// Returns the value of the first name-value pair with the given name. - /// - /// Throws a NotFoundException if the name-value pair does not exist. - - const std::string& get(const std::string& name, const std::string& defaultValue) const; - /// Returns the value of the first name-value pair with the given name. - /// If no value with the given name has been found, the defaultValue is returned. - - bool has(const std::string& name) const; - /// Returns true if there is at least one name-value pair - /// with the given name. - - ConstIterator find(const std::string& name) const; - /// Returns an iterator pointing to the first name-value pair - /// with the given name. - - ConstIterator begin() const; - /// Returns an iterator pointing to the begin of - /// the name-value pair collection. - - ConstIterator end() const; - /// Returns an iterator pointing to the end of - /// the name-value pair collection. - - bool empty() const; - /// Returns true iff the header does not have any content. - - int size() const; - /// Returns the number of name-value pairs in the - /// collection. - - void erase(const std::string& name); - /// Removes all name-value pairs with the given name. - - void clear(); - /// Removes all name-value pairs and their values. - -private: - HeaderMap _map; -}; - - -// -// inlines -// -inline void swap(NameValueCollection& nvc1, NameValueCollection& nvc2) -{ - nvc1.swap(nvc2); -} - - -} } // namespace Poco::Net - - -#endif // Net_NameValueCollection_INCLUDED +// +// NameValueCollection.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/NameValueCollection.h#1 $ +// +// Library: Net +// Package: Messages +// Module: NameValueCollection +// +// Definition of the NameValueCollection 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_NameValueCollection_INCLUDED +#define Net_NameValueCollection_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/String.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API NameValueCollection + /// A collection of name-value pairs that are used in + /// various internet protocols like HTTP and SMTP. + /// + /// The name is case-insensitive. + /// + /// There can be more than one name-value pair with the + /// same name. +{ +public: + struct ILT + { + bool operator() (const std::string& s1, const std::string& s2) const + { + return Poco::icompare(s1, s2) < 0; + } + }; + + typedef std::multimap HeaderMap; + typedef HeaderMap::iterator Iterator; + typedef HeaderMap::const_iterator ConstIterator; + + NameValueCollection(); + /// Creates an empty NameValueCollection. + + NameValueCollection(const NameValueCollection& nvc); + /// Creates a NameValueCollection by copying another one. + + virtual ~NameValueCollection(); + /// Destroys the NameValueCollection. + + NameValueCollection& operator = (const NameValueCollection& nvc); + /// Assigns the name-value pairs of another NameValueCollection to this one. + + void swap(NameValueCollection& nvc); + /// Swaps the NameValueCollection with another one. + + const std::string& operator [] (const std::string& name) const; + /// Returns the value of the (first) name-value pair with the given name. + /// + /// Throws a NotFoundException if the name-value pair does not exist. + + void set(const std::string& name, const std::string& value); + /// Sets the value of the (first) name-value pair with the given name. + + void add(const std::string& name, const std::string& value); + /// Adds a new name-value pair with the given name and value. + + const std::string& get(const std::string& name) const; + /// Returns the value of the first name-value pair with the given name. + /// + /// Throws a NotFoundException if the name-value pair does not exist. + + const std::string& get(const std::string& name, const std::string& defaultValue) const; + /// Returns the value of the first name-value pair with the given name. + /// If no value with the given name has been found, the defaultValue is returned. + + bool has(const std::string& name) const; + /// Returns true if there is at least one name-value pair + /// with the given name. + + ConstIterator find(const std::string& name) const; + /// Returns an iterator pointing to the first name-value pair + /// with the given name. + + ConstIterator begin() const; + /// Returns an iterator pointing to the begin of + /// the name-value pair collection. + + ConstIterator end() const; + /// Returns an iterator pointing to the end of + /// the name-value pair collection. + + bool empty() const; + /// Returns true iff the header does not have any content. + + int size() const; + /// Returns the number of name-value pairs in the + /// collection. + + void erase(const std::string& name); + /// Removes all name-value pairs with the given name. + + void clear(); + /// Removes all name-value pairs and their values. + +private: + HeaderMap _map; +}; + + +// +// inlines +// +inline void swap(NameValueCollection& nvc1, NameValueCollection& nvc2) +{ + nvc1.swap(nvc2); +} + + +} } // namespace Poco::Net + + +#endif // Net_NameValueCollection_INCLUDED diff --git a/Net/include/Poco/Net/Net.h b/Net/include/Poco/Net/Net.h index 70983b2f3..820bf9909 100644 --- a/Net/include/Poco/Net/Net.h +++ b/Net/include/Poco/Net/Net.h @@ -1,70 +1,70 @@ -// -// Net.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/Net.h#1 $ -// -// Library: Net -// Package: NetCore -// Module: IPAddress -// -// Basic definitions for the Poco Net library. -// This file must be the first file included by every other Net -// header file. -// -// 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_Net_INCLUDED -#define Net_Net_INCLUDED - - -#include "Poco/Foundation.h" - - -// -// The following block is the standard way of creating macros which make exporting -// from a DLL simpler. All files within this DLL are compiled with the Net_EXPORTS -// symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see -// Net_API functions as being imported from a DLL, wheras this DLL sees symbols -// defined with this macro as being exported. -// -#if defined(_WIN32) && defined(POCO_DLL) - #if defined(Net_EXPORTS) - #define Net_API __declspec(dllexport) - #else - #define Net_API __declspec(dllimport) - #endif -#endif - - -#if !defined(Net_API) - #define Net_API -#endif - - -#endif // Net_Net_INCLUDED +// +// Net.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/Net.h#1 $ +// +// Library: Net +// Package: NetCore +// Module: IPAddress +// +// Basic definitions for the Poco Net library. +// This file must be the first file included by every other Net +// header file. +// +// 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_Net_INCLUDED +#define Net_Net_INCLUDED + + +#include "Poco/Foundation.h" + + +// +// The following block is the standard way of creating macros which make exporting +// from a DLL simpler. All files within this DLL are compiled with the Net_EXPORTS +// symbol defined on the command line. this symbol should not be defined on any project +// that uses this DLL. This way any other project whose source files include this file see +// Net_API functions as being imported from a DLL, wheras this DLL sees symbols +// defined with this macro as being exported. +// +#if defined(_WIN32) && defined(POCO_DLL) + #if defined(Net_EXPORTS) + #define Net_API __declspec(dllexport) + #else + #define Net_API __declspec(dllimport) + #endif +#endif + + +#if !defined(Net_API) + #define Net_API +#endif + + +#endif // Net_Net_INCLUDED diff --git a/Net/include/Poco/Net/NetException.h b/Net/include/Poco/Net/NetException.h index ff8df3645..c6849f126 100644 --- a/Net/include/Poco/Net/NetException.h +++ b/Net/include/Poco/Net/NetException.h @@ -1,75 +1,75 @@ -// -// NetException.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/NetException.h#1 $ -// -// Library: Net -// Package: NetCore -// Module: NetException -// -// Definition of the NetException 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_NetException_INCLUDED -#define Net_NetException_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Exception.h" - - -namespace Poco { -namespace Net { - - -POCO_DECLARE_EXCEPTION(Net_API, NetException, Poco::IOException) -POCO_DECLARE_EXCEPTION(Net_API, InvalidAddressException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, ServiceNotFoundException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, ConnectionAbortedException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, ConnectionResetException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, ConnectionRefusedException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, DNSException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, HostNotFoundException, DNSException) -POCO_DECLARE_EXCEPTION(Net_API, NoAddressFoundException, DNSException) -POCO_DECLARE_EXCEPTION(Net_API, InterfaceNotFoundException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, MessageException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, MultipartException, MessageException) -POCO_DECLARE_EXCEPTION(Net_API, HTTPException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, NotAuthenticatedException, HTTPException) -POCO_DECLARE_EXCEPTION(Net_API, UnsupportedRedirectException, HTTPException) -POCO_DECLARE_EXCEPTION(Net_API, FTPException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, SMTPException, NetException) -POCO_DECLARE_EXCEPTION(Net_API, POP3Exception, NetException) -POCO_DECLARE_EXCEPTION(Net_API, ICMPException, NetException) - - -} } // namespace Poco::Net - - -#endif // Net_NetException_INCLUDED +// +// NetException.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/NetException.h#1 $ +// +// Library: Net +// Package: NetCore +// Module: NetException +// +// Definition of the NetException 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_NetException_INCLUDED +#define Net_NetException_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Exception.h" + + +namespace Poco { +namespace Net { + + +POCO_DECLARE_EXCEPTION(Net_API, NetException, Poco::IOException) +POCO_DECLARE_EXCEPTION(Net_API, InvalidAddressException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, ServiceNotFoundException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, ConnectionAbortedException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, ConnectionResetException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, ConnectionRefusedException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, DNSException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, HostNotFoundException, DNSException) +POCO_DECLARE_EXCEPTION(Net_API, NoAddressFoundException, DNSException) +POCO_DECLARE_EXCEPTION(Net_API, InterfaceNotFoundException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, MessageException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, MultipartException, MessageException) +POCO_DECLARE_EXCEPTION(Net_API, HTTPException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, NotAuthenticatedException, HTTPException) +POCO_DECLARE_EXCEPTION(Net_API, UnsupportedRedirectException, HTTPException) +POCO_DECLARE_EXCEPTION(Net_API, FTPException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, SMTPException, NetException) +POCO_DECLARE_EXCEPTION(Net_API, POP3Exception, NetException) +POCO_DECLARE_EXCEPTION(Net_API, ICMPException, NetException) + + +} } // namespace Poco::Net + + +#endif // Net_NetException_INCLUDED diff --git a/Net/include/Poco/Net/NetworkInterface.h b/Net/include/Poco/Net/NetworkInterface.h index 79085e136..ea3ec1d85 100644 --- a/Net/include/Poco/Net/NetworkInterface.h +++ b/Net/include/Poco/Net/NetworkInterface.h @@ -1,185 +1,185 @@ -// -// NetworkInterface.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/NetworkInterface.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: NetworkInterface -// -// Definition of the NetworkInterface 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_NetworkInterface_INCLUDED -#define Net_NetworkInterface_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/IPAddress.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API NetworkInterface - /// This class represents a network interface. - /// - /// NetworkInterface is used with MulticastSocket to specify - /// multicast interfaces for sending and receiving multicast - /// messages. -{ -public: - typedef std::vector NetworkInterfaceList; - - NetworkInterface(); - /// Creates a NetworkInterface representing the - /// default interface. - /// - /// The name is empty, the IP address is the wildcard - /// address and the index is zero. - - NetworkInterface(const NetworkInterface& interface); - /// Creates the NetworkInterface by copying another one. - - ~NetworkInterface(); - /// Destroys the NetworkInterface. - - NetworkInterface& operator = (const NetworkInterface& interface); - /// Assigns another NetworkInterface. - - int index() const; - /// Returns the interface index. - /// - /// Only supported if IPv6 is available. - /// Returns -1 if IPv6 is not available. - - const std::string& name() const; - /// Returns the interface name. - - const IPAddress& address() const; - /// Returns the IP address bound to the interface. - - bool supportsIPv4() const; - /// Returns true if the interface supports IPv4. - - bool supportsIPv6() const; - /// Returns true if the interface supports IPv6. - - static NetworkInterface forName(const std::string& name, bool requireIPv6 = false); - /// Returns the NetworkInterface for the given name. - /// - /// If requireIPv6 is false, an IPv4 interface is returned. - /// Otherwise, an IPv6 interface is returned. - /// - /// Throws an InterfaceNotFoundException if an interface - /// with the give name does not exist. - - static NetworkInterface forAddress(const IPAddress& address); - /// Returns the NetworkInterface for the given IP address. - /// - /// Throws an InterfaceNotFoundException if an interface - /// with the give address does not exist. - - static NetworkInterface forIndex(int index); - /// Returns the NetworkInterface for the given interface index. - /// If an index of 0 is specified, a NetworkInterface instance - /// representing the default interface (empty name and - /// wildcard address) is returned. - /// - /// Throws an InterfaceNotFoundException if an interface - /// with the given index does not exist (or IPv6 is not - /// available). - - static NetworkInterfaceList list(); - /// Returns a list with all network interfaces - /// on the system. - /// - /// If there are multiple addresses bound to one interface, - /// multiple NetworkInterface instances are created for - /// the same interface. - -protected: - NetworkInterface(const std::string& name, const IPAddress& address, int index = -1); - /// Creates the NetworkInterface. - - IPAddress interfaceNameToAddress(const std::string& interfaceName) const; - /// Determines the IPAddress bound to the interface with the given name. - - int interfaceNameToIndex(const std::string& interfaceName) const; - /// Determines the interface index of the interface with the given name. - -private: - std::string _name; - IPAddress _address; - int _index; - - static Poco::FastMutex _mutex; -}; - - -// -// inlines -// -inline int NetworkInterface::index() const -{ - return _index; -} - - -inline const std::string& NetworkInterface::name() const -{ - return _name; -} - - -inline const IPAddress& NetworkInterface::address() const -{ - return _address; -} - - -inline bool NetworkInterface::supportsIPv4() const -{ - return _index == -1; -} - - -inline bool NetworkInterface::supportsIPv6() const -{ - return _index != -1; -} - - -} } // namespace Poco::Net - - -#endif // Net_NetworkInterface_INCLUDED +// +// NetworkInterface.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/NetworkInterface.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: NetworkInterface +// +// Definition of the NetworkInterface 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_NetworkInterface_INCLUDED +#define Net_NetworkInterface_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/IPAddress.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API NetworkInterface + /// This class represents a network interface. + /// + /// NetworkInterface is used with MulticastSocket to specify + /// multicast interfaces for sending and receiving multicast + /// messages. +{ +public: + typedef std::vector NetworkInterfaceList; + + NetworkInterface(); + /// Creates a NetworkInterface representing the + /// default interface. + /// + /// The name is empty, the IP address is the wildcard + /// address and the index is zero. + + NetworkInterface(const NetworkInterface& interface); + /// Creates the NetworkInterface by copying another one. + + ~NetworkInterface(); + /// Destroys the NetworkInterface. + + NetworkInterface& operator = (const NetworkInterface& interface); + /// Assigns another NetworkInterface. + + int index() const; + /// Returns the interface index. + /// + /// Only supported if IPv6 is available. + /// Returns -1 if IPv6 is not available. + + const std::string& name() const; + /// Returns the interface name. + + const IPAddress& address() const; + /// Returns the IP address bound to the interface. + + bool supportsIPv4() const; + /// Returns true if the interface supports IPv4. + + bool supportsIPv6() const; + /// Returns true if the interface supports IPv6. + + static NetworkInterface forName(const std::string& name, bool requireIPv6 = false); + /// Returns the NetworkInterface for the given name. + /// + /// If requireIPv6 is false, an IPv4 interface is returned. + /// Otherwise, an IPv6 interface is returned. + /// + /// Throws an InterfaceNotFoundException if an interface + /// with the give name does not exist. + + static NetworkInterface forAddress(const IPAddress& address); + /// Returns the NetworkInterface for the given IP address. + /// + /// Throws an InterfaceNotFoundException if an interface + /// with the give address does not exist. + + static NetworkInterface forIndex(int index); + /// Returns the NetworkInterface for the given interface index. + /// If an index of 0 is specified, a NetworkInterface instance + /// representing the default interface (empty name and + /// wildcard address) is returned. + /// + /// Throws an InterfaceNotFoundException if an interface + /// with the given index does not exist (or IPv6 is not + /// available). + + static NetworkInterfaceList list(); + /// Returns a list with all network interfaces + /// on the system. + /// + /// If there are multiple addresses bound to one interface, + /// multiple NetworkInterface instances are created for + /// the same interface. + +protected: + NetworkInterface(const std::string& name, const IPAddress& address, int index = -1); + /// Creates the NetworkInterface. + + IPAddress interfaceNameToAddress(const std::string& interfaceName) const; + /// Determines the IPAddress bound to the interface with the given name. + + int interfaceNameToIndex(const std::string& interfaceName) const; + /// Determines the interface index of the interface with the given name. + +private: + std::string _name; + IPAddress _address; + int _index; + + static Poco::FastMutex _mutex; +}; + + +// +// inlines +// +inline int NetworkInterface::index() const +{ + return _index; +} + + +inline const std::string& NetworkInterface::name() const +{ + return _name; +} + + +inline const IPAddress& NetworkInterface::address() const +{ + return _address; +} + + +inline bool NetworkInterface::supportsIPv4() const +{ + return _index == -1; +} + + +inline bool NetworkInterface::supportsIPv6() const +{ + return _index != -1; +} + + +} } // namespace Poco::Net + + +#endif // Net_NetworkInterface_INCLUDED diff --git a/Net/include/Poco/Net/NullPartHandler.h b/Net/include/Poco/Net/NullPartHandler.h index b5823ab45..f62c35db8 100644 --- a/Net/include/Poco/Net/NullPartHandler.h +++ b/Net/include/Poco/Net/NullPartHandler.h @@ -1,69 +1,69 @@ -// -// NullPartHandler.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/NullPartHandler.h#1 $ -// -// Library: Net -// Package: Messages -// Module: NullPartHandler -// -// Definition of the NullPartHandler 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_NullPartHandler_INCLUDED -#define Net_NullPartHandler_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/PartHandler.h" - - -namespace Poco { -namespace Net { - - -class Net_API NullPartHandler: public PartHandler - /// A very special PartHandler that simply discards all data. -{ -public: - NullPartHandler(); - /// Creates the NullPartHandler. - - ~NullPartHandler(); - /// Destroys the NullPartHandler. - - void handlePart(const MessageHeader& header, std::istream& stream); - /// Reads and discards all data from the stream. -}; - - -} } // namespace Poco::Net - - -#endif // Net_NullPartHandler_INCLUDED +// +// NullPartHandler.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/NullPartHandler.h#1 $ +// +// Library: Net +// Package: Messages +// Module: NullPartHandler +// +// Definition of the NullPartHandler 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_NullPartHandler_INCLUDED +#define Net_NullPartHandler_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/PartHandler.h" + + +namespace Poco { +namespace Net { + + +class Net_API NullPartHandler: public PartHandler + /// A very special PartHandler that simply discards all data. +{ +public: + NullPartHandler(); + /// Creates the NullPartHandler. + + ~NullPartHandler(); + /// Destroys the NullPartHandler. + + void handlePart(const MessageHeader& header, std::istream& stream); + /// Reads and discards all data from the stream. +}; + + +} } // namespace Poco::Net + + +#endif // Net_NullPartHandler_INCLUDED diff --git a/Net/include/Poco/Net/POP3ClientSession.h b/Net/include/Poco/Net/POP3ClientSession.h index 3750add4f..cfc7b6ace 100644 --- a/Net/include/Poco/Net/POP3ClientSession.h +++ b/Net/include/Poco/Net/POP3ClientSession.h @@ -1,207 +1,207 @@ -// -// POP3ClientSession.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/POP3ClientSession.h#1 $ -// -// Library: Net -// Package: Mail -// Module: POP3ClientSession -// -// Definition of the POP3ClientSession 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_POP3ClientSession_INCLUDED -#define Net_POP3ClientSession_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/DialogSocket.h" -#include "Poco/Timespan.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class MessageHeader; -class MailMessage; -class PartHandler; - - -class Net_API POP3ClientSession - /// This class implements an Post Office Protocol - /// Version 3 (POP3, RFC 1939) - /// client for receiving e-mail messages. -{ -public: - enum - { - POP3_PORT = 110 - }; - - struct MessageInfo - /// Information returned by listMessages(). - { - int id; - int size; - }; - - typedef std::vector MessageInfoVec; - - POP3ClientSession(const StreamSocket& socket); - /// Creates the POP3ClientSession using - /// the given socket, which must be connected - /// to a POP3 server. - - POP3ClientSession(const std::string& host, Poco::UInt16 port = POP3_PORT); - /// Creates the POP3ClientSession using a socket connected - /// to the given host and port. - - virtual ~POP3ClientSession(); - /// Destroys the SMTPClientSession. - - void setTimeout(const Poco::Timespan& timeout); - /// Sets the timeout for socket read operations. - - Poco::Timespan getTimeout() const; - /// Returns the timeout for socket read operations. - - void login(const std::string& username, const std::string& password); - /// Logs in to the POP3 server by sending a USER command - /// followed by a PASS command. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - void close(); - /// Sends a QUIT command and closes the connection to the server. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - int messageCount(); - /// Sends a STAT command to determine the number of messages - /// available on the server and returns that number. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - void listMessages(MessageInfoVec& messages); - /// Fills the given vector with the ids and sizes of all - /// messages available on the server. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - void retrieveMessage(int id, MailMessage& message); - /// Retrieves the message with the given id from the server and - /// stores the raw message content in the message's - /// content string, available with message.getContent(). - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - void retrieveMessage(int id, MailMessage& message, PartHandler& handler); - /// Retrieves the message with the given id from the server and - /// stores it in message. - /// - /// If the message has multiple parts, the parts - /// are reported to the PartHandler. If the message - /// is not a multi-part message, the content is stored - /// in a string available by calling message.getContent(). - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - void retrieveMessage(int id, std::ostream& ostr); - /// Retrieves the raw message with the given id from the - /// server and copies it to the given output stream. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - void retrieveHeader(int id, MessageHeader& header); - /// Retrieves the message header of the message with the - /// given id and stores it in header. - /// - /// For this to work, the server must support the TOP command. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - void deleteMessage(int id); - /// Marks the message with the given ID for deletion. The message - /// will be deleted when the connection to the server is - /// closed by calling close(). - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - bool sendCommand(const std::string& command, std::string& response); - /// Sends the given command verbatim to the server - /// and waits for a response. - /// - /// Returns true if the response is positive, false otherwise. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - bool sendCommand(const std::string& command, const std::string& arg, std::string& response); - /// Sends the given command verbatim to the server - /// and waits for a response. - /// - /// Returns true if the response is positive, false otherwise. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - - bool sendCommand(const std::string& command, const std::string& arg1, const std::string& arg2, std::string& response); - /// Sends the given command verbatim to the server - /// and waits for a response. - /// - /// Returns true if the response is positive, false otherwise. - /// - /// Throws a POP3Exception in case of a POP3-specific error, or a - /// NetException in case of a general network communication failure. - -protected: - static bool isPositive(const std::string& response); - -private: - DialogSocket _socket; - bool _isOpen; -}; - - -} } // namespace Poco::Net - - -#endif // Net_POP3ClientSession_INCLUDED +// +// POP3ClientSession.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/POP3ClientSession.h#1 $ +// +// Library: Net +// Package: Mail +// Module: POP3ClientSession +// +// Definition of the POP3ClientSession 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_POP3ClientSession_INCLUDED +#define Net_POP3ClientSession_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/DialogSocket.h" +#include "Poco/Timespan.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class MessageHeader; +class MailMessage; +class PartHandler; + + +class Net_API POP3ClientSession + /// This class implements an Post Office Protocol + /// Version 3 (POP3, RFC 1939) + /// client for receiving e-mail messages. +{ +public: + enum + { + POP3_PORT = 110 + }; + + struct MessageInfo + /// Information returned by listMessages(). + { + int id; + int size; + }; + + typedef std::vector MessageInfoVec; + + POP3ClientSession(const StreamSocket& socket); + /// Creates the POP3ClientSession using + /// the given socket, which must be connected + /// to a POP3 server. + + POP3ClientSession(const std::string& host, Poco::UInt16 port = POP3_PORT); + /// Creates the POP3ClientSession using a socket connected + /// to the given host and port. + + virtual ~POP3ClientSession(); + /// Destroys the SMTPClientSession. + + void setTimeout(const Poco::Timespan& timeout); + /// Sets the timeout for socket read operations. + + Poco::Timespan getTimeout() const; + /// Returns the timeout for socket read operations. + + void login(const std::string& username, const std::string& password); + /// Logs in to the POP3 server by sending a USER command + /// followed by a PASS command. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + void close(); + /// Sends a QUIT command and closes the connection to the server. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + int messageCount(); + /// Sends a STAT command to determine the number of messages + /// available on the server and returns that number. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + void listMessages(MessageInfoVec& messages); + /// Fills the given vector with the ids and sizes of all + /// messages available on the server. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + void retrieveMessage(int id, MailMessage& message); + /// Retrieves the message with the given id from the server and + /// stores the raw message content in the message's + /// content string, available with message.getContent(). + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + void retrieveMessage(int id, MailMessage& message, PartHandler& handler); + /// Retrieves the message with the given id from the server and + /// stores it in message. + /// + /// If the message has multiple parts, the parts + /// are reported to the PartHandler. If the message + /// is not a multi-part message, the content is stored + /// in a string available by calling message.getContent(). + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + void retrieveMessage(int id, std::ostream& ostr); + /// Retrieves the raw message with the given id from the + /// server and copies it to the given output stream. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + void retrieveHeader(int id, MessageHeader& header); + /// Retrieves the message header of the message with the + /// given id and stores it in header. + /// + /// For this to work, the server must support the TOP command. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + void deleteMessage(int id); + /// Marks the message with the given ID for deletion. The message + /// will be deleted when the connection to the server is + /// closed by calling close(). + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + bool sendCommand(const std::string& command, std::string& response); + /// Sends the given command verbatim to the server + /// and waits for a response. + /// + /// Returns true if the response is positive, false otherwise. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + bool sendCommand(const std::string& command, const std::string& arg, std::string& response); + /// Sends the given command verbatim to the server + /// and waits for a response. + /// + /// Returns true if the response is positive, false otherwise. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + + bool sendCommand(const std::string& command, const std::string& arg1, const std::string& arg2, std::string& response); + /// Sends the given command verbatim to the server + /// and waits for a response. + /// + /// Returns true if the response is positive, false otherwise. + /// + /// Throws a POP3Exception in case of a POP3-specific error, or a + /// NetException in case of a general network communication failure. + +protected: + static bool isPositive(const std::string& response); + +private: + DialogSocket _socket; + bool _isOpen; +}; + + +} } // namespace Poco::Net + + +#endif // Net_POP3ClientSession_INCLUDED diff --git a/Net/include/Poco/Net/PartHandler.h b/Net/include/Poco/Net/PartHandler.h index 518a1db79..b85f817a9 100644 --- a/Net/include/Poco/Net/PartHandler.h +++ b/Net/include/Poco/Net/PartHandler.h @@ -1,90 +1,90 @@ -// -// PartHandler.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/PartHandler.h#1 $ -// -// Library: Net -// Package: Messages -// Module: PartHandler -// -// Definition of the PartHandler 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_PartHandler_INCLUDED -#define Net_PartHandler_INCLUDED - - -#include "Poco/Net/Net.h" -#include - - -namespace Poco { -namespace Net { - - -class MessageHeader; - - -class Net_API PartHandler - /// The base class for all part or attachment handlers. - /// - /// Part handlers are used for handling email parts and - /// attachments in MIME multipart messages, as well as file - /// uploads via HTML forms. - /// - /// Subclasses must override handlePart(). -{ -public: - virtual void handlePart(const MessageHeader& header, std::istream& stream) = 0; - /// Called for every part encountered during the processing - /// of an email message or an uploaded HTML form. - /// - /// Information about the part can be extracted from - /// the given message header. What information can be obtained - /// from header depends on the kind of part. - /// - /// The content of the part can be read from stream. - -protected: - PartHandler(); - /// Creates the PartHandler. - - virtual ~PartHandler(); - /// Destroys the PartHandler. - -private: - PartHandler(const PartHandler&); - PartHandler& operator = (const PartHandler&); -}; - - -} } // namespace Poco::Net - - -#endif // Net_PartHandler_INCLUDED +// +// PartHandler.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/PartHandler.h#1 $ +// +// Library: Net +// Package: Messages +// Module: PartHandler +// +// Definition of the PartHandler 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_PartHandler_INCLUDED +#define Net_PartHandler_INCLUDED + + +#include "Poco/Net/Net.h" +#include + + +namespace Poco { +namespace Net { + + +class MessageHeader; + + +class Net_API PartHandler + /// The base class for all part or attachment handlers. + /// + /// Part handlers are used for handling email parts and + /// attachments in MIME multipart messages, as well as file + /// uploads via HTML forms. + /// + /// Subclasses must override handlePart(). +{ +public: + virtual void handlePart(const MessageHeader& header, std::istream& stream) = 0; + /// Called for every part encountered during the processing + /// of an email message or an uploaded HTML form. + /// + /// Information about the part can be extracted from + /// the given message header. What information can be obtained + /// from header depends on the kind of part. + /// + /// The content of the part can be read from stream. + +protected: + PartHandler(); + /// Creates the PartHandler. + + virtual ~PartHandler(); + /// Destroys the PartHandler. + +private: + PartHandler(const PartHandler&); + PartHandler& operator = (const PartHandler&); +}; + + +} } // namespace Poco::Net + + +#endif // Net_PartHandler_INCLUDED diff --git a/Net/include/Poco/Net/PartSource.h b/Net/include/Poco/Net/PartSource.h index 367364a8f..815892928 100644 --- a/Net/include/Poco/Net/PartSource.h +++ b/Net/include/Poco/Net/PartSource.h @@ -1,103 +1,103 @@ -// -// PartSource.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/PartSource.h#1 $ -// -// Library: Net -// Package: Messages -// Module: PartSource -// -// Definition of the PartSource 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_PartSource_INCLUDED -#define Net_PartSource_INCLUDED - - -#include "Poco/Net/Net.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API PartSource - /// This abstract class is used for adding parts or attachments - /// to mail messages, as well as for uploading files as part of a HTML form. -{ -public: - virtual std::istream& stream() = 0; - /// Returns an input stream for reading the - /// part data. - /// - /// Subclasses must override this method. - - virtual const std::string& filename(); - /// Returns the filename for the part or attachment. - /// - /// May be overridded by subclasses. The default - /// implementation returns an empty string. - - const std::string& mediaType() const; - /// Returns the MIME media type for this part or attachment. - - virtual ~PartSource(); - /// Destroys the PartSource. - -protected: - PartSource(); - /// Creates the PartSource, using - /// the application/octet-stream MIME type. - - PartSource(const std::string& mediaType); - /// Creates the PartSource, using the - /// given MIME type. - -private: - PartSource(const PartSource&); - PartSource& operator = (const PartSource&); - - std::string _mediaType; -}; - - -// -// inlines -// -inline const std::string& PartSource::mediaType() const -{ - return _mediaType; -} - - -} } // namespace Poco::Net - - -#endif // Net_PartSource_INCLUDED +// +// PartSource.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/PartSource.h#1 $ +// +// Library: Net +// Package: Messages +// Module: PartSource +// +// Definition of the PartSource 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_PartSource_INCLUDED +#define Net_PartSource_INCLUDED + + +#include "Poco/Net/Net.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API PartSource + /// This abstract class is used for adding parts or attachments + /// to mail messages, as well as for uploading files as part of a HTML form. +{ +public: + virtual std::istream& stream() = 0; + /// Returns an input stream for reading the + /// part data. + /// + /// Subclasses must override this method. + + virtual const std::string& filename(); + /// Returns the filename for the part or attachment. + /// + /// May be overridded by subclasses. The default + /// implementation returns an empty string. + + const std::string& mediaType() const; + /// Returns the MIME media type for this part or attachment. + + virtual ~PartSource(); + /// Destroys the PartSource. + +protected: + PartSource(); + /// Creates the PartSource, using + /// the application/octet-stream MIME type. + + PartSource(const std::string& mediaType); + /// Creates the PartSource, using the + /// given MIME type. + +private: + PartSource(const PartSource&); + PartSource& operator = (const PartSource&); + + std::string _mediaType; +}; + + +// +// inlines +// +inline const std::string& PartSource::mediaType() const +{ + return _mediaType; +} + + +} } // namespace Poco::Net + + +#endif // Net_PartSource_INCLUDED diff --git a/Net/include/Poco/Net/QuotedPrintableDecoder.h b/Net/include/Poco/Net/QuotedPrintableDecoder.h index ab0500f7a..35b753a47 100644 --- a/Net/include/Poco/Net/QuotedPrintableDecoder.h +++ b/Net/include/Poco/Net/QuotedPrintableDecoder.h @@ -1,96 +1,96 @@ -// -// QuotedPrintableDecoder.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/QuotedPrintableDecoder.h#1 $ -// -// Library: Net -// Package: Messages -// Module: QuotedPrintableDecoder -// -// Definition of the QuotedPrintableDecoder 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_QuotedPrintableDecoder_INCLUDED -#define Net_QuotedPrintableDecoder_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/UnbufferedStreamBuf.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API QuotedPrintableDecoderBuf: public Poco::UnbufferedStreamBuf - /// This streambuf decodes all quoted-printable (see RFC 2045) - /// encoded data read from the istream connected to it. -{ -public: - QuotedPrintableDecoderBuf(std::istream& istr); - ~QuotedPrintableDecoderBuf(); - -private: - int readFromDevice(); - - std::istream& _istr; -}; - - -class Net_API QuotedPrintableDecoderIOS: public virtual std::ios - /// The base class for QuotedPrintableDecoder. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - QuotedPrintableDecoderIOS(std::istream& istr); - ~QuotedPrintableDecoderIOS(); - QuotedPrintableDecoderBuf* rdbuf(); - -protected: - QuotedPrintableDecoderBuf _buf; -}; - - -class Net_API QuotedPrintableDecoder: public QuotedPrintableDecoderIOS, public std::istream - /// This istream decodes all quoted-printable (see RFC 2045) - /// encoded data read from the istream connected to it. -{ -public: - QuotedPrintableDecoder(std::istream& istr); - ~QuotedPrintableDecoder(); -}; - - -} } // namespace Poco::Net - - -#endif // Net_QuotedPrintableDecoder_INCLUDED +// +// QuotedPrintableDecoder.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/QuotedPrintableDecoder.h#1 $ +// +// Library: Net +// Package: Messages +// Module: QuotedPrintableDecoder +// +// Definition of the QuotedPrintableDecoder 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_QuotedPrintableDecoder_INCLUDED +#define Net_QuotedPrintableDecoder_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/UnbufferedStreamBuf.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API QuotedPrintableDecoderBuf: public Poco::UnbufferedStreamBuf + /// This streambuf decodes all quoted-printable (see RFC 2045) + /// encoded data read from the istream connected to it. +{ +public: + QuotedPrintableDecoderBuf(std::istream& istr); + ~QuotedPrintableDecoderBuf(); + +private: + int readFromDevice(); + + std::istream& _istr; +}; + + +class Net_API QuotedPrintableDecoderIOS: public virtual std::ios + /// The base class for QuotedPrintableDecoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + QuotedPrintableDecoderIOS(std::istream& istr); + ~QuotedPrintableDecoderIOS(); + QuotedPrintableDecoderBuf* rdbuf(); + +protected: + QuotedPrintableDecoderBuf _buf; +}; + + +class Net_API QuotedPrintableDecoder: public QuotedPrintableDecoderIOS, public std::istream + /// This istream decodes all quoted-printable (see RFC 2045) + /// encoded data read from the istream connected to it. +{ +public: + QuotedPrintableDecoder(std::istream& istr); + ~QuotedPrintableDecoder(); +}; + + +} } // namespace Poco::Net + + +#endif // Net_QuotedPrintableDecoder_INCLUDED diff --git a/Net/include/Poco/Net/QuotedPrintableEncoder.h b/Net/include/Poco/Net/QuotedPrintableEncoder.h index b471b723b..e9265f30a 100644 --- a/Net/include/Poco/Net/QuotedPrintableEncoder.h +++ b/Net/include/Poco/Net/QuotedPrintableEncoder.h @@ -1,107 +1,107 @@ -// -// QuotedPrintableEncoder.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/QuotedPrintableEncoder.h#1 $ -// -// Library: Net -// Package: Messages -// Module: QuotedPrintableEncoder -// -// Definition of the QuotedPrintableEncoder 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_QuotedPrintableEncoder_INCLUDED -#define Net_QuotedPrintableEncoder_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/UnbufferedStreamBuf.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API QuotedPrintableEncoderBuf: public Poco::UnbufferedStreamBuf - /// This streambuf encodes all data written - /// to it in quoted-printable encoding (see RFC 2045) - /// and forwards it to a connected ostream. -{ -public: - QuotedPrintableEncoderBuf(std::ostream& ostr); - ~QuotedPrintableEncoderBuf(); - int close(); - -private: - int writeToDevice(char c); - void writeEncoded(char c); - void writeRaw(char c); - - int _pending; - int _lineLength; - std::ostream& _ostr; -}; - - -class Net_API QuotedPrintableEncoderIOS: public virtual std::ios - /// The base class for QuotedPrintableEncoder. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - QuotedPrintableEncoderIOS(std::ostream& ostr); - ~QuotedPrintableEncoderIOS(); - int close(); - QuotedPrintableEncoderBuf* rdbuf(); - -protected: - QuotedPrintableEncoderBuf _buf; -}; - - -class Net_API QuotedPrintableEncoder: public QuotedPrintableEncoderIOS, public std::ostream - /// This ostream encodes all data - /// written to it in quoted-printable encoding - /// (see RFC 2045) and forwards it to a connected ostream. - /// Always call close() when done - /// writing data, to ensure proper - /// completion of the encoding operation. -{ -public: - QuotedPrintableEncoder(std::ostream& ostr); - ~QuotedPrintableEncoder(); -}; - - -} } // namespace Poco::Net - - -#endif // Net_QuotedPrintableEncoder_INCLUDED +// +// QuotedPrintableEncoder.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/QuotedPrintableEncoder.h#1 $ +// +// Library: Net +// Package: Messages +// Module: QuotedPrintableEncoder +// +// Definition of the QuotedPrintableEncoder 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_QuotedPrintableEncoder_INCLUDED +#define Net_QuotedPrintableEncoder_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/UnbufferedStreamBuf.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API QuotedPrintableEncoderBuf: public Poco::UnbufferedStreamBuf + /// This streambuf encodes all data written + /// to it in quoted-printable encoding (see RFC 2045) + /// and forwards it to a connected ostream. +{ +public: + QuotedPrintableEncoderBuf(std::ostream& ostr); + ~QuotedPrintableEncoderBuf(); + int close(); + +private: + int writeToDevice(char c); + void writeEncoded(char c); + void writeRaw(char c); + + int _pending; + int _lineLength; + std::ostream& _ostr; +}; + + +class Net_API QuotedPrintableEncoderIOS: public virtual std::ios + /// The base class for QuotedPrintableEncoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + QuotedPrintableEncoderIOS(std::ostream& ostr); + ~QuotedPrintableEncoderIOS(); + int close(); + QuotedPrintableEncoderBuf* rdbuf(); + +protected: + QuotedPrintableEncoderBuf _buf; +}; + + +class Net_API QuotedPrintableEncoder: public QuotedPrintableEncoderIOS, public std::ostream + /// This ostream encodes all data + /// written to it in quoted-printable encoding + /// (see RFC 2045) and forwards it to a connected ostream. + /// Always call close() when done + /// writing data, to ensure proper + /// completion of the encoding operation. +{ +public: + QuotedPrintableEncoder(std::ostream& ostr); + ~QuotedPrintableEncoder(); +}; + + +} } // namespace Poco::Net + + +#endif // Net_QuotedPrintableEncoder_INCLUDED diff --git a/Net/include/Poco/Net/RawSocket.h b/Net/include/Poco/Net/RawSocket.h index d7b7d7a91..a6c428c55 100644 --- a/Net/include/Poco/Net/RawSocket.h +++ b/Net/include/Poco/Net/RawSocket.h @@ -1,169 +1,169 @@ -// -// RawSocket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/RawSocket.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: RawSocket -// -// Definition of the RawSocket 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 Net_RawSocket_INCLUDED -#define Net_RawSocket_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/Socket.h" - - -namespace Poco { -namespace Net { - - -class Net_API RawSocket: public Socket - /// This class provides an interface to a - /// raw IP socket. -{ -public: - RawSocket(); - /// Creates an unconnected IPv4 raw socket. - - RawSocket(IPAddress::Family family, int proto = IPPROTO_RAW); - /// Creates an unconnected raw socket. - /// - /// The socket will be created for the - /// given address family. - - RawSocket(const SocketAddress& address, bool reuseAddress = false); - /// Creates a raw socket and binds it - /// to the given address. - /// - /// Depending on the address family, the socket - /// will be either an IPv4 or an IPv6 socket. - - RawSocket(const Socket& socket); - /// Creates the RawSocket with the SocketImpl - /// from another socket. The SocketImpl must be - /// a RawSocketImpl, otherwise an InvalidArgumentException - /// will be thrown. - - ~RawSocket(); - /// Destroys the RawSocket. - - RawSocket& operator = (const Socket& socket); - /// Assignment operator. - /// - /// Releases the socket's SocketImpl and - /// attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - void connect(const SocketAddress& address); - /// Restricts incoming and outgoing - /// packets to the specified address. - /// - /// Cannot be used together with bind(). - - void bind(const SocketAddress& address, bool reuseAddress = false); - /// Bind a local address to the socket. - /// - /// This is usually only done when establishing a server - /// socket. - /// - /// If reuseAddress is true, sets the SO_REUSEADDR - /// socket option. - /// - /// Cannot be used together with connect(). - - int sendBytes(const void* buffer, int length, int flags = 0); - /// Sends the contents of the given buffer through - /// the socket. - /// - /// Returns the number of bytes sent, which may be - /// less than the number of bytes specified. - - int receiveBytes(void* buffer, int length, int flags = 0); - /// Receives data from the socket and stores it - /// in buffer. Up to length bytes are received. - /// - /// Returns the number of bytes received. - - int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0); - /// Sends the contents of the given buffer through - /// the socket to the given address. - /// - /// Returns the number of bytes sent, which may be - /// less than the number of bytes specified. - - int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0); - /// Receives data from the socket and stores it - /// in buffer. Up to length bytes are received. - /// Stores the address of the sender in address. - /// - /// Returns the number of bytes received. - - void setBroadcast(bool flag); - /// Sets the value of the SO_BROADCAST socket option. - /// - /// Setting this flag allows sending datagrams to - /// the broadcast address. - - bool getBroadcast() const; - /// Returns the value of the SO_BROADCAST socket option. - -protected: - RawSocket(SocketImpl* pImpl); - /// Creates the Socket and attaches the given SocketImpl. - /// The socket takes owership of the SocketImpl. - /// - /// The SocketImpl must be a StreamSocketImpl, otherwise - /// an InvalidArgumentException will be thrown. -}; - - -// -// inlines -// -inline void RawSocket::setBroadcast(bool flag) -{ - impl()->setBroadcast(flag); -} - - -inline bool RawSocket::getBroadcast() const -{ - return impl()->getBroadcast(); -} - - -} } // namespace Poco::Net - - -#endif // Net_RawSocket_INCLUDED +// +// RawSocket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/RawSocket.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: RawSocket +// +// Definition of the RawSocket 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 Net_RawSocket_INCLUDED +#define Net_RawSocket_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/Socket.h" + + +namespace Poco { +namespace Net { + + +class Net_API RawSocket: public Socket + /// This class provides an interface to a + /// raw IP socket. +{ +public: + RawSocket(); + /// Creates an unconnected IPv4 raw socket. + + RawSocket(IPAddress::Family family, int proto = IPPROTO_RAW); + /// Creates an unconnected raw socket. + /// + /// The socket will be created for the + /// given address family. + + RawSocket(const SocketAddress& address, bool reuseAddress = false); + /// Creates a raw socket and binds it + /// to the given address. + /// + /// Depending on the address family, the socket + /// will be either an IPv4 or an IPv6 socket. + + RawSocket(const Socket& socket); + /// Creates the RawSocket with the SocketImpl + /// from another socket. The SocketImpl must be + /// a RawSocketImpl, otherwise an InvalidArgumentException + /// will be thrown. + + ~RawSocket(); + /// Destroys the RawSocket. + + RawSocket& operator = (const Socket& socket); + /// Assignment operator. + /// + /// Releases the socket's SocketImpl and + /// attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + void connect(const SocketAddress& address); + /// Restricts incoming and outgoing + /// packets to the specified address. + /// + /// Cannot be used together with bind(). + + void bind(const SocketAddress& address, bool reuseAddress = false); + /// Bind a local address to the socket. + /// + /// This is usually only done when establishing a server + /// socket. + /// + /// If reuseAddress is true, sets the SO_REUSEADDR + /// socket option. + /// + /// Cannot be used together with connect(). + + int sendBytes(const void* buffer, int length, int flags = 0); + /// Sends the contents of the given buffer through + /// the socket. + /// + /// Returns the number of bytes sent, which may be + /// less than the number of bytes specified. + + int receiveBytes(void* buffer, int length, int flags = 0); + /// Receives data from the socket and stores it + /// in buffer. Up to length bytes are received. + /// + /// Returns the number of bytes received. + + int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0); + /// Sends the contents of the given buffer through + /// the socket to the given address. + /// + /// Returns the number of bytes sent, which may be + /// less than the number of bytes specified. + + int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0); + /// Receives data from the socket and stores it + /// in buffer. Up to length bytes are received. + /// Stores the address of the sender in address. + /// + /// Returns the number of bytes received. + + void setBroadcast(bool flag); + /// Sets the value of the SO_BROADCAST socket option. + /// + /// Setting this flag allows sending datagrams to + /// the broadcast address. + + bool getBroadcast() const; + /// Returns the value of the SO_BROADCAST socket option. + +protected: + RawSocket(SocketImpl* pImpl); + /// Creates the Socket and attaches the given SocketImpl. + /// The socket takes owership of the SocketImpl. + /// + /// The SocketImpl must be a StreamSocketImpl, otherwise + /// an InvalidArgumentException will be thrown. +}; + + +// +// inlines +// +inline void RawSocket::setBroadcast(bool flag) +{ + impl()->setBroadcast(flag); +} + + +inline bool RawSocket::getBroadcast() const +{ + return impl()->getBroadcast(); +} + + +} } // namespace Poco::Net + + +#endif // Net_RawSocket_INCLUDED diff --git a/Net/include/Poco/Net/RawSocketImpl.h b/Net/include/Poco/Net/RawSocketImpl.h index 3854d5dd6..c0fa1baf1 100644 --- a/Net/include/Poco/Net/RawSocketImpl.h +++ b/Net/include/Poco/Net/RawSocketImpl.h @@ -1,78 +1,78 @@ -// -// RawSocketImpl.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/RawSocketImpl.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: RawSocketImpl -// -// Definition of the RawSocketImpl 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 Net_RawSocketImpl_INCLUDED -#define Net_RawSocketImpl_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketImpl.h" - - -namespace Poco { -namespace Net { - - -class Net_API RawSocketImpl: public SocketImpl - /// This class implements a raw socket. -{ -public: - RawSocketImpl(); - /// Creates an unconnected IPv4 raw socket with IPPROTO_RAW. - - RawSocketImpl(IPAddress::Family family, int proto = IPPROTO_RAW); - /// Creates an unconnected raw socket. - /// - /// The socket will be created for the - /// given address family. - - RawSocketImpl(poco_socket_t sockfd); - /// Creates a RawSocketImpl using the given native socket. - -protected: - void init(int af); - void init2(int af, int proto); - - ~RawSocketImpl(); -}; - - -} } // namespace Poco::Net - - -#endif // Net_RawSocketImpl_INCLUDED +// +// RawSocketImpl.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/RawSocketImpl.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: RawSocketImpl +// +// Definition of the RawSocketImpl 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 Net_RawSocketImpl_INCLUDED +#define Net_RawSocketImpl_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketImpl.h" + + +namespace Poco { +namespace Net { + + +class Net_API RawSocketImpl: public SocketImpl + /// This class implements a raw socket. +{ +public: + RawSocketImpl(); + /// Creates an unconnected IPv4 raw socket with IPPROTO_RAW. + + RawSocketImpl(IPAddress::Family family, int proto = IPPROTO_RAW); + /// Creates an unconnected raw socket. + /// + /// The socket will be created for the + /// given address family. + + RawSocketImpl(poco_socket_t sockfd); + /// Creates a RawSocketImpl using the given native socket. + +protected: + void init(int af); + void init2(int af, int proto); + + ~RawSocketImpl(); +}; + + +} } // namespace Poco::Net + + +#endif // Net_RawSocketImpl_INCLUDED diff --git a/Net/include/Poco/Net/SMTPClientSession.h b/Net/include/Poco/Net/SMTPClientSession.h index 04b662f14..4921301b0 100644 --- a/Net/include/Poco/Net/SMTPClientSession.h +++ b/Net/include/Poco/Net/SMTPClientSession.h @@ -1,179 +1,179 @@ -// -// SMTPClientSession.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SMTPClientSession.h#1 $ -// -// Library: Net -// Package: Mail -// Module: SMTPClientSession -// -// Definition of the SMTPClientSession 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_SMTPClientSession_INCLUDED -#define Net_SMTPClientSession_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/DialogSocket.h" -#include "Poco/Timespan.h" - - -namespace Poco { -namespace Net { - - -class MailMessage; - - -class Net_API SMTPClientSession - /// This class implements an Simple Mail - /// Transfer Procotol (SMTP, RFC 2821) - /// client for sending e-mail messages. -{ -public: - enum - { - SMTP_PORT = 25 - }; - - SMTPClientSession(const StreamSocket& socket); - /// Creates the SMTPClientSession using - /// the given socket, which must be connected - /// to a SMTP server. - - SMTPClientSession(const std::string& host, Poco::UInt16 port = SMTP_PORT); - /// Creates the SMTPClientSession using a socket connected - /// to the given host and port. - - virtual ~SMTPClientSession(); - /// Destroys the SMTPClientSession. - - void setTimeout(const Poco::Timespan& timeout); - /// Sets the timeout for socket read operations. - - Poco::Timespan getTimeout() const; - /// Returns the timeout for socket read operations. - - void login(const std::string& hostname); - /// Greets the SMTP server by sending a EHLO command - /// with the given hostname as argument. - /// - /// If the server does not understand the EHLO command, - /// a HELO command is sent instead. - /// - /// Throws a SMTPException in case of a SMTP-specific error, or a - /// NetException in case of a general network communication failure. - - void login(); - /// Calls login(hostname) with the current host name. - - void close(); - /// Sends a QUIT command and closes the connection to the server. - /// - /// Throws a SMTPException in case of a SMTP-specific error, or a - /// NetException in case of a general network communication failure. - - void sendMessage(const MailMessage& message); - /// Sends the given mail message by sending a MAIL FROM command, - /// a RCPT TO command for every recipient, and a DATA command with - /// the message headers and content. - /// - /// Throws a SMTPException in case of a SMTP-specific error, or a - /// NetException in case of a general network communication failure. - - int sendCommand(const std::string& command, std::string& response); - /// Sends the given command verbatim to the server - /// and waits for a response. - /// - /// Throws a SMTPException in case of a SMTP-specific error, or a - /// NetException in case of a general network communication failure. - - int sendCommand(const std::string& command, const std::string& arg, std::string& response); - /// Sends the given command verbatim to the server - /// and waits for a response. - /// - /// Throws a SMTPException in case of a SMTP-specific error, or a - /// NetException in case of a general network communication failure. - -protected: - enum StatusClass - { - SMTP_POSITIVE_COMPLETION = 2, - SMTP_POSITIVE_INTERMEDIATE = 3, - SMTP_TRANSIENT_NEGATIVE = 4, - SMTP_PERMANENT_NEGATIVE = 5 - }; - enum - { - DEFAULT_TIMEOUT = 30000000 // 30 seconds default timeout for socket operations - }; - - static bool isPositiveCompletion(int status); - static bool isPositiveIntermediate(int status); - static bool isTransientNegative(int status); - static bool isPermanentNegative(int status); - -private: - DialogSocket _socket; - bool _isOpen; -}; - - -// -// inlines -// -inline bool SMTPClientSession::isPositiveCompletion(int status) -{ - return status/100 == SMTP_POSITIVE_COMPLETION; -} - - -inline bool SMTPClientSession::isPositiveIntermediate(int status) -{ - return status/100 == SMTP_POSITIVE_INTERMEDIATE; -} - - -inline bool SMTPClientSession::isTransientNegative(int status) -{ - return status/100 == SMTP_TRANSIENT_NEGATIVE; -} - - -inline bool SMTPClientSession::isPermanentNegative(int status) -{ - return status/100 == SMTP_PERMANENT_NEGATIVE; -} - - -} } // namespace Poco::Net - - -#endif // Net_SMTPClientSession_INCLUDED +// +// SMTPClientSession.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SMTPClientSession.h#1 $ +// +// Library: Net +// Package: Mail +// Module: SMTPClientSession +// +// Definition of the SMTPClientSession 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_SMTPClientSession_INCLUDED +#define Net_SMTPClientSession_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/DialogSocket.h" +#include "Poco/Timespan.h" + + +namespace Poco { +namespace Net { + + +class MailMessage; + + +class Net_API SMTPClientSession + /// This class implements an Simple Mail + /// Transfer Procotol (SMTP, RFC 2821) + /// client for sending e-mail messages. +{ +public: + enum + { + SMTP_PORT = 25 + }; + + SMTPClientSession(const StreamSocket& socket); + /// Creates the SMTPClientSession using + /// the given socket, which must be connected + /// to a SMTP server. + + SMTPClientSession(const std::string& host, Poco::UInt16 port = SMTP_PORT); + /// Creates the SMTPClientSession using a socket connected + /// to the given host and port. + + virtual ~SMTPClientSession(); + /// Destroys the SMTPClientSession. + + void setTimeout(const Poco::Timespan& timeout); + /// Sets the timeout for socket read operations. + + Poco::Timespan getTimeout() const; + /// Returns the timeout for socket read operations. + + void login(const std::string& hostname); + /// Greets the SMTP server by sending a EHLO command + /// with the given hostname as argument. + /// + /// If the server does not understand the EHLO command, + /// a HELO command is sent instead. + /// + /// Throws a SMTPException in case of a SMTP-specific error, or a + /// NetException in case of a general network communication failure. + + void login(); + /// Calls login(hostname) with the current host name. + + void close(); + /// Sends a QUIT command and closes the connection to the server. + /// + /// Throws a SMTPException in case of a SMTP-specific error, or a + /// NetException in case of a general network communication failure. + + void sendMessage(const MailMessage& message); + /// Sends the given mail message by sending a MAIL FROM command, + /// a RCPT TO command for every recipient, and a DATA command with + /// the message headers and content. + /// + /// Throws a SMTPException in case of a SMTP-specific error, or a + /// NetException in case of a general network communication failure. + + int sendCommand(const std::string& command, std::string& response); + /// Sends the given command verbatim to the server + /// and waits for a response. + /// + /// Throws a SMTPException in case of a SMTP-specific error, or a + /// NetException in case of a general network communication failure. + + int sendCommand(const std::string& command, const std::string& arg, std::string& response); + /// Sends the given command verbatim to the server + /// and waits for a response. + /// + /// Throws a SMTPException in case of a SMTP-specific error, or a + /// NetException in case of a general network communication failure. + +protected: + enum StatusClass + { + SMTP_POSITIVE_COMPLETION = 2, + SMTP_POSITIVE_INTERMEDIATE = 3, + SMTP_TRANSIENT_NEGATIVE = 4, + SMTP_PERMANENT_NEGATIVE = 5 + }; + enum + { + DEFAULT_TIMEOUT = 30000000 // 30 seconds default timeout for socket operations + }; + + static bool isPositiveCompletion(int status); + static bool isPositiveIntermediate(int status); + static bool isTransientNegative(int status); + static bool isPermanentNegative(int status); + +private: + DialogSocket _socket; + bool _isOpen; +}; + + +// +// inlines +// +inline bool SMTPClientSession::isPositiveCompletion(int status) +{ + return status/100 == SMTP_POSITIVE_COMPLETION; +} + + +inline bool SMTPClientSession::isPositiveIntermediate(int status) +{ + return status/100 == SMTP_POSITIVE_INTERMEDIATE; +} + + +inline bool SMTPClientSession::isTransientNegative(int status) +{ + return status/100 == SMTP_TRANSIENT_NEGATIVE; +} + + +inline bool SMTPClientSession::isPermanentNegative(int status) +{ + return status/100 == SMTP_PERMANENT_NEGATIVE; +} + + +} } // namespace Poco::Net + + +#endif // Net_SMTPClientSession_INCLUDED diff --git a/Net/include/Poco/Net/ServerSocket.h b/Net/include/Poco/Net/ServerSocket.h index 4aff1059f..6d6df9456 100644 --- a/Net/include/Poco/Net/ServerSocket.h +++ b/Net/include/Poco/Net/ServerSocket.h @@ -1,156 +1,156 @@ -// -// ServerSocket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ServerSocket.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: ServerSocket -// -// Definition of the ServerSocket 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_ServerSocket_INCLUDED -#define Net_ServerSocket_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/Socket.h" -#include "Poco/Net/StreamSocket.h" - - -namespace Poco { -namespace Net { - - -class Net_API ServerSocket: public Socket - /// This class provides an interface to a - /// TCP server socket. -{ -public: - ServerSocket(); - /// Creates a server socket. - /// - /// The server socket must be bound to - /// and address and put into listening state. - - ServerSocket(const Socket& socket); - /// Creates the ServerSocket with the SocketImpl - /// from another socket. The SocketImpl must be - /// a ServerSocketImpl, otherwise an InvalidArgumentException - /// will be thrown. - - ServerSocket(const SocketAddress& address, int backlog = 64); - /// Creates a server socket, binds it - /// to the given address and puts it in listening - /// state. - /// - /// After successful construction, the server socket - /// is ready to accept connections. - - ServerSocket(Poco::UInt16 port, int backlog = 64); - /// Creates a server socket, binds it - /// to the given port and puts it in listening - /// state. - /// - /// After successful construction, the server socket - /// is ready to accept connections. - - virtual ~ServerSocket(); - /// Destroys the StreamSocket. - - ServerSocket& operator = (const Socket& socket); - /// Assignment operator. - /// - /// Releases the socket's SocketImpl and - /// attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - virtual void bind(const SocketAddress& address, bool reuseAddress = false); - /// Bind a local address to the socket. - /// - /// This is usually only done when establishing a server - /// socket. TCP clients should not bind a socket to a - /// specific address. - /// - /// If reuseAddress is true, sets the SO_REUSEADDR - /// socket option. - - virtual void bind(Poco::UInt16 port, bool reuseAddress = false); - /// Bind a local port to the socket. - /// - /// This is usually only done when establishing a server - /// socket. - /// - /// If reuseAddress is true, sets the SO_REUSEADDR - /// socket option. - - virtual void listen(int backlog = 64); - /// Puts the socket into listening state. - /// - /// The socket becomes a passive socket that - /// can accept incoming connection requests. - /// - /// The backlog argument specifies the maximum - /// number of connections that can be queued - /// for this socket. - - virtual StreamSocket acceptConnection(SocketAddress& clientAddr); - /// Get the next completed connection from the - /// socket's completed connection queue. - /// - /// If the queue is empty, waits until a connection - /// request completes. - /// - /// Returns a new TCP socket for the connection - /// with the client. - /// - /// The client socket's address is returned in clientAddr. - - virtual StreamSocket acceptConnection(); - /// Get the next completed connection from the - /// socket's completed connection queue. - /// - /// If the queue is empty, waits until a connection - /// request completes. - /// - /// Returns a new TCP socket for the connection - /// with the client. - -protected: - ServerSocket(SocketImpl* pImpl, bool); - /// The bool argument is to resolve an ambiguity with - /// another constructor (Microsoft Visual C++ 2005) -}; - - -} } // namespace Poco::Net - - -#endif // Net_ServerSocket_INCLUDED +// +// ServerSocket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ServerSocket.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: ServerSocket +// +// Definition of the ServerSocket 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_ServerSocket_INCLUDED +#define Net_ServerSocket_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/Socket.h" +#include "Poco/Net/StreamSocket.h" + + +namespace Poco { +namespace Net { + + +class Net_API ServerSocket: public Socket + /// This class provides an interface to a + /// TCP server socket. +{ +public: + ServerSocket(); + /// Creates a server socket. + /// + /// The server socket must be bound to + /// and address and put into listening state. + + ServerSocket(const Socket& socket); + /// Creates the ServerSocket with the SocketImpl + /// from another socket. The SocketImpl must be + /// a ServerSocketImpl, otherwise an InvalidArgumentException + /// will be thrown. + + ServerSocket(const SocketAddress& address, int backlog = 64); + /// Creates a server socket, binds it + /// to the given address and puts it in listening + /// state. + /// + /// After successful construction, the server socket + /// is ready to accept connections. + + ServerSocket(Poco::UInt16 port, int backlog = 64); + /// Creates a server socket, binds it + /// to the given port and puts it in listening + /// state. + /// + /// After successful construction, the server socket + /// is ready to accept connections. + + virtual ~ServerSocket(); + /// Destroys the StreamSocket. + + ServerSocket& operator = (const Socket& socket); + /// Assignment operator. + /// + /// Releases the socket's SocketImpl and + /// attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + virtual void bind(const SocketAddress& address, bool reuseAddress = false); + /// Bind a local address to the socket. + /// + /// This is usually only done when establishing a server + /// socket. TCP clients should not bind a socket to a + /// specific address. + /// + /// If reuseAddress is true, sets the SO_REUSEADDR + /// socket option. + + virtual void bind(Poco::UInt16 port, bool reuseAddress = false); + /// Bind a local port to the socket. + /// + /// This is usually only done when establishing a server + /// socket. + /// + /// If reuseAddress is true, sets the SO_REUSEADDR + /// socket option. + + virtual void listen(int backlog = 64); + /// Puts the socket into listening state. + /// + /// The socket becomes a passive socket that + /// can accept incoming connection requests. + /// + /// The backlog argument specifies the maximum + /// number of connections that can be queued + /// for this socket. + + virtual StreamSocket acceptConnection(SocketAddress& clientAddr); + /// Get the next completed connection from the + /// socket's completed connection queue. + /// + /// If the queue is empty, waits until a connection + /// request completes. + /// + /// Returns a new TCP socket for the connection + /// with the client. + /// + /// The client socket's address is returned in clientAddr. + + virtual StreamSocket acceptConnection(); + /// Get the next completed connection from the + /// socket's completed connection queue. + /// + /// If the queue is empty, waits until a connection + /// request completes. + /// + /// Returns a new TCP socket for the connection + /// with the client. + +protected: + ServerSocket(SocketImpl* pImpl, bool); + /// The bool argument is to resolve an ambiguity with + /// another constructor (Microsoft Visual C++ 2005) +}; + + +} } // namespace Poco::Net + + +#endif // Net_ServerSocket_INCLUDED diff --git a/Net/include/Poco/Net/ServerSocketImpl.h b/Net/include/Poco/Net/ServerSocketImpl.h index 4b23b08d3..7364edeb0 100644 --- a/Net/include/Poco/Net/ServerSocketImpl.h +++ b/Net/include/Poco/Net/ServerSocketImpl.h @@ -1,67 +1,67 @@ -// -// ServerSocketImpl.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/ServerSocketImpl.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: ServerSocketImpl -// -// Definition of the ServerSocketImpl 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_ServerSocketImpl_INCLUDED -#define Net_ServerSocketImpl_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketImpl.h" - - -namespace Poco { -namespace Net { - - -class Net_API ServerSocketImpl: public SocketImpl - /// This class implements a TCP server socket. -{ -public: - ServerSocketImpl(); - /// Creates the ServerSocketImpl. - -protected: - virtual ~ServerSocketImpl(); - /// Destroys the ServerSocketImpl. -}; - - -} } // namespace Poco::Net - - -#endif // Net_ServerSocketImpl_INCLUDED +// +// ServerSocketImpl.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/ServerSocketImpl.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: ServerSocketImpl +// +// Definition of the ServerSocketImpl 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_ServerSocketImpl_INCLUDED +#define Net_ServerSocketImpl_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketImpl.h" + + +namespace Poco { +namespace Net { + + +class Net_API ServerSocketImpl: public SocketImpl + /// This class implements a TCP server socket. +{ +public: + ServerSocketImpl(); + /// Creates the ServerSocketImpl. + +protected: + virtual ~ServerSocketImpl(); + /// Destroys the ServerSocketImpl. +}; + + +} } // namespace Poco::Net + + +#endif // Net_ServerSocketImpl_INCLUDED diff --git a/Net/include/Poco/Net/Socket.h b/Net/include/Poco/Net/Socket.h index 5763276a3..e0b825184 100644 --- a/Net/include/Poco/Net/Socket.h +++ b/Net/include/Poco/Net/Socket.h @@ -1,589 +1,589 @@ -// -// Socket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/Socket.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: Socket -// -// Definition of the Socket 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_Socket_INCLUDED -#define Net_Socket_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketImpl.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API Socket - /// Socket is the common base class for - /// StreamSocket, ServerSocket, DatagramSocket and other - /// socket classes. - /// - /// It provides operations common to all socket types. -{ -public: - enum SelectMode - /// The mode argument to poll() and select(). - { - SELECT_READ = 1, - SELECT_WRITE = 2, - SELECT_ERROR = 4 - }; - - typedef std::vector SocketList; - - Socket(); - /// Creates an uninitialized socket. - - Socket(const Socket& socket); - /// Copy constructor. - /// - /// Attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - Socket& operator = (const Socket& socket); - /// Assignment operator. - /// - /// Releases the socket's SocketImpl and - /// attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - virtual ~Socket(); - /// Destroys the Socket and releases the - /// SocketImpl. - - bool operator == (const Socket& socket) const; - /// Returns true if both sockets share the same - /// SocketImpl, false otherwise. - - bool operator != (const Socket& socket) const; - /// Returns false if both sockets share the same - /// SocketImpl, true otherwise. - - bool operator < (const Socket& socket) const; - /// Compares the SocketImpl pointers. - - bool operator <= (const Socket& socket) const; - /// Compares the SocketImpl pointers. - - bool operator > (const Socket& socket) const; - /// Compares the SocketImpl pointers. - - bool operator >= (const Socket& socket) const; - /// Compares the SocketImpl pointers. - - void close(); - /// Closes the socket. - - static int select(SocketList& readList, SocketList& writeList, SocketList& exceptList, const Poco::Timespan& timeout); - /// Determines the status of one or more sockets, - /// using a call to select(). - /// - /// ReadList contains the list of sockets which should be - /// checked for readability. - /// - /// WriteList contains the list of sockets which should be - /// checked for writeability. - /// - /// ExceptList contains a list of sockets which should be - /// checked for a pending error. - /// - /// Returns the number of sockets ready. - /// - /// After return, - /// * readList contains those sockets ready for reading, - /// * writeList contains those sockets ready for writing, - /// * exceptList contains those sockets with a pending error. - - bool poll(const Poco::Timespan& timeout, int mode) const; - /// Determines the status of the socket, using a - /// call to select(). - /// - /// The mode argument is constructed by combining the values - /// of the SelectMode enumeration. - /// - /// Returns true if the next operation corresponding to - /// mode will not block, false otherwise. - - int available() const; - /// Returns the number of bytes available that can be read - /// without causing the socket to block. - - void setSendBufferSize(int size); - /// Sets the size of the send buffer. - - int getSendBufferSize() const; - /// Returns the size of the send buffer. - /// - /// The returned value may be different than the - /// value previously set with setSendBufferSize(), - /// as the system is free to adjust the value. - - void setReceiveBufferSize(int size); - /// Sets the size of the receive buffer. - - int getReceiveBufferSize() const; - /// Returns the size of the receive buffer. - /// - /// The returned value may be different than the - /// value previously set with setReceiveBufferSize(), - /// as the system is free to adjust the value. - - void setSendTimeout(const Poco::Timespan& timeout); - /// Sets the send timeout for the socket. - - Poco::Timespan getSendTimeout() const; - /// Returns the send timeout for the socket. - /// - /// The returned timeout may be different than the - /// timeout previously set with setSendTimeout(), - /// as the system is free to adjust the value. - - void setReceiveTimeout(const Poco::Timespan& timeout); - /// Sets the send timeout for the socket. - /// - /// On systems that do not support SO_RCVTIMEO, a - /// workaround using poll() is provided. - - Poco::Timespan getReceiveTimeout() const; - /// Returns the receive timeout for the socket. - /// - /// The returned timeout may be different than the - /// timeout previously set with getReceiveTimeout(), - /// as the system is free to adjust the value. - - void setOption(int level, int option, int value); - /// Sets the socket option specified by level and option - /// to the given integer value. - - void setOption(int level, int option, unsigned value); - /// Sets the socket option specified by level and option - /// to the given integer value. - - void setOption(int level, int option, unsigned char value); - /// Sets the socket option specified by level and option - /// to the given integer value. - - void setOption(int level, int option, const Poco::Timespan& value); - /// Sets the socket option specified by level and option - /// to the given time value. - - void setOption(int level, int option, const IPAddress& value); - /// Sets the socket option specified by level and option - /// to the given time value. - - void getOption(int level, int option, int& value) const; - /// Returns the value of the socket option - /// specified by level and option. - - void getOption(int level, int option, unsigned& value) const; - /// Returns the value of the socket option - /// specified by level and option. - - void getOption(int level, int option, unsigned char& value) const; - /// Returns the value of the socket option - /// specified by level and option. - - void getOption(int level, int option, Poco::Timespan& value) const; - /// Returns the value of the socket option - /// specified by level and option. - - void getOption(int level, int option, IPAddress& value) const; - /// Returns the value of the socket option - /// specified by level and option. - - void setLinger(bool on, int seconds); - /// Sets the value of the SO_LINGER socket option. - - void getLinger(bool& on, int& seconds) const; - /// Returns the value of the SO_LINGER socket option. - - void setNoDelay(bool flag); - /// Sets the value of the TCP_NODELAY socket option. - - bool getNoDelay() const; - /// Returns the value of the TCP_NODELAY socket option. - - void setKeepAlive(bool flag); - /// Sets the value of the SO_KEEPALIVE socket option. - - bool getKeepAlive() const; - /// Returns the value of the SO_KEEPALIVE socket option. - - void setReuseAddress(bool flag); - /// Sets the value of the SO_REUSEADDR socket option. - - bool getReuseAddress() const; - /// Returns the value of the SO_REUSEADDR socket option. - - void setReusePort(bool flag); - /// Sets the value of the SO_REUSEPORT socket option. - /// Does nothing if the socket implementation does not - /// support SO_REUSEPORT. - - bool getReusePort() const; - /// Returns the value of the SO_REUSEPORT socket option. - /// - /// Returns false if the socket implementation does not - /// support SO_REUSEPORT. - - void setOOBInline(bool flag); - /// Sets the value of the SO_OOBINLINE socket option. - - bool getOOBInline() const; - /// Returns the value of the SO_OOBINLINE socket option. - - void setBlocking(bool flag); - /// Sets the socket in blocking mode if flag is true, - /// disables blocking mode if flag is false. - - SocketAddress address() const; - /// Returns the IP address and port number of the socket. - - SocketAddress peerAddress() const; - /// Returns the IP address and port number of the peer socket. - - SocketImpl* impl() const; - /// Returns the SocketImpl for this socket. - - static bool supportsIPv4(); - /// Returns true if the system supports IPv4. - - static bool supportsIPv6(); - /// Returns true if the system supports IPv6. - -protected: - Socket(SocketImpl* pImpl); - /// Creates the Socket and attaches the given SocketImpl. - /// The socket takes owership of the SocketImpl. - - poco_socket_t sockfd() const; - /// Returns the socket descriptor for this socket. - -private: - SocketImpl* _pImpl; -}; - - -// -// inlines -// -inline bool Socket::operator == (const Socket& socket) const -{ - return _pImpl == socket._pImpl; -} - - -inline bool Socket::operator != (const Socket& socket) const -{ - return _pImpl != socket._pImpl; -} - - -inline bool Socket::operator < (const Socket& socket) const -{ - return _pImpl < socket._pImpl; -} - - -inline bool Socket::operator <= (const Socket& socket) const -{ - return _pImpl <= socket._pImpl; -} - - -inline bool Socket::operator > (const Socket& socket) const -{ - return _pImpl > socket._pImpl; -} - - -inline bool Socket::operator >= (const Socket& socket) const -{ - return _pImpl >= socket._pImpl; -} - - -inline void Socket::close() -{ - _pImpl->close(); -} - - -inline bool Socket::poll(const Poco::Timespan& timeout, int mode) const -{ - return _pImpl->poll(timeout, mode); -} - - -inline int Socket::available() const -{ - return _pImpl->available(); -} - - -inline void Socket::setSendBufferSize(int size) -{ - _pImpl->setSendBufferSize(size); -} - - -inline int Socket::getSendBufferSize() const -{ - return _pImpl->getSendBufferSize(); -} - - -inline void Socket::setReceiveBufferSize(int size) -{ - _pImpl->setReceiveBufferSize(size); -} - - -inline int Socket::getReceiveBufferSize() const -{ - return _pImpl->getReceiveBufferSize(); -} - - -inline void Socket::setSendTimeout(const Poco::Timespan& timeout) -{ - _pImpl->setSendTimeout(timeout); -} - - -inline Poco::Timespan Socket::getSendTimeout() const -{ - return _pImpl->getSendTimeout(); -} - - -inline void Socket::setReceiveTimeout(const Poco::Timespan& timeout) -{ - _pImpl->setReceiveTimeout(timeout); -} - - -inline Poco::Timespan Socket::getReceiveTimeout() const -{ - return _pImpl->getReceiveTimeout(); -} - - -inline void Socket::setOption(int level, int option, int value) -{ - _pImpl->setOption(level, option, value); -} - - -inline void Socket::setOption(int level, int option, unsigned value) -{ - _pImpl->setOption(level, option, value); -} - - -inline void Socket::setOption(int level, int option, unsigned char value) -{ - _pImpl->setOption(level, option, value); -} - - -inline void Socket::setOption(int level, int option, const Poco::Timespan& value) -{ - _pImpl->setOption(level, option, value); -} - - -inline void Socket::setOption(int level, int option, const IPAddress& value) -{ - _pImpl->setOption(level, option, value); -} - - -inline void Socket::getOption(int level, int option, int& value) const -{ - _pImpl->getOption(level, option, value); -} - - -inline void Socket::getOption(int level, int option, unsigned& value) const -{ - _pImpl->getOption(level, option, value); -} - - -inline void Socket::getOption(int level, int option, unsigned char& value) const -{ - _pImpl->getOption(level, option, value); -} - - -inline void Socket::getOption(int level, int option, Poco::Timespan& value) const -{ - _pImpl->getOption(level, option, value); -} - - -inline void Socket::getOption(int level, int option, IPAddress& value) const -{ - _pImpl->getOption(level, option, value); -} - - -inline void Socket::setLinger(bool on, int seconds) -{ - _pImpl->setLinger(on, seconds); -} - - -inline void Socket::getLinger(bool& on, int& seconds) const -{ - _pImpl->getLinger(on, seconds); -} - - -inline void Socket::setNoDelay(bool flag) -{ - _pImpl->setNoDelay(flag); -} - - -inline bool Socket::getNoDelay() const -{ - return _pImpl->getNoDelay(); -} - - -inline void Socket::setKeepAlive(bool flag) -{ - _pImpl->setKeepAlive(flag); -} - - -inline bool Socket::getKeepAlive() const -{ - return _pImpl->getKeepAlive(); -} - - -inline void Socket::setReuseAddress(bool flag) -{ - _pImpl->setReuseAddress(flag); -} - - -inline bool Socket::getReuseAddress() const -{ - return _pImpl->getReuseAddress(); -} - - -inline void Socket::setReusePort(bool flag) -{ - _pImpl->setReusePort(flag); -} - - -inline bool Socket::getReusePort() const -{ - return _pImpl->getReusePort(); -} - - -inline void Socket::setOOBInline(bool flag) -{ - _pImpl->setOOBInline(flag); -} - - -inline bool Socket::getOOBInline() const -{ - return _pImpl->getOOBInline(); -} - - -inline void Socket::setBlocking(bool flag) -{ - _pImpl->setBlocking(flag); -} - - -inline SocketImpl* Socket::impl() const -{ - return _pImpl; -} - - -inline poco_socket_t Socket::sockfd() const -{ - return _pImpl->sockfd(); -} - - -inline SocketAddress Socket::address() const -{ - return _pImpl->address(); -} - - -inline SocketAddress Socket::peerAddress() const -{ - return _pImpl->peerAddress(); -} - - -inline bool Socket::supportsIPv4() -{ - return true; -} - - -inline bool Socket::supportsIPv6() -{ -#if defined(POCO_HAVE_IPv6) - return true; -#else - return false; -#endif -} - - -} } // namespace Poco::Net - - -#endif // Net_Socket_INCLUDED +// +// Socket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/Socket.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: Socket +// +// Definition of the Socket 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_Socket_INCLUDED +#define Net_Socket_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketImpl.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API Socket + /// Socket is the common base class for + /// StreamSocket, ServerSocket, DatagramSocket and other + /// socket classes. + /// + /// It provides operations common to all socket types. +{ +public: + enum SelectMode + /// The mode argument to poll() and select(). + { + SELECT_READ = 1, + SELECT_WRITE = 2, + SELECT_ERROR = 4 + }; + + typedef std::vector SocketList; + + Socket(); + /// Creates an uninitialized socket. + + Socket(const Socket& socket); + /// Copy constructor. + /// + /// Attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + Socket& operator = (const Socket& socket); + /// Assignment operator. + /// + /// Releases the socket's SocketImpl and + /// attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + virtual ~Socket(); + /// Destroys the Socket and releases the + /// SocketImpl. + + bool operator == (const Socket& socket) const; + /// Returns true if both sockets share the same + /// SocketImpl, false otherwise. + + bool operator != (const Socket& socket) const; + /// Returns false if both sockets share the same + /// SocketImpl, true otherwise. + + bool operator < (const Socket& socket) const; + /// Compares the SocketImpl pointers. + + bool operator <= (const Socket& socket) const; + /// Compares the SocketImpl pointers. + + bool operator > (const Socket& socket) const; + /// Compares the SocketImpl pointers. + + bool operator >= (const Socket& socket) const; + /// Compares the SocketImpl pointers. + + void close(); + /// Closes the socket. + + static int select(SocketList& readList, SocketList& writeList, SocketList& exceptList, const Poco::Timespan& timeout); + /// Determines the status of one or more sockets, + /// using a call to select(). + /// + /// ReadList contains the list of sockets which should be + /// checked for readability. + /// + /// WriteList contains the list of sockets which should be + /// checked for writeability. + /// + /// ExceptList contains a list of sockets which should be + /// checked for a pending error. + /// + /// Returns the number of sockets ready. + /// + /// After return, + /// * readList contains those sockets ready for reading, + /// * writeList contains those sockets ready for writing, + /// * exceptList contains those sockets with a pending error. + + bool poll(const Poco::Timespan& timeout, int mode) const; + /// Determines the status of the socket, using a + /// call to select(). + /// + /// The mode argument is constructed by combining the values + /// of the SelectMode enumeration. + /// + /// Returns true if the next operation corresponding to + /// mode will not block, false otherwise. + + int available() const; + /// Returns the number of bytes available that can be read + /// without causing the socket to block. + + void setSendBufferSize(int size); + /// Sets the size of the send buffer. + + int getSendBufferSize() const; + /// Returns the size of the send buffer. + /// + /// The returned value may be different than the + /// value previously set with setSendBufferSize(), + /// as the system is free to adjust the value. + + void setReceiveBufferSize(int size); + /// Sets the size of the receive buffer. + + int getReceiveBufferSize() const; + /// Returns the size of the receive buffer. + /// + /// The returned value may be different than the + /// value previously set with setReceiveBufferSize(), + /// as the system is free to adjust the value. + + void setSendTimeout(const Poco::Timespan& timeout); + /// Sets the send timeout for the socket. + + Poco::Timespan getSendTimeout() const; + /// Returns the send timeout for the socket. + /// + /// The returned timeout may be different than the + /// timeout previously set with setSendTimeout(), + /// as the system is free to adjust the value. + + void setReceiveTimeout(const Poco::Timespan& timeout); + /// Sets the send timeout for the socket. + /// + /// On systems that do not support SO_RCVTIMEO, a + /// workaround using poll() is provided. + + Poco::Timespan getReceiveTimeout() const; + /// Returns the receive timeout for the socket. + /// + /// The returned timeout may be different than the + /// timeout previously set with getReceiveTimeout(), + /// as the system is free to adjust the value. + + void setOption(int level, int option, int value); + /// Sets the socket option specified by level and option + /// to the given integer value. + + void setOption(int level, int option, unsigned value); + /// Sets the socket option specified by level and option + /// to the given integer value. + + void setOption(int level, int option, unsigned char value); + /// Sets the socket option specified by level and option + /// to the given integer value. + + void setOption(int level, int option, const Poco::Timespan& value); + /// Sets the socket option specified by level and option + /// to the given time value. + + void setOption(int level, int option, const IPAddress& value); + /// Sets the socket option specified by level and option + /// to the given time value. + + void getOption(int level, int option, int& value) const; + /// Returns the value of the socket option + /// specified by level and option. + + void getOption(int level, int option, unsigned& value) const; + /// Returns the value of the socket option + /// specified by level and option. + + void getOption(int level, int option, unsigned char& value) const; + /// Returns the value of the socket option + /// specified by level and option. + + void getOption(int level, int option, Poco::Timespan& value) const; + /// Returns the value of the socket option + /// specified by level and option. + + void getOption(int level, int option, IPAddress& value) const; + /// Returns the value of the socket option + /// specified by level and option. + + void setLinger(bool on, int seconds); + /// Sets the value of the SO_LINGER socket option. + + void getLinger(bool& on, int& seconds) const; + /// Returns the value of the SO_LINGER socket option. + + void setNoDelay(bool flag); + /// Sets the value of the TCP_NODELAY socket option. + + bool getNoDelay() const; + /// Returns the value of the TCP_NODELAY socket option. + + void setKeepAlive(bool flag); + /// Sets the value of the SO_KEEPALIVE socket option. + + bool getKeepAlive() const; + /// Returns the value of the SO_KEEPALIVE socket option. + + void setReuseAddress(bool flag); + /// Sets the value of the SO_REUSEADDR socket option. + + bool getReuseAddress() const; + /// Returns the value of the SO_REUSEADDR socket option. + + void setReusePort(bool flag); + /// Sets the value of the SO_REUSEPORT socket option. + /// Does nothing if the socket implementation does not + /// support SO_REUSEPORT. + + bool getReusePort() const; + /// Returns the value of the SO_REUSEPORT socket option. + /// + /// Returns false if the socket implementation does not + /// support SO_REUSEPORT. + + void setOOBInline(bool flag); + /// Sets the value of the SO_OOBINLINE socket option. + + bool getOOBInline() const; + /// Returns the value of the SO_OOBINLINE socket option. + + void setBlocking(bool flag); + /// Sets the socket in blocking mode if flag is true, + /// disables blocking mode if flag is false. + + SocketAddress address() const; + /// Returns the IP address and port number of the socket. + + SocketAddress peerAddress() const; + /// Returns the IP address and port number of the peer socket. + + SocketImpl* impl() const; + /// Returns the SocketImpl for this socket. + + static bool supportsIPv4(); + /// Returns true if the system supports IPv4. + + static bool supportsIPv6(); + /// Returns true if the system supports IPv6. + +protected: + Socket(SocketImpl* pImpl); + /// Creates the Socket and attaches the given SocketImpl. + /// The socket takes owership of the SocketImpl. + + poco_socket_t sockfd() const; + /// Returns the socket descriptor for this socket. + +private: + SocketImpl* _pImpl; +}; + + +// +// inlines +// +inline bool Socket::operator == (const Socket& socket) const +{ + return _pImpl == socket._pImpl; +} + + +inline bool Socket::operator != (const Socket& socket) const +{ + return _pImpl != socket._pImpl; +} + + +inline bool Socket::operator < (const Socket& socket) const +{ + return _pImpl < socket._pImpl; +} + + +inline bool Socket::operator <= (const Socket& socket) const +{ + return _pImpl <= socket._pImpl; +} + + +inline bool Socket::operator > (const Socket& socket) const +{ + return _pImpl > socket._pImpl; +} + + +inline bool Socket::operator >= (const Socket& socket) const +{ + return _pImpl >= socket._pImpl; +} + + +inline void Socket::close() +{ + _pImpl->close(); +} + + +inline bool Socket::poll(const Poco::Timespan& timeout, int mode) const +{ + return _pImpl->poll(timeout, mode); +} + + +inline int Socket::available() const +{ + return _pImpl->available(); +} + + +inline void Socket::setSendBufferSize(int size) +{ + _pImpl->setSendBufferSize(size); +} + + +inline int Socket::getSendBufferSize() const +{ + return _pImpl->getSendBufferSize(); +} + + +inline void Socket::setReceiveBufferSize(int size) +{ + _pImpl->setReceiveBufferSize(size); +} + + +inline int Socket::getReceiveBufferSize() const +{ + return _pImpl->getReceiveBufferSize(); +} + + +inline void Socket::setSendTimeout(const Poco::Timespan& timeout) +{ + _pImpl->setSendTimeout(timeout); +} + + +inline Poco::Timespan Socket::getSendTimeout() const +{ + return _pImpl->getSendTimeout(); +} + + +inline void Socket::setReceiveTimeout(const Poco::Timespan& timeout) +{ + _pImpl->setReceiveTimeout(timeout); +} + + +inline Poco::Timespan Socket::getReceiveTimeout() const +{ + return _pImpl->getReceiveTimeout(); +} + + +inline void Socket::setOption(int level, int option, int value) +{ + _pImpl->setOption(level, option, value); +} + + +inline void Socket::setOption(int level, int option, unsigned value) +{ + _pImpl->setOption(level, option, value); +} + + +inline void Socket::setOption(int level, int option, unsigned char value) +{ + _pImpl->setOption(level, option, value); +} + + +inline void Socket::setOption(int level, int option, const Poco::Timespan& value) +{ + _pImpl->setOption(level, option, value); +} + + +inline void Socket::setOption(int level, int option, const IPAddress& value) +{ + _pImpl->setOption(level, option, value); +} + + +inline void Socket::getOption(int level, int option, int& value) const +{ + _pImpl->getOption(level, option, value); +} + + +inline void Socket::getOption(int level, int option, unsigned& value) const +{ + _pImpl->getOption(level, option, value); +} + + +inline void Socket::getOption(int level, int option, unsigned char& value) const +{ + _pImpl->getOption(level, option, value); +} + + +inline void Socket::getOption(int level, int option, Poco::Timespan& value) const +{ + _pImpl->getOption(level, option, value); +} + + +inline void Socket::getOption(int level, int option, IPAddress& value) const +{ + _pImpl->getOption(level, option, value); +} + + +inline void Socket::setLinger(bool on, int seconds) +{ + _pImpl->setLinger(on, seconds); +} + + +inline void Socket::getLinger(bool& on, int& seconds) const +{ + _pImpl->getLinger(on, seconds); +} + + +inline void Socket::setNoDelay(bool flag) +{ + _pImpl->setNoDelay(flag); +} + + +inline bool Socket::getNoDelay() const +{ + return _pImpl->getNoDelay(); +} + + +inline void Socket::setKeepAlive(bool flag) +{ + _pImpl->setKeepAlive(flag); +} + + +inline bool Socket::getKeepAlive() const +{ + return _pImpl->getKeepAlive(); +} + + +inline void Socket::setReuseAddress(bool flag) +{ + _pImpl->setReuseAddress(flag); +} + + +inline bool Socket::getReuseAddress() const +{ + return _pImpl->getReuseAddress(); +} + + +inline void Socket::setReusePort(bool flag) +{ + _pImpl->setReusePort(flag); +} + + +inline bool Socket::getReusePort() const +{ + return _pImpl->getReusePort(); +} + + +inline void Socket::setOOBInline(bool flag) +{ + _pImpl->setOOBInline(flag); +} + + +inline bool Socket::getOOBInline() const +{ + return _pImpl->getOOBInline(); +} + + +inline void Socket::setBlocking(bool flag) +{ + _pImpl->setBlocking(flag); +} + + +inline SocketImpl* Socket::impl() const +{ + return _pImpl; +} + + +inline poco_socket_t Socket::sockfd() const +{ + return _pImpl->sockfd(); +} + + +inline SocketAddress Socket::address() const +{ + return _pImpl->address(); +} + + +inline SocketAddress Socket::peerAddress() const +{ + return _pImpl->peerAddress(); +} + + +inline bool Socket::supportsIPv4() +{ + return true; +} + + +inline bool Socket::supportsIPv6() +{ +#if defined(POCO_HAVE_IPv6) + return true; +#else + return false; +#endif +} + + +} } // namespace Poco::Net + + +#endif // Net_Socket_INCLUDED diff --git a/Net/include/Poco/Net/SocketAcceptor.h b/Net/include/Poco/Net/SocketAcceptor.h index b966156cc..7be9044f1 100644 --- a/Net/include/Poco/Net/SocketAcceptor.h +++ b/Net/include/Poco/Net/SocketAcceptor.h @@ -1,184 +1,184 @@ -// -// SocketAcceptor.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketAcceptor.h#1 $ -// -// Library: Net -// Package: Reactor -// Module: SocketAcceptor -// -// Definition of the SocketAcceptor 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_SocketAcceptor_INCLUDED -#define Net_SocketAcceptor_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketNotification.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Observer.h" - - -namespace Poco { -namespace Net { - - -template -class SocketAcceptor - /// This class implements the Acceptor part of the - /// Acceptor-Connector design pattern. - /// - /// The Acceptor-Connector pattern has been described in the book - /// "Pattern Languages of Program Design 3", edited by Robert Martin, - /// Frank Buschmann and Dirk Riehle (Addison Wesley, 1997). - /// - /// The Acceptor-Connector design pattern decouples connection - /// establishment and service initialization in a distributed system - /// from the processing performed once a service is initialized. - /// This decoupling is achieved with three components: Acceptors, - /// Connectors and Service Handlers. - /// The SocketAcceptor passively waits for connection requests (usually - /// from a remote Connector) and establishes a connection upon - /// arrival of a connection requests. Also, a Service Handler is - /// initialized to process the data arriving via the connection in - /// an application-specific way. - /// - /// The SocketAcceptor sets up a ServerSocket and registers itself - /// for a ReadableNotification, denoting an incoming connection request. - /// - /// When the ServerSocket becomes readable the SocketAcceptor accepts - /// the connection request and creates a ServiceHandler to - /// service the connection. - /// - /// The ServiceHandler class must provide a constructor that - /// takes a StreamSocket and a SocketReactor as arguments, - /// e.g.: - /// MyServiceHandler(const StreamSocket& socket, ServiceReactor& reactor) - /// - /// When the ServiceHandler is done, it must destroy itself. - /// - /// Subclasses can override the createServiceHandler() factory method - /// if special steps are necessary to create a ServiceHandler object. -{ -public: - SocketAcceptor(ServerSocket& socket): - _socket(socket), - _pReactor(0) - /// Creates an SocketAcceptor, using the given ServerSocket. - { - } - - SocketAcceptor(ServerSocket& socket, SocketReactor& reactor): - _socket(socket), - _pReactor(0) - /// Creates an SocketAcceptor, using the given ServerSocket. - /// The SocketAcceptor registers itself with the given SocketReactor. - { - registerAcceptor(reactor); - } - - virtual ~SocketAcceptor() - /// Destroys the SocketAcceptor. - { - unregisterAcceptor(); - } - - virtual void registerAcceptor(SocketReactor& reactor) - /// Registers the SocketAcceptor with a SocketReactor. - /// - /// A subclass can override this and, for example, also register - /// an event handler for a timeout event. - /// - /// The overriding method must call the baseclass implementation first. - { - _pReactor = &reactor; - _pReactor->addEventHandler(_socket, Poco::Observer(*this, &SocketAcceptor::onAccept)); - } - - virtual void unregisterAcceptor() - /// Unregisters the SocketAcceptor. - /// - /// A subclass can override this and, for example, also unregister - /// its event handler for a timeout event. - /// - /// The overriding method must call the baseclass implementation first. - { - if (_pReactor) - { - _pReactor->removeEventHandler(_socket, Poco::Observer(*this, &SocketAcceptor::onAccept)); - } - } - - void onAccept(ReadableNotification* pNotification) - { - pNotification->release(); - StreamSocket sock = _socket.acceptConnection(); - createServiceHandler(sock); - } - -protected: - virtual ServiceHandler* createServiceHandler(StreamSocket& socket) - /// Create and initialize a new ServiceHandler instance. - /// - /// Subclasses can override this method. - { - return new ServiceHandler(socket, *_pReactor); - } - - SocketReactor* reactor() - /// Returns a pointer to the SocketReactor where - /// this SocketAcceptor is registered. - /// - /// The pointer may be null. - { - return _pReactor; - } - - Socket& socket() - /// Returns a reference to the SocketAcceptor's socket. - { - return _socket; - } - -private: - SocketAcceptor(); - SocketAcceptor(const SocketAcceptor&); - SocketAcceptor& operator = (const SocketAcceptor&); - - ServerSocket _socket; - SocketReactor* _pReactor; -}; - - -} } // namespace Poco::Net - - -#endif // Net_SocketAcceptor_INCLUDED +// +// SocketAcceptor.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketAcceptor.h#1 $ +// +// Library: Net +// Package: Reactor +// Module: SocketAcceptor +// +// Definition of the SocketAcceptor 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_SocketAcceptor_INCLUDED +#define Net_SocketAcceptor_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketNotification.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Observer.h" + + +namespace Poco { +namespace Net { + + +template +class SocketAcceptor + /// This class implements the Acceptor part of the + /// Acceptor-Connector design pattern. + /// + /// The Acceptor-Connector pattern has been described in the book + /// "Pattern Languages of Program Design 3", edited by Robert Martin, + /// Frank Buschmann and Dirk Riehle (Addison Wesley, 1997). + /// + /// The Acceptor-Connector design pattern decouples connection + /// establishment and service initialization in a distributed system + /// from the processing performed once a service is initialized. + /// This decoupling is achieved with three components: Acceptors, + /// Connectors and Service Handlers. + /// The SocketAcceptor passively waits for connection requests (usually + /// from a remote Connector) and establishes a connection upon + /// arrival of a connection requests. Also, a Service Handler is + /// initialized to process the data arriving via the connection in + /// an application-specific way. + /// + /// The SocketAcceptor sets up a ServerSocket and registers itself + /// for a ReadableNotification, denoting an incoming connection request. + /// + /// When the ServerSocket becomes readable the SocketAcceptor accepts + /// the connection request and creates a ServiceHandler to + /// service the connection. + /// + /// The ServiceHandler class must provide a constructor that + /// takes a StreamSocket and a SocketReactor as arguments, + /// e.g.: + /// MyServiceHandler(const StreamSocket& socket, ServiceReactor& reactor) + /// + /// When the ServiceHandler is done, it must destroy itself. + /// + /// Subclasses can override the createServiceHandler() factory method + /// if special steps are necessary to create a ServiceHandler object. +{ +public: + SocketAcceptor(ServerSocket& socket): + _socket(socket), + _pReactor(0) + /// Creates an SocketAcceptor, using the given ServerSocket. + { + } + + SocketAcceptor(ServerSocket& socket, SocketReactor& reactor): + _socket(socket), + _pReactor(0) + /// Creates an SocketAcceptor, using the given ServerSocket. + /// The SocketAcceptor registers itself with the given SocketReactor. + { + registerAcceptor(reactor); + } + + virtual ~SocketAcceptor() + /// Destroys the SocketAcceptor. + { + unregisterAcceptor(); + } + + virtual void registerAcceptor(SocketReactor& reactor) + /// Registers the SocketAcceptor with a SocketReactor. + /// + /// A subclass can override this and, for example, also register + /// an event handler for a timeout event. + /// + /// The overriding method must call the baseclass implementation first. + { + _pReactor = &reactor; + _pReactor->addEventHandler(_socket, Poco::Observer(*this, &SocketAcceptor::onAccept)); + } + + virtual void unregisterAcceptor() + /// Unregisters the SocketAcceptor. + /// + /// A subclass can override this and, for example, also unregister + /// its event handler for a timeout event. + /// + /// The overriding method must call the baseclass implementation first. + { + if (_pReactor) + { + _pReactor->removeEventHandler(_socket, Poco::Observer(*this, &SocketAcceptor::onAccept)); + } + } + + void onAccept(ReadableNotification* pNotification) + { + pNotification->release(); + StreamSocket sock = _socket.acceptConnection(); + createServiceHandler(sock); + } + +protected: + virtual ServiceHandler* createServiceHandler(StreamSocket& socket) + /// Create and initialize a new ServiceHandler instance. + /// + /// Subclasses can override this method. + { + return new ServiceHandler(socket, *_pReactor); + } + + SocketReactor* reactor() + /// Returns a pointer to the SocketReactor where + /// this SocketAcceptor is registered. + /// + /// The pointer may be null. + { + return _pReactor; + } + + Socket& socket() + /// Returns a reference to the SocketAcceptor's socket. + { + return _socket; + } + +private: + SocketAcceptor(); + SocketAcceptor(const SocketAcceptor&); + SocketAcceptor& operator = (const SocketAcceptor&); + + ServerSocket _socket; + SocketReactor* _pReactor; +}; + + +} } // namespace Poco::Net + + +#endif // Net_SocketAcceptor_INCLUDED diff --git a/Net/include/Poco/Net/SocketAddress.h b/Net/include/Poco/Net/SocketAddress.h index 0acb3f443..3f558ccd0 100644 --- a/Net/include/Poco/Net/SocketAddress.h +++ b/Net/include/Poco/Net/SocketAddress.h @@ -1,162 +1,162 @@ -// -// SocketAddress.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketAddress.h#1 $ -// -// Library: Net -// Package: NetCore -// Module: SocketAddress -// -// Definition of the SocketAddress 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_SocketAddress_INCLUDED -#define Net_SocketAddress_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketDefs.h" -#include "Poco/Net/IPAddress.h" - - -namespace Poco { -namespace Net { - - -class IPAddress; -class SocketAddressImpl; - - -class Net_API SocketAddress - /// This class represents an internet (IP) endpoint/socket - /// address. The address can belong either to the - /// IPv4 or the IPv6 address family and consists of a - /// host address and a port number. -{ -public: - SocketAddress(); - /// Creates a wildcard (all zero) IPv4 SocketAddress. - - SocketAddress(const IPAddress& host, Poco::UInt16 port); - /// Creates a SocketAddress from an IP address and a port number. - - SocketAddress(const std::string& host, Poco::UInt16 port); - /// Creates a SocketAddress from an IP address and a port number. - /// - /// The IP address must either be a domain name, or it must - /// be in dotted decimal (IPv4) or hex string (IPv6) format. - - SocketAddress(const std::string& host, const std::string& port); - /// Creates a SocketAddress from an IP address and a - /// service name or port number. - /// - /// The IP address must either be a domain name, or it must - /// be in dotted decimal (IPv4) or hex string (IPv6) format. - /// - /// The given port must either be a decimal port number, or - /// a service name. - - explicit SocketAddress(const std::string& hostAndPort); - /// Creates a SocketAddress from an IP address or host name and a - /// port number/service name. Host name/address and port number must - /// be separated by a colon. In case of an IPv6 address, - /// the address part must be enclosed in brackets. - /// - /// Examples: - /// 192.168.1.10:80 - /// [::FFFF:192.168.1.120]:2040 - /// www.appinf.com:8080 - - SocketAddress(const SocketAddress& addr); - /// Creates a SocketAddress by copying another one. - - SocketAddress(const struct sockaddr* addr, poco_socklen_t length); - /// Creates a SocketAddress from a native socket address. - - ~SocketAddress(); - /// Destroys the SocketAddress. - - SocketAddress& operator = (const SocketAddress& addr); - /// Assigns another SocketAddress. - - void swap(SocketAddress& addr); - /// Swaps the SocketAddress with another one. - - IPAddress host() const; - /// Returns the host IP address. - - Poco::UInt16 port() const; - /// Returns the port number. - - poco_socklen_t length() const; - /// Returns the length of the internal native socket address. - - const struct sockaddr* addr() const; - /// Returns a pointer to the internal native socket address. - - int af() const; - /// Returns the address family (AF_INET or AF_INET6) of the address. - - std::string toString() const; - /// Returns a string representation of the address. - - enum - { - MAX_ADDRESS_LENGTH = -#if defined(POCO_HAVE_IPv6) - sizeof(struct sockaddr_in6) -#else - sizeof(struct sockaddr_in) -#endif - /// Maximum length in bytes of a socket address. - }; - -protected: - void init(const IPAddress& host, Poco::UInt16 port); - void init(const std::string& host, Poco::UInt16 port); - Poco::UInt16 resolveService(const std::string& service); - -private: - SocketAddressImpl* _pImpl; -}; - - -// -// inlines -// -inline void swap(SocketAddress& a1, SocketAddress& a2) -{ - a1.swap(a2); -} - - -} } // namespace Poco::Net - - -#endif // Net_SocketAddress_INCLUDED +// +// SocketAddress.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketAddress.h#1 $ +// +// Library: Net +// Package: NetCore +// Module: SocketAddress +// +// Definition of the SocketAddress 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_SocketAddress_INCLUDED +#define Net_SocketAddress_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketDefs.h" +#include "Poco/Net/IPAddress.h" + + +namespace Poco { +namespace Net { + + +class IPAddress; +class SocketAddressImpl; + + +class Net_API SocketAddress + /// This class represents an internet (IP) endpoint/socket + /// address. The address can belong either to the + /// IPv4 or the IPv6 address family and consists of a + /// host address and a port number. +{ +public: + SocketAddress(); + /// Creates a wildcard (all zero) IPv4 SocketAddress. + + SocketAddress(const IPAddress& host, Poco::UInt16 port); + /// Creates a SocketAddress from an IP address and a port number. + + SocketAddress(const std::string& host, Poco::UInt16 port); + /// Creates a SocketAddress from an IP address and a port number. + /// + /// The IP address must either be a domain name, or it must + /// be in dotted decimal (IPv4) or hex string (IPv6) format. + + SocketAddress(const std::string& host, const std::string& port); + /// Creates a SocketAddress from an IP address and a + /// service name or port number. + /// + /// The IP address must either be a domain name, or it must + /// be in dotted decimal (IPv4) or hex string (IPv6) format. + /// + /// The given port must either be a decimal port number, or + /// a service name. + + explicit SocketAddress(const std::string& hostAndPort); + /// Creates a SocketAddress from an IP address or host name and a + /// port number/service name. Host name/address and port number must + /// be separated by a colon. In case of an IPv6 address, + /// the address part must be enclosed in brackets. + /// + /// Examples: + /// 192.168.1.10:80 + /// [::FFFF:192.168.1.120]:2040 + /// www.appinf.com:8080 + + SocketAddress(const SocketAddress& addr); + /// Creates a SocketAddress by copying another one. + + SocketAddress(const struct sockaddr* addr, poco_socklen_t length); + /// Creates a SocketAddress from a native socket address. + + ~SocketAddress(); + /// Destroys the SocketAddress. + + SocketAddress& operator = (const SocketAddress& addr); + /// Assigns another SocketAddress. + + void swap(SocketAddress& addr); + /// Swaps the SocketAddress with another one. + + IPAddress host() const; + /// Returns the host IP address. + + Poco::UInt16 port() const; + /// Returns the port number. + + poco_socklen_t length() const; + /// Returns the length of the internal native socket address. + + const struct sockaddr* addr() const; + /// Returns a pointer to the internal native socket address. + + int af() const; + /// Returns the address family (AF_INET or AF_INET6) of the address. + + std::string toString() const; + /// Returns a string representation of the address. + + enum + { + MAX_ADDRESS_LENGTH = +#if defined(POCO_HAVE_IPv6) + sizeof(struct sockaddr_in6) +#else + sizeof(struct sockaddr_in) +#endif + /// Maximum length in bytes of a socket address. + }; + +protected: + void init(const IPAddress& host, Poco::UInt16 port); + void init(const std::string& host, Poco::UInt16 port); + Poco::UInt16 resolveService(const std::string& service); + +private: + SocketAddressImpl* _pImpl; +}; + + +// +// inlines +// +inline void swap(SocketAddress& a1, SocketAddress& a2) +{ + a1.swap(a2); +} + + +} } // namespace Poco::Net + + +#endif // Net_SocketAddress_INCLUDED diff --git a/Net/include/Poco/Net/SocketConnector.h b/Net/include/Poco/Net/SocketConnector.h index 1e200ea39..d7de82558 100644 --- a/Net/include/Poco/Net/SocketConnector.h +++ b/Net/include/Poco/Net/SocketConnector.h @@ -1,227 +1,227 @@ -// -// SocketConnector.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketConnector.h#1 $ -// -// Library: Net -// Package: Reactor -// Module: SocketConnector -// -// Definition of the SocketConnector 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_SocketConnector_INCLUDED -#define Net_SocketConnector_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketNotification.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Observer.h" - - -namespace Poco { -namespace Net { - - -template -class SocketConnector - /// This class implements the Connector part of the - /// Acceptor-Connector design pattern. - /// - /// The Acceptor-Connector pattern has been described in the book - /// "Pattern Languages of Program Design 3", edited by Robert Martin, - /// Frank Buschmann and Dirk Riehle (Addison Wesley, 1997). - /// - /// The Acceptor-Connector design pattern decouples connection - /// establishment and service initialization in a distributed system - /// from the processing performed once a service is initialized. - /// This decoupling is achieved with three components: Acceptors, - /// Connectors and Service Handlers. - /// The Connector actively establishes a connection with a remote - /// server socket (usually managed by an Acceptor) and initializes - /// a Service Handler to manage the connection. - /// - /// The SocketConnector sets up a StreamSocket, initiates a non-blocking - /// connect operation and registers itself for ReadableNotification, WritableNotification - /// and ErrorNotification. ReadableNotification or WritableNotification denote the successful - /// establishment of the connection. - /// - /// When the StreamSocket becomes readable or writeable, the SocketConnector - /// creates a ServiceHandler to service the connection and unregisters - /// itself. - /// - /// In case of an error (ErrorNotification), the SocketConnector unregisters itself - /// and calls the onError() method, which can be overridden by subclasses - /// to perform custom error handling. - /// - /// The ServiceHandler class must provide a constructor that - /// takes a StreamSocket and a SocketReactor as arguments, - /// e.g.: - /// MyServiceHandler(const StreamSocket& socket, ServiceReactor& reactor) - /// - /// When the ServiceHandler is done, it must destroy itself. - /// - /// Subclasses can override the createServiceHandler() factory method - /// if special steps are necessary to create a ServiceHandler object. -{ -public: - SocketConnector(SocketAddress& address): - _pReactor(0) - /// Creates a SocketConnector, using the given Socket. - { - _socket.connectNB(address); - } - - SocketConnector(SocketAddress& address, SocketReactor& reactor): - _pReactor(0) - /// Creates an acceptor, using the given ServerSocket. - /// The SocketConnector registers itself with the given SocketReactor. - { - _socket.connectNB(address); - registerConnector(reactor); - } - - virtual ~SocketConnector() - /// Destroys the SocketConnector. - { - unregisterConnector(); - } - - virtual void registerConnector(SocketReactor& reactor) - /// Registers the SocketConnector with a SocketReactor. - /// - /// A subclass can override this and, for example, also register - /// an event handler for a timeout event. - /// - /// The overriding method must call the baseclass implementation first. - { - _pReactor = &reactor; - _pReactor->addEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onReadable)); - _pReactor->addEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onWritable)); - _pReactor->addEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onError)); - } - - virtual void unregisterConnector() - /// Unregisters the SocketConnector. - /// - /// A subclass can override this and, for example, also unregister - /// its event handler for a timeout event. - /// - /// The overriding method must call the baseclass implementation first. - { - if (_pReactor) - { - _pReactor->removeEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onReadable)); - _pReactor->removeEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onWritable)); - _pReactor->removeEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onError)); - } - } - - void onReadable(ReadableNotification* pNotification) - { - pNotification->release(); - int err = _socket.impl()->socketError(); - if (err) - { - onError(err); - unregisterConnector(); - } - else - { - onConnect(); - } - } - - void onWritable(WritableNotification* pNotification) - { - pNotification->release(); - onConnect(); - } - - void onConnect() - { - _socket.setBlocking(true); - createServiceHandler(); - unregisterConnector(); - } - - void onError(ErrorNotification* pNotification) - { - pNotification->release(); - onError(_socket.impl()->socketError()); - unregisterConnector(); - } - -protected: - virtual ServiceHandler* createServiceHandler() - /// Create and initialize a new ServiceHandler instance. - /// - /// Subclasses can override this method. - { - return new ServiceHandler(_socket, *_pReactor); - } - - virtual void onError(int errorCode) - /// Called when the socket cannot be connected. - /// - /// Subclasses can override this method. - { - } - - SocketReactor* reactor() - /// Returns a pointer to the SocketReactor where - /// this SocketConnector is registered. - /// - /// The pointer may be null. - { - return _pReactor; - } - - Socket& socket() - /// Returns a reference to the SocketConnector's socket. - { - return _socket; - } - -private: - SocketConnector(); - SocketConnector(const SocketConnector&); - SocketConnector& operator = (const SocketConnector&); - - StreamSocket _socket; - SocketReactor* _pReactor; -}; - - -} } // namespace Poco::Net - - -#endif // Net_SocketConnector_INCLUDED +// +// SocketConnector.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketConnector.h#1 $ +// +// Library: Net +// Package: Reactor +// Module: SocketConnector +// +// Definition of the SocketConnector 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_SocketConnector_INCLUDED +#define Net_SocketConnector_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketNotification.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Observer.h" + + +namespace Poco { +namespace Net { + + +template +class SocketConnector + /// This class implements the Connector part of the + /// Acceptor-Connector design pattern. + /// + /// The Acceptor-Connector pattern has been described in the book + /// "Pattern Languages of Program Design 3", edited by Robert Martin, + /// Frank Buschmann and Dirk Riehle (Addison Wesley, 1997). + /// + /// The Acceptor-Connector design pattern decouples connection + /// establishment and service initialization in a distributed system + /// from the processing performed once a service is initialized. + /// This decoupling is achieved with three components: Acceptors, + /// Connectors and Service Handlers. + /// The Connector actively establishes a connection with a remote + /// server socket (usually managed by an Acceptor) and initializes + /// a Service Handler to manage the connection. + /// + /// The SocketConnector sets up a StreamSocket, initiates a non-blocking + /// connect operation and registers itself for ReadableNotification, WritableNotification + /// and ErrorNotification. ReadableNotification or WritableNotification denote the successful + /// establishment of the connection. + /// + /// When the StreamSocket becomes readable or writeable, the SocketConnector + /// creates a ServiceHandler to service the connection and unregisters + /// itself. + /// + /// In case of an error (ErrorNotification), the SocketConnector unregisters itself + /// and calls the onError() method, which can be overridden by subclasses + /// to perform custom error handling. + /// + /// The ServiceHandler class must provide a constructor that + /// takes a StreamSocket and a SocketReactor as arguments, + /// e.g.: + /// MyServiceHandler(const StreamSocket& socket, ServiceReactor& reactor) + /// + /// When the ServiceHandler is done, it must destroy itself. + /// + /// Subclasses can override the createServiceHandler() factory method + /// if special steps are necessary to create a ServiceHandler object. +{ +public: + SocketConnector(SocketAddress& address): + _pReactor(0) + /// Creates a SocketConnector, using the given Socket. + { + _socket.connectNB(address); + } + + SocketConnector(SocketAddress& address, SocketReactor& reactor): + _pReactor(0) + /// Creates an acceptor, using the given ServerSocket. + /// The SocketConnector registers itself with the given SocketReactor. + { + _socket.connectNB(address); + registerConnector(reactor); + } + + virtual ~SocketConnector() + /// Destroys the SocketConnector. + { + unregisterConnector(); + } + + virtual void registerConnector(SocketReactor& reactor) + /// Registers the SocketConnector with a SocketReactor. + /// + /// A subclass can override this and, for example, also register + /// an event handler for a timeout event. + /// + /// The overriding method must call the baseclass implementation first. + { + _pReactor = &reactor; + _pReactor->addEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onReadable)); + _pReactor->addEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onWritable)); + _pReactor->addEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onError)); + } + + virtual void unregisterConnector() + /// Unregisters the SocketConnector. + /// + /// A subclass can override this and, for example, also unregister + /// its event handler for a timeout event. + /// + /// The overriding method must call the baseclass implementation first. + { + if (_pReactor) + { + _pReactor->removeEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onReadable)); + _pReactor->removeEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onWritable)); + _pReactor->removeEventHandler(_socket, Poco::Observer(*this, &SocketConnector::onError)); + } + } + + void onReadable(ReadableNotification* pNotification) + { + pNotification->release(); + int err = _socket.impl()->socketError(); + if (err) + { + onError(err); + unregisterConnector(); + } + else + { + onConnect(); + } + } + + void onWritable(WritableNotification* pNotification) + { + pNotification->release(); + onConnect(); + } + + void onConnect() + { + _socket.setBlocking(true); + createServiceHandler(); + unregisterConnector(); + } + + void onError(ErrorNotification* pNotification) + { + pNotification->release(); + onError(_socket.impl()->socketError()); + unregisterConnector(); + } + +protected: + virtual ServiceHandler* createServiceHandler() + /// Create and initialize a new ServiceHandler instance. + /// + /// Subclasses can override this method. + { + return new ServiceHandler(_socket, *_pReactor); + } + + virtual void onError(int errorCode) + /// Called when the socket cannot be connected. + /// + /// Subclasses can override this method. + { + } + + SocketReactor* reactor() + /// Returns a pointer to the SocketReactor where + /// this SocketConnector is registered. + /// + /// The pointer may be null. + { + return _pReactor; + } + + Socket& socket() + /// Returns a reference to the SocketConnector's socket. + { + return _socket; + } + +private: + SocketConnector(); + SocketConnector(const SocketConnector&); + SocketConnector& operator = (const SocketConnector&); + + StreamSocket _socket; + SocketReactor* _pReactor; +}; + + +} } // namespace Poco::Net + + +#endif // Net_SocketConnector_INCLUDED diff --git a/Net/include/Poco/Net/SocketDefs.h b/Net/include/Poco/Net/SocketDefs.h index edd16a06f..9b501f924 100644 --- a/Net/include/Poco/Net/SocketDefs.h +++ b/Net/include/Poco/Net/SocketDefs.h @@ -1,201 +1,201 @@ -// -// SocketDefs.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketDefs.h#1 $ -// -// Library: Net -// Package: NetCore -// Module: SocketDefs -// -// Include platform-specific header files for sockets. -// -// 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_SocketDefs_INCLUDED -#define Net_SocketDefs_INCLUDED - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include -#include -#define POCO_INVALID_SOCKET INVALID_SOCKET -#define poco_socket_t SOCKET -#define poco_socklen_t int -#define poco_closesocket(s) closesocket(s) -#define POCO_EINTR WSAEINTR -#define POCO_EACCES WSAEACCES -#define POCO_EFAULT WSAEFAULT -#define POCO_EINVAL WSAEINVAL -#define POCO_EMFILE WSAEMFILE -#define POCO_EAGAIN WSAEWOULDBLOCK -#define POCO_EWOULDBLOCK WSAEWOULDBLOCK -#define POCO_EINPROGRESS WSAEINPROGRESS -#define POCO_EALREADY WSAEALREADY -#define POCO_ENOTSOCK WSAENOTSOCK -#define POCO_EDESTADDRREQ WSAEDESTADDRREQ -#define POCO_EMSGSIZE WSAEMSGSIZE -#define POCO_EPROTOTYPE WSAEPROTOTYPE -#define POCO_ENOPROTOOPT WSAENOPROTOOPT -#define POCO_EPROTONOSUPPORT WSAEPROTONOSUPPORT -#define POCO_ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT -#define POCO_ENOTSUP WSAEOPNOTSUPP -#define POCO_EPFNOSUPPORT WSAEPFNOSUPPORT -#define POCO_EAFNOSUPPORT WSAEAFNOSUPPORT -#define POCO_EADDRINUSE WSAEADDRINUSE -#define POCO_EADDRNOTAVAIL WSAEADDRNOTAVAIL -#define POCO_ENETDOWN WSAENETDOWN -#define POCO_ENETUNREACH WSAENETUNREACH -#define POCO_ENETRESET WSAENETRESET -#define POCO_ECONNABORTED WSAECONNABORTED -#define POCO_ECONNRESET WSAECONNRESET -#define POCO_ENOBUFS WSAENOBUFS -#define POCO_EISCONN WSAEISCONN -#define POCO_ENOTCONN WSAENOTCONN -#define POCO_ESHUTDOWN WSAESHUTDOWN -#define POCO_ETIMEDOUT WSAETIMEDOUT -#define POCO_ECONNREFUSED WSAECONNREFUSED -#define POCO_EHOSTDOWN WSAEHOSTDOWN -#define POCO_EHOSTUNREACH WSAEHOSTUNREACH -#define POCO_ESYSNOTREADY WSASYSNOTREADY -#define POCO_ENOTINIT WSANOTINITIALISED -#define POCO_HOST_NOT_FOUND WSAHOST_NOT_FOUND -#define POCO_TRY_AGAIN WSATRY_AGAIN -#define POCO_NO_RECOVERY WSANO_RECOVERY -#define POCO_NO_DATA WSANO_DATA -#elif defined(POCO_OS_FAMILY_UNIX) || defined(POCO_OS_FAMILY_VMS) -#include -#include -#include -#include -#if POCO_OS != POCO_OS_HPUX -#include -#endif -#include -#if defined(POCO_OS_FAMILY_VMS) -#include -#else -#include -#endif -#include -#include -#include -#if defined(POCO_OS_FAMILY_UNIX) -#include -#endif -#if defined(sun) || defined(__APPLE__) -#include -#include -#endif -#define POCO_INVALID_SOCKET -1 -#define poco_socket_t int -#define poco_socklen_t socklen_t -#define poco_closesocket(s) ::close(s) -#define POCO_EINTR EINTR -#define POCO_EACCES EACCES -#define POCO_EFAULT EFAULT -#define POCO_EINVAL EINVAL -#define POCO_EMFILE EMFILE -#define POCO_EAGAIN EAGAIN -#define POCO_EWOULDBLOCK EWOULDBLOCK -#define POCO_EINPROGRESS EINPROGRESS -#define POCO_EALREADY EALREADY -#define POCO_ENOTSOCK ENOTSOCK -#define POCO_EDESTADDRREQ EDESTADDRREQ -#define POCO_EMSGSIZE EMSGSIZE -#define POCO_EPROTOTYPE EPROTOTYPE -#define POCO_ENOPROTOOPT ENOPROTOOPT -#define POCO_EPROTONOSUPPORT EPROTONOSUPPORT -#if defined(ESOCKTNOSUPPORT) -#define POCO_ESOCKTNOSUPPORT ESOCKTNOSUPPORT -#else -#define POCO_ESOCKTNOSUPPORT -1 -#endif -#define POCO_ENOTSUP ENOTSUP -#define POCO_EPFNOSUPPORT EPFNOSUPPORT -#define POCO_EAFNOSUPPORT EAFNOSUPPORT -#define POCO_EADDRINUSE EADDRINUSE -#define POCO_EADDRNOTAVAIL EADDRNOTAVAIL -#define POCO_ENETDOWN ENETDOWN -#define POCO_ENETUNREACH ENETUNREACH -#define POCO_ENETRESET ENETRESET -#define POCO_ECONNABORTED ECONNABORTED -#define POCO_ECONNRESET ECONNRESET -#define POCO_ENOBUFS ENOBUFS -#define POCO_EISCONN EISCONN -#define POCO_ENOTCONN ENOTCONN -#if defined(ESHUTDOWN) -#define POCO_ESHUTDOWN ESHUTDOWN -#else -#define POCO_ESHUTDOWN -2 -#endif -#define POCO_ETIMEDOUT ETIMEDOUT -#define POCO_ECONNREFUSED ECONNREFUSED -#if defined(EHOSTDOWN) -#define POCO_EHOSTDOWN EHOSTDOWN -#else -#define POCO_EHOSTDOWN -3 -#endif -#define POCO_EHOSTUNREACH EHOSTUNREACH -#define POCO_ESYSNOTREADY -4 -#define POCO_ENOTINIT -5 -#define POCO_HOST_NOT_FOUND HOST_NOT_FOUND -#define POCO_TRY_AGAIN TRY_AGAIN -#define POCO_NO_RECOVERY NO_RECOVERY -#define POCO_NO_DATA NO_DATA -#endif - - -#if defined(POCO_OS_FAMILY_BSD) || (POCO_OS == POCO_OS_TRU64) || (POCO_OS == POCO_OS_AIX) || (POCO_OS == POCO_OS_IRIX) || (POCO_OS == POCO_OS_QNX) || (POCO_OS == POCO_OS_VXWORKS) -#define POCO_HAVE_SALEN 1 -#endif - - -#if (POCO_OS == POCO_OS_HPUX) -#define POCO_BROKEN_TIMEOUTS 1 -#endif - - -#if defined(POCO_HAVE_SALEN) -#define poco_set_sa_len(pSA, len) (pSA)->sa_len = (len) -#define poco_set_sin_len(pSA) (pSA)->sin_len = sizeof(struct sockaddr_in) -#if defined(POCO_HAVE_IPv6) -#define poco_set_sin6_len(pSA) (pSA)->sin6_len = sizeof(struct sockaddr_in6) -#endif -#else -#define poco_set_sa_len(pSA, len) (void) 0 -#define poco_set_sin_len(pSA) (void) 0 -#define poco_set_sin6_len(pSA) (void) 0 -#endif - - -#ifndef INADDR_NONE -#define INADDR_NONE 0xFFFFFFFF -#endif - - -#endif // Net_SocketDefs_INCLUDED +// +// SocketDefs.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketDefs.h#1 $ +// +// Library: Net +// Package: NetCore +// Module: SocketDefs +// +// Include platform-specific header files for sockets. +// +// 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_SocketDefs_INCLUDED +#define Net_SocketDefs_INCLUDED + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include +#include +#define POCO_INVALID_SOCKET INVALID_SOCKET +#define poco_socket_t SOCKET +#define poco_socklen_t int +#define poco_closesocket(s) closesocket(s) +#define POCO_EINTR WSAEINTR +#define POCO_EACCES WSAEACCES +#define POCO_EFAULT WSAEFAULT +#define POCO_EINVAL WSAEINVAL +#define POCO_EMFILE WSAEMFILE +#define POCO_EAGAIN WSAEWOULDBLOCK +#define POCO_EWOULDBLOCK WSAEWOULDBLOCK +#define POCO_EINPROGRESS WSAEINPROGRESS +#define POCO_EALREADY WSAEALREADY +#define POCO_ENOTSOCK WSAENOTSOCK +#define POCO_EDESTADDRREQ WSAEDESTADDRREQ +#define POCO_EMSGSIZE WSAEMSGSIZE +#define POCO_EPROTOTYPE WSAEPROTOTYPE +#define POCO_ENOPROTOOPT WSAENOPROTOOPT +#define POCO_EPROTONOSUPPORT WSAEPROTONOSUPPORT +#define POCO_ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT +#define POCO_ENOTSUP WSAEOPNOTSUPP +#define POCO_EPFNOSUPPORT WSAEPFNOSUPPORT +#define POCO_EAFNOSUPPORT WSAEAFNOSUPPORT +#define POCO_EADDRINUSE WSAEADDRINUSE +#define POCO_EADDRNOTAVAIL WSAEADDRNOTAVAIL +#define POCO_ENETDOWN WSAENETDOWN +#define POCO_ENETUNREACH WSAENETUNREACH +#define POCO_ENETRESET WSAENETRESET +#define POCO_ECONNABORTED WSAECONNABORTED +#define POCO_ECONNRESET WSAECONNRESET +#define POCO_ENOBUFS WSAENOBUFS +#define POCO_EISCONN WSAEISCONN +#define POCO_ENOTCONN WSAENOTCONN +#define POCO_ESHUTDOWN WSAESHUTDOWN +#define POCO_ETIMEDOUT WSAETIMEDOUT +#define POCO_ECONNREFUSED WSAECONNREFUSED +#define POCO_EHOSTDOWN WSAEHOSTDOWN +#define POCO_EHOSTUNREACH WSAEHOSTUNREACH +#define POCO_ESYSNOTREADY WSASYSNOTREADY +#define POCO_ENOTINIT WSANOTINITIALISED +#define POCO_HOST_NOT_FOUND WSAHOST_NOT_FOUND +#define POCO_TRY_AGAIN WSATRY_AGAIN +#define POCO_NO_RECOVERY WSANO_RECOVERY +#define POCO_NO_DATA WSANO_DATA +#elif defined(POCO_OS_FAMILY_UNIX) || defined(POCO_OS_FAMILY_VMS) +#include +#include +#include +#include +#if POCO_OS != POCO_OS_HPUX +#include +#endif +#include +#if defined(POCO_OS_FAMILY_VMS) +#include +#else +#include +#endif +#include +#include +#include +#if defined(POCO_OS_FAMILY_UNIX) +#include +#endif +#if defined(sun) || defined(__APPLE__) +#include +#include +#endif +#define POCO_INVALID_SOCKET -1 +#define poco_socket_t int +#define poco_socklen_t socklen_t +#define poco_closesocket(s) ::close(s) +#define POCO_EINTR EINTR +#define POCO_EACCES EACCES +#define POCO_EFAULT EFAULT +#define POCO_EINVAL EINVAL +#define POCO_EMFILE EMFILE +#define POCO_EAGAIN EAGAIN +#define POCO_EWOULDBLOCK EWOULDBLOCK +#define POCO_EINPROGRESS EINPROGRESS +#define POCO_EALREADY EALREADY +#define POCO_ENOTSOCK ENOTSOCK +#define POCO_EDESTADDRREQ EDESTADDRREQ +#define POCO_EMSGSIZE EMSGSIZE +#define POCO_EPROTOTYPE EPROTOTYPE +#define POCO_ENOPROTOOPT ENOPROTOOPT +#define POCO_EPROTONOSUPPORT EPROTONOSUPPORT +#if defined(ESOCKTNOSUPPORT) +#define POCO_ESOCKTNOSUPPORT ESOCKTNOSUPPORT +#else +#define POCO_ESOCKTNOSUPPORT -1 +#endif +#define POCO_ENOTSUP ENOTSUP +#define POCO_EPFNOSUPPORT EPFNOSUPPORT +#define POCO_EAFNOSUPPORT EAFNOSUPPORT +#define POCO_EADDRINUSE EADDRINUSE +#define POCO_EADDRNOTAVAIL EADDRNOTAVAIL +#define POCO_ENETDOWN ENETDOWN +#define POCO_ENETUNREACH ENETUNREACH +#define POCO_ENETRESET ENETRESET +#define POCO_ECONNABORTED ECONNABORTED +#define POCO_ECONNRESET ECONNRESET +#define POCO_ENOBUFS ENOBUFS +#define POCO_EISCONN EISCONN +#define POCO_ENOTCONN ENOTCONN +#if defined(ESHUTDOWN) +#define POCO_ESHUTDOWN ESHUTDOWN +#else +#define POCO_ESHUTDOWN -2 +#endif +#define POCO_ETIMEDOUT ETIMEDOUT +#define POCO_ECONNREFUSED ECONNREFUSED +#if defined(EHOSTDOWN) +#define POCO_EHOSTDOWN EHOSTDOWN +#else +#define POCO_EHOSTDOWN -3 +#endif +#define POCO_EHOSTUNREACH EHOSTUNREACH +#define POCO_ESYSNOTREADY -4 +#define POCO_ENOTINIT -5 +#define POCO_HOST_NOT_FOUND HOST_NOT_FOUND +#define POCO_TRY_AGAIN TRY_AGAIN +#define POCO_NO_RECOVERY NO_RECOVERY +#define POCO_NO_DATA NO_DATA +#endif + + +#if defined(POCO_OS_FAMILY_BSD) || (POCO_OS == POCO_OS_TRU64) || (POCO_OS == POCO_OS_AIX) || (POCO_OS == POCO_OS_IRIX) || (POCO_OS == POCO_OS_QNX) || (POCO_OS == POCO_OS_VXWORKS) +#define POCO_HAVE_SALEN 1 +#endif + + +#if (POCO_OS == POCO_OS_HPUX) +#define POCO_BROKEN_TIMEOUTS 1 +#endif + + +#if defined(POCO_HAVE_SALEN) +#define poco_set_sa_len(pSA, len) (pSA)->sa_len = (len) +#define poco_set_sin_len(pSA) (pSA)->sin_len = sizeof(struct sockaddr_in) +#if defined(POCO_HAVE_IPv6) +#define poco_set_sin6_len(pSA) (pSA)->sin6_len = sizeof(struct sockaddr_in6) +#endif +#else +#define poco_set_sa_len(pSA, len) (void) 0 +#define poco_set_sin_len(pSA) (void) 0 +#define poco_set_sin6_len(pSA) (void) 0 +#endif + + +#ifndef INADDR_NONE +#define INADDR_NONE 0xFFFFFFFF +#endif + + +#endif // Net_SocketDefs_INCLUDED diff --git a/Net/include/Poco/Net/SocketImpl.h b/Net/include/Poco/Net/SocketImpl.h index 0f90ab04b..ef28a6843 100644 --- a/Net/include/Poco/Net/SocketImpl.h +++ b/Net/include/Poco/Net/SocketImpl.h @@ -1,451 +1,451 @@ -// -// SocketImpl.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketImpl.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: SocketImpl -// -// Definition of the SocketImpl 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_SocketImpl_INCLUDED -#define Net_SocketImpl_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketDefs.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/RefCountedObject.h" -#include "Poco/Timespan.h" - - -namespace Poco { -namespace Net { - - -class Net_API SocketImpl: public Poco::RefCountedObject - /// This class encapsulates the Berkeley sockets API. - /// - /// Subclasses implement specific socket types like - /// stream or datagram sockets. - /// - /// You should not create any instances of this class. -{ -public: - enum SelectMode - { - SELECT_READ = 1, - SELECT_WRITE = 2, - SELECT_ERROR = 4 - }; - - virtual SocketImpl* acceptConnection(SocketAddress& clientAddr); - /// Get the next completed connection from the - /// socket's completed connection queue. - /// - /// If the queue is empty, waits until a connection - /// request completes. - /// - /// Returns a new TCP socket for the connection - /// with the client. - /// - /// The client socket's address is returned in clientAddr. - - virtual void connect(const SocketAddress& address); - /// Initializes the socket and establishes a connection to - /// the TCP server at the given address. - /// - /// Can also be used for UDP sockets. In this case, no - /// connection is established. Instead, incoming and outgoing - /// packets are restricted to the specified address. - - virtual void connect(const SocketAddress& address, const Poco::Timespan& timeout); - /// Initializes the socket, sets the socket timeout and - /// establishes a connection to the TCP server at the given address. - - virtual void connectNB(const SocketAddress& address); - /// Initializes the socket and establishes a connection to - /// the TCP server at the given address. Prior to opening the - /// connection the socket is set to nonblocking mode. - - virtual void bind(const SocketAddress& address, bool reuseAddress = false); - /// Bind a local address to the socket. - /// - /// This is usually only done when establishing a server - /// socket. TCP clients should not bind a socket to a - /// specific address. - /// - /// If reuseAddress is true, sets the SO_REUSEADDR - /// socket option. - - virtual void listen(int backlog = 64); - /// Puts the socket into listening state. - /// - /// The socket becomes a passive socket that - /// can accept incoming connection requests. - /// - /// The backlog argument specifies the maximum - /// number of connections that can be queued - /// for this socket. - - virtual void close(); - /// Close the socket. - - virtual void shutdownReceive(); - /// Shuts down the receiving part of the socket connection. - - virtual void shutdownSend(); - /// Shuts down the sending part of the socket connection. - - virtual void shutdown(); - /// Shuts down both the receiving and the sending part - /// of the socket connection. - - virtual int sendBytes(const void* buffer, int length, int flags = 0); - /// Sends the contents of the given buffer through - /// the socket. - /// - /// Returns the number of bytes sent, which may be - /// less than the number of bytes specified. - - virtual int receiveBytes(void* buffer, int length, int flags = 0); - /// Receives data from the socket and stores it - /// in buffer. Up to length bytes are received. - /// - /// Returns the number of bytes received. - - virtual int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0); - /// Sends the contents of the given buffer through - /// the socket to the given address. - /// - /// Returns the number of bytes sent, which may be - /// less than the number of bytes specified. - - virtual int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0); - /// Receives data from the socket and stores it - /// in buffer. Up to length bytes are received. - /// Stores the address of the sender in address. - /// - /// Returns the number of bytes received. - - virtual void sendUrgent(unsigned char data); - /// Sends one byte of urgent data through - /// the socket. - /// - /// The data is sent with the MSG_OOB flag. - /// - /// The preferred way for a socket to receive urgent data - /// is by enabling the SO_OOBINLINE option. - - virtual int available(); - /// Returns the number of bytes available that can be read - /// without causing the socket to block. - - virtual bool poll(const Poco::Timespan& timeout, int mode); - /// Determines the status of the socket, using a - /// call to select(). - /// - /// The mode argument is constructed by combining the values - /// of the SelectMode enumeration. - /// - /// Returns true if the next operation corresponding to - /// mode will not block, false otherwise. - - virtual void setSendBufferSize(int size); - /// Sets the size of the send buffer. - - virtual int getSendBufferSize(); - /// Returns the size of the send buffer. - /// - /// The returned value may be different than the - /// value previously set with setSendBufferSize(), - /// as the system is free to adjust the value. - - virtual void setReceiveBufferSize(int size); - /// Sets the size of the receive buffer. - - virtual int getReceiveBufferSize(); - /// Returns the size of the receive buffer. - /// - /// The returned value may be different than the - /// value previously set with setReceiveBufferSize(), - /// as the system is free to adjust the value. - - virtual void setSendTimeout(const Poco::Timespan& timeout); - /// Sets the send timeout for the socket. - - virtual Poco::Timespan getSendTimeout(); - /// Returns the send timeout for the socket. - /// - /// The returned timeout may be different than the - /// timeout previously set with setSendTimeout(), - /// as the system is free to adjust the value. - - virtual void setReceiveTimeout(const Poco::Timespan& timeout); - /// Sets the send timeout for the socket. - /// - /// On systems that do not support SO_RCVTIMEO, a - /// workaround using poll() is provided. - - virtual Poco::Timespan getReceiveTimeout(); - /// Returns the receive timeout for the socket. - /// - /// The returned timeout may be different than the - /// timeout previously set with setReceiveTimeout(), - /// as the system is free to adjust the value. - - virtual SocketAddress address(); - /// Returns the IP address and port number of the socket. - - virtual SocketAddress peerAddress(); - /// Returns the IP address and port number of the peer socket. - - void setOption(int level, int option, int value); - /// Sets the socket option specified by level and option - /// to the given integer value. - - void setOption(int level, int option, unsigned value); - /// Sets the socket option specified by level and option - /// to the given integer value. - - void setOption(int level, int option, unsigned char value); - /// Sets the socket option specified by level and option - /// to the given integer value. - - void setOption(int level, int option, const Poco::Timespan& value); - /// Sets the socket option specified by level and option - /// to the given time value. - - void setOption(int level, int option, const IPAddress& value); - /// Sets the socket option specified by level and option - /// to the given time value. - - virtual void setRawOption(int level, int option, const void* value, poco_socklen_t length); - /// Sets the socket option specified by level and option - /// to the given time value. - - void getOption(int level, int option, int& value); - /// Returns the value of the socket option - /// specified by level and option. - - void getOption(int level, int option, unsigned& value); - /// Returns the value of the socket option - /// specified by level and option. - - void getOption(int level, int option, unsigned char& value); - /// Returns the value of the socket option - /// specified by level and option. - - void getOption(int level, int option, Poco::Timespan& value); - /// Returns the value of the socket option - /// specified by level and option. - - void getOption(int level, int option, IPAddress& value); - /// Returns the value of the socket option - /// specified by level and option. - - virtual void getRawOption(int level, int option, void* value, poco_socklen_t& length); - /// Returns the value of the socket option - /// specified by level and option. - - void setLinger(bool on, int seconds); - /// Sets the value of the SO_LINGER socket option. - - void getLinger(bool& on, int& seconds); - /// Returns the value of the SO_LINGER socket option. - - void setNoDelay(bool flag); - /// Sets the value of the TCP_NODELAY socket option. - - bool getNoDelay(); - /// Returns the value of the TCP_NODELAY socket option. - - void setKeepAlive(bool flag); - /// Sets the value of the SO_KEEPALIVE socket option. - - bool getKeepAlive(); - /// Returns the value of the SO_KEEPALIVE socket option. - - void setReuseAddress(bool flag); - /// Sets the value of the SO_REUSEADDR socket option. - - bool getReuseAddress(); - /// Returns the value of the SO_REUSEADDR socket option. - - void setReusePort(bool flag); - /// Sets the value of the SO_REUSEPORT socket option. - /// Does nothing if the socket implementation does not - /// support SO_REUSEPORT. - - bool getReusePort(); - /// Returns the value of the SO_REUSEPORT socket option. - /// - /// Returns false if the socket implementation does not - /// support SO_REUSEPORT. - - void setOOBInline(bool flag); - /// Sets the value of the SO_OOBINLINE socket option. - - bool getOOBInline(); - /// Returns the value of the SO_OOBINLINE socket option. - - void setBroadcast(bool flag); - /// Sets the value of the SO_BROADCAST socket option. - - bool getBroadcast(); - /// Returns the value of the SO_BROADCAST socket option. - - void setBlocking(bool flag); - /// Sets the socket in blocking mode if flag is true, - /// disables blocking mode if flag is false. - - int socketError(); - /// Returns the value of the SO_ERROR socket option. - - poco_socket_t sockfd(); - /// Returns the socket descriptor for the - /// underlying native socket. - - void ioctl(int request, int& arg); - /// A wrapper for the ioctl system call. - - void ioctl(int request, void* arg); - /// A wrapper for the ioctl system call. - - bool initialized() const; - /// Returns true iff the underlying socket is initialized. - -protected: - SocketImpl(); - /// Creates a SocketImpl. - - SocketImpl(poco_socket_t sockfd); - /// Creates a SocketImpl using the given native socket. - - virtual ~SocketImpl(); - /// Destroys the SocketImpl. - /// Closes the socket if it is still open. - - virtual void init(int af); - /// Creates the underlying native socket. - /// - /// Subclasses must implement this method so - /// that it calls initSocket() with the - /// appropriate arguments. - /// - /// The default implementation creates a - /// stream socket. - - void initSocket(int af, int type, int proto = 0); - /// Creates the underlying native socket. - /// - /// The first argument, af, specifies the address family - /// used by the socket, which should be either AF_INET or - /// AF_INET6. - /// - /// The second argument, type, specifies the type of the - /// socket, which can be one of SOCK_STREAM, SOCK_DGRAM - /// or SOCK_RAW. - /// - /// The third argument, proto, is normally set to 0, - /// except for raw sockets. - - void setSockfd(poco_socket_t aSocket); - /// Allows subclasses to set the socket manually, iff no valid socket is set yet! - - void invalidate(); - /// Sets a socket to POCO_INVALID_SOCKET. It is assumed that the socket was closed - /// via a prior operation. - - static int lastError(); - /// Returns the last error code. - - static void error(); - /// Throws an appropriate exception for the last error. - - static void error(const std::string& arg); - /// Throws an appropriate exception for the last error. - - static void error(int code); - /// Throws an appropriate exception for the given error code. - - static void error(int code, const std::string& arg); - /// Throws an appropriate exception for the given error code. - -private: - SocketImpl(const SocketImpl&); - SocketImpl& operator = (const SocketImpl&); - - poco_socket_t _sockfd; -#if defined(POCO_BROKEN_TIMEOUTS) - Poco::Timespan _recvTimeout; -#endif - - friend class Socket; - friend class SecureSocketImpl; -}; - - -// -// inlines -// -inline poco_socket_t SocketImpl::sockfd() -{ - return _sockfd; -} - - -inline bool SocketImpl::initialized() const -{ - return _sockfd != POCO_INVALID_SOCKET; -} - - -inline int SocketImpl::lastError() -{ -#if defined(_WIN32) - return WSAGetLastError(); -#else - return errno; -#endif -} - - -inline void SocketImpl::invalidate() -{ - _sockfd = POCO_INVALID_SOCKET; -} - - -} } // namespace Poco::Net - - -#endif // Net_SocketImpl_INCLUDED +// +// SocketImpl.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketImpl.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: SocketImpl +// +// Definition of the SocketImpl 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_SocketImpl_INCLUDED +#define Net_SocketImpl_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketDefs.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/RefCountedObject.h" +#include "Poco/Timespan.h" + + +namespace Poco { +namespace Net { + + +class Net_API SocketImpl: public Poco::RefCountedObject + /// This class encapsulates the Berkeley sockets API. + /// + /// Subclasses implement specific socket types like + /// stream or datagram sockets. + /// + /// You should not create any instances of this class. +{ +public: + enum SelectMode + { + SELECT_READ = 1, + SELECT_WRITE = 2, + SELECT_ERROR = 4 + }; + + virtual SocketImpl* acceptConnection(SocketAddress& clientAddr); + /// Get the next completed connection from the + /// socket's completed connection queue. + /// + /// If the queue is empty, waits until a connection + /// request completes. + /// + /// Returns a new TCP socket for the connection + /// with the client. + /// + /// The client socket's address is returned in clientAddr. + + virtual void connect(const SocketAddress& address); + /// Initializes the socket and establishes a connection to + /// the TCP server at the given address. + /// + /// Can also be used for UDP sockets. In this case, no + /// connection is established. Instead, incoming and outgoing + /// packets are restricted to the specified address. + + virtual void connect(const SocketAddress& address, const Poco::Timespan& timeout); + /// Initializes the socket, sets the socket timeout and + /// establishes a connection to the TCP server at the given address. + + virtual void connectNB(const SocketAddress& address); + /// Initializes the socket and establishes a connection to + /// the TCP server at the given address. Prior to opening the + /// connection the socket is set to nonblocking mode. + + virtual void bind(const SocketAddress& address, bool reuseAddress = false); + /// Bind a local address to the socket. + /// + /// This is usually only done when establishing a server + /// socket. TCP clients should not bind a socket to a + /// specific address. + /// + /// If reuseAddress is true, sets the SO_REUSEADDR + /// socket option. + + virtual void listen(int backlog = 64); + /// Puts the socket into listening state. + /// + /// The socket becomes a passive socket that + /// can accept incoming connection requests. + /// + /// The backlog argument specifies the maximum + /// number of connections that can be queued + /// for this socket. + + virtual void close(); + /// Close the socket. + + virtual void shutdownReceive(); + /// Shuts down the receiving part of the socket connection. + + virtual void shutdownSend(); + /// Shuts down the sending part of the socket connection. + + virtual void shutdown(); + /// Shuts down both the receiving and the sending part + /// of the socket connection. + + virtual int sendBytes(const void* buffer, int length, int flags = 0); + /// Sends the contents of the given buffer through + /// the socket. + /// + /// Returns the number of bytes sent, which may be + /// less than the number of bytes specified. + + virtual int receiveBytes(void* buffer, int length, int flags = 0); + /// Receives data from the socket and stores it + /// in buffer. Up to length bytes are received. + /// + /// Returns the number of bytes received. + + virtual int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0); + /// Sends the contents of the given buffer through + /// the socket to the given address. + /// + /// Returns the number of bytes sent, which may be + /// less than the number of bytes specified. + + virtual int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0); + /// Receives data from the socket and stores it + /// in buffer. Up to length bytes are received. + /// Stores the address of the sender in address. + /// + /// Returns the number of bytes received. + + virtual void sendUrgent(unsigned char data); + /// Sends one byte of urgent data through + /// the socket. + /// + /// The data is sent with the MSG_OOB flag. + /// + /// The preferred way for a socket to receive urgent data + /// is by enabling the SO_OOBINLINE option. + + virtual int available(); + /// Returns the number of bytes available that can be read + /// without causing the socket to block. + + virtual bool poll(const Poco::Timespan& timeout, int mode); + /// Determines the status of the socket, using a + /// call to select(). + /// + /// The mode argument is constructed by combining the values + /// of the SelectMode enumeration. + /// + /// Returns true if the next operation corresponding to + /// mode will not block, false otherwise. + + virtual void setSendBufferSize(int size); + /// Sets the size of the send buffer. + + virtual int getSendBufferSize(); + /// Returns the size of the send buffer. + /// + /// The returned value may be different than the + /// value previously set with setSendBufferSize(), + /// as the system is free to adjust the value. + + virtual void setReceiveBufferSize(int size); + /// Sets the size of the receive buffer. + + virtual int getReceiveBufferSize(); + /// Returns the size of the receive buffer. + /// + /// The returned value may be different than the + /// value previously set with setReceiveBufferSize(), + /// as the system is free to adjust the value. + + virtual void setSendTimeout(const Poco::Timespan& timeout); + /// Sets the send timeout for the socket. + + virtual Poco::Timespan getSendTimeout(); + /// Returns the send timeout for the socket. + /// + /// The returned timeout may be different than the + /// timeout previously set with setSendTimeout(), + /// as the system is free to adjust the value. + + virtual void setReceiveTimeout(const Poco::Timespan& timeout); + /// Sets the send timeout for the socket. + /// + /// On systems that do not support SO_RCVTIMEO, a + /// workaround using poll() is provided. + + virtual Poco::Timespan getReceiveTimeout(); + /// Returns the receive timeout for the socket. + /// + /// The returned timeout may be different than the + /// timeout previously set with setReceiveTimeout(), + /// as the system is free to adjust the value. + + virtual SocketAddress address(); + /// Returns the IP address and port number of the socket. + + virtual SocketAddress peerAddress(); + /// Returns the IP address and port number of the peer socket. + + void setOption(int level, int option, int value); + /// Sets the socket option specified by level and option + /// to the given integer value. + + void setOption(int level, int option, unsigned value); + /// Sets the socket option specified by level and option + /// to the given integer value. + + void setOption(int level, int option, unsigned char value); + /// Sets the socket option specified by level and option + /// to the given integer value. + + void setOption(int level, int option, const Poco::Timespan& value); + /// Sets the socket option specified by level and option + /// to the given time value. + + void setOption(int level, int option, const IPAddress& value); + /// Sets the socket option specified by level and option + /// to the given time value. + + virtual void setRawOption(int level, int option, const void* value, poco_socklen_t length); + /// Sets the socket option specified by level and option + /// to the given time value. + + void getOption(int level, int option, int& value); + /// Returns the value of the socket option + /// specified by level and option. + + void getOption(int level, int option, unsigned& value); + /// Returns the value of the socket option + /// specified by level and option. + + void getOption(int level, int option, unsigned char& value); + /// Returns the value of the socket option + /// specified by level and option. + + void getOption(int level, int option, Poco::Timespan& value); + /// Returns the value of the socket option + /// specified by level and option. + + void getOption(int level, int option, IPAddress& value); + /// Returns the value of the socket option + /// specified by level and option. + + virtual void getRawOption(int level, int option, void* value, poco_socklen_t& length); + /// Returns the value of the socket option + /// specified by level and option. + + void setLinger(bool on, int seconds); + /// Sets the value of the SO_LINGER socket option. + + void getLinger(bool& on, int& seconds); + /// Returns the value of the SO_LINGER socket option. + + void setNoDelay(bool flag); + /// Sets the value of the TCP_NODELAY socket option. + + bool getNoDelay(); + /// Returns the value of the TCP_NODELAY socket option. + + void setKeepAlive(bool flag); + /// Sets the value of the SO_KEEPALIVE socket option. + + bool getKeepAlive(); + /// Returns the value of the SO_KEEPALIVE socket option. + + void setReuseAddress(bool flag); + /// Sets the value of the SO_REUSEADDR socket option. + + bool getReuseAddress(); + /// Returns the value of the SO_REUSEADDR socket option. + + void setReusePort(bool flag); + /// Sets the value of the SO_REUSEPORT socket option. + /// Does nothing if the socket implementation does not + /// support SO_REUSEPORT. + + bool getReusePort(); + /// Returns the value of the SO_REUSEPORT socket option. + /// + /// Returns false if the socket implementation does not + /// support SO_REUSEPORT. + + void setOOBInline(bool flag); + /// Sets the value of the SO_OOBINLINE socket option. + + bool getOOBInline(); + /// Returns the value of the SO_OOBINLINE socket option. + + void setBroadcast(bool flag); + /// Sets the value of the SO_BROADCAST socket option. + + bool getBroadcast(); + /// Returns the value of the SO_BROADCAST socket option. + + void setBlocking(bool flag); + /// Sets the socket in blocking mode if flag is true, + /// disables blocking mode if flag is false. + + int socketError(); + /// Returns the value of the SO_ERROR socket option. + + poco_socket_t sockfd(); + /// Returns the socket descriptor for the + /// underlying native socket. + + void ioctl(int request, int& arg); + /// A wrapper for the ioctl system call. + + void ioctl(int request, void* arg); + /// A wrapper for the ioctl system call. + + bool initialized() const; + /// Returns true iff the underlying socket is initialized. + +protected: + SocketImpl(); + /// Creates a SocketImpl. + + SocketImpl(poco_socket_t sockfd); + /// Creates a SocketImpl using the given native socket. + + virtual ~SocketImpl(); + /// Destroys the SocketImpl. + /// Closes the socket if it is still open. + + virtual void init(int af); + /// Creates the underlying native socket. + /// + /// Subclasses must implement this method so + /// that it calls initSocket() with the + /// appropriate arguments. + /// + /// The default implementation creates a + /// stream socket. + + void initSocket(int af, int type, int proto = 0); + /// Creates the underlying native socket. + /// + /// The first argument, af, specifies the address family + /// used by the socket, which should be either AF_INET or + /// AF_INET6. + /// + /// The second argument, type, specifies the type of the + /// socket, which can be one of SOCK_STREAM, SOCK_DGRAM + /// or SOCK_RAW. + /// + /// The third argument, proto, is normally set to 0, + /// except for raw sockets. + + void setSockfd(poco_socket_t aSocket); + /// Allows subclasses to set the socket manually, iff no valid socket is set yet! + + void invalidate(); + /// Sets a socket to POCO_INVALID_SOCKET. It is assumed that the socket was closed + /// via a prior operation. + + static int lastError(); + /// Returns the last error code. + + static void error(); + /// Throws an appropriate exception for the last error. + + static void error(const std::string& arg); + /// Throws an appropriate exception for the last error. + + static void error(int code); + /// Throws an appropriate exception for the given error code. + + static void error(int code, const std::string& arg); + /// Throws an appropriate exception for the given error code. + +private: + SocketImpl(const SocketImpl&); + SocketImpl& operator = (const SocketImpl&); + + poco_socket_t _sockfd; +#if defined(POCO_BROKEN_TIMEOUTS) + Poco::Timespan _recvTimeout; +#endif + + friend class Socket; + friend class SecureSocketImpl; +}; + + +// +// inlines +// +inline poco_socket_t SocketImpl::sockfd() +{ + return _sockfd; +} + + +inline bool SocketImpl::initialized() const +{ + return _sockfd != POCO_INVALID_SOCKET; +} + + +inline int SocketImpl::lastError() +{ +#if defined(_WIN32) + return WSAGetLastError(); +#else + return errno; +#endif +} + + +inline void SocketImpl::invalidate() +{ + _sockfd = POCO_INVALID_SOCKET; +} + + +} } // namespace Poco::Net + + +#endif // Net_SocketImpl_INCLUDED diff --git a/Net/include/Poco/Net/SocketNotification.h b/Net/include/Poco/Net/SocketNotification.h index 87c2487c1..3ab265aea 100644 --- a/Net/include/Poco/Net/SocketNotification.h +++ b/Net/include/Poco/Net/SocketNotification.h @@ -1,162 +1,162 @@ -// -// SocketNotification.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketNotification.h#1 $ -// -// Library: Net -// Package: Reactor -// Module: SocketNotification -// -// Definition of the SocketNotification 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_SocketNotification_INCLUDED -#define Net_SocketNotification_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/Socket.h" -#include "Poco/Notification.h" - - -namespace Poco { -namespace Net { - - -class SocketReactor; - - -class Net_API SocketNotification: public Poco::Notification - /// The base class for all notifications generated by - /// the SocketReactor. -{ -public: - SocketNotification(SocketReactor* pReactor); - /// Creates the SocketNotification for the given SocketReactor. - - virtual ~SocketNotification(); - /// Destroys the SocketNotification. - - SocketReactor& source(); - /// Returns the SocketReactor that generated the notification. - - Socket& socket(); - /// Returns the socket that caused the notification. - -private: - void setSocket(const Socket& socket); - - SocketReactor* _pReactor; - Socket _socket; - - friend class SocketNotifier; -}; - - -class Net_API ReadableNotification: public SocketNotification - /// This notification is sent if a socket has become readable. -{ -public: - ReadableNotification(SocketReactor* pReactor); - /// Creates the ReadableNotification for the given SocketReactor. - - ~ReadableNotification(); - /// Destroys the ReadableNotification. -}; - - -class Net_API WritableNotification: public SocketNotification - /// This notification is sent if a socket has become writable. -{ -public: - WritableNotification(SocketReactor* pReactor); - /// Creates the WritableNotification for the given SocketReactor. - - ~WritableNotification(); - /// Destroys the WritableNotification. -}; - - -class Net_API ErrorNotification: public SocketNotification - /// This notification is sent if a socket has signalled an error. -{ -public: - ErrorNotification(SocketReactor* pReactor); - /// Creates the ErrorNotification for the given SocketReactor. - - ~ErrorNotification(); - /// Destroys the ErrorNotification. -}; - - -class Net_API TimeoutNotification: public SocketNotification - /// This notification is sent if no other event has occured - /// for a specified time. -{ -public: - TimeoutNotification(SocketReactor* pReactor); - /// Creates the TimeoutNotification for the given SocketReactor. - - ~TimeoutNotification(); - /// Destroys the TimeoutNotification. -}; - - -class Net_API ShutdownNotification: public SocketNotification - /// This notification is sent when the SocketReactor is - /// about to shut down. -{ -public: - ShutdownNotification(SocketReactor* pReactor); - /// Creates the ShutdownNotification for the given SocketReactor. - - ~ShutdownNotification(); - /// Destroys the ShutdownNotification. -}; - - -// -// inlines -// -inline SocketReactor& SocketNotification::source() -{ - return *_pReactor; -} - - -inline Socket& SocketNotification::socket() -{ - return _socket; -} - - -} } // namespace Poco::Net - - -#endif // Net_SocketNotification_INCLUDED +// +// SocketNotification.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketNotification.h#1 $ +// +// Library: Net +// Package: Reactor +// Module: SocketNotification +// +// Definition of the SocketNotification 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_SocketNotification_INCLUDED +#define Net_SocketNotification_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/Socket.h" +#include "Poco/Notification.h" + + +namespace Poco { +namespace Net { + + +class SocketReactor; + + +class Net_API SocketNotification: public Poco::Notification + /// The base class for all notifications generated by + /// the SocketReactor. +{ +public: + SocketNotification(SocketReactor* pReactor); + /// Creates the SocketNotification for the given SocketReactor. + + virtual ~SocketNotification(); + /// Destroys the SocketNotification. + + SocketReactor& source(); + /// Returns the SocketReactor that generated the notification. + + Socket& socket(); + /// Returns the socket that caused the notification. + +private: + void setSocket(const Socket& socket); + + SocketReactor* _pReactor; + Socket _socket; + + friend class SocketNotifier; +}; + + +class Net_API ReadableNotification: public SocketNotification + /// This notification is sent if a socket has become readable. +{ +public: + ReadableNotification(SocketReactor* pReactor); + /// Creates the ReadableNotification for the given SocketReactor. + + ~ReadableNotification(); + /// Destroys the ReadableNotification. +}; + + +class Net_API WritableNotification: public SocketNotification + /// This notification is sent if a socket has become writable. +{ +public: + WritableNotification(SocketReactor* pReactor); + /// Creates the WritableNotification for the given SocketReactor. + + ~WritableNotification(); + /// Destroys the WritableNotification. +}; + + +class Net_API ErrorNotification: public SocketNotification + /// This notification is sent if a socket has signalled an error. +{ +public: + ErrorNotification(SocketReactor* pReactor); + /// Creates the ErrorNotification for the given SocketReactor. + + ~ErrorNotification(); + /// Destroys the ErrorNotification. +}; + + +class Net_API TimeoutNotification: public SocketNotification + /// This notification is sent if no other event has occured + /// for a specified time. +{ +public: + TimeoutNotification(SocketReactor* pReactor); + /// Creates the TimeoutNotification for the given SocketReactor. + + ~TimeoutNotification(); + /// Destroys the TimeoutNotification. +}; + + +class Net_API ShutdownNotification: public SocketNotification + /// This notification is sent when the SocketReactor is + /// about to shut down. +{ +public: + ShutdownNotification(SocketReactor* pReactor); + /// Creates the ShutdownNotification for the given SocketReactor. + + ~ShutdownNotification(); + /// Destroys the ShutdownNotification. +}; + + +// +// inlines +// +inline SocketReactor& SocketNotification::source() +{ + return *_pReactor; +} + + +inline Socket& SocketNotification::socket() +{ + return _socket; +} + + +} } // namespace Poco::Net + + +#endif // Net_SocketNotification_INCLUDED diff --git a/Net/include/Poco/Net/SocketNotifier.h b/Net/include/Poco/Net/SocketNotifier.h index 3b133a555..f65664a26 100644 --- a/Net/include/Poco/Net/SocketNotifier.h +++ b/Net/include/Poco/Net/SocketNotifier.h @@ -1,114 +1,114 @@ -// -// SocketNotifier.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketNotifier.h#1 $ -// -// Library: Net -// Package: Reactor -// Module: SocketNotifier -// -// Definition of the SocketNotifier 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_SocketNotifier_INCLUDED -#define Net_SocketNotifier_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/Socket.h" -#include "Poco/RefCountedObject.h" -#include "Poco/NotificationCenter.h" -#include "Poco/Observer.h" -#include - - -namespace Poco { -namespace Net { - - -class Socket; -class SocketReactor; -class SocketNotification; - - -class Net_API SocketNotifier: public Poco::RefCountedObject - /// This class is used internally by SocketReactor - /// to notify registered event handlers of socket events. -{ -public: - SocketNotifier(const Socket& socket); - /// Creates the SocketNotifier for the given socket. - - void addObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer); - /// Adds the given observer. - - void removeObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer); - /// Removes the given observer. - - bool accepts(SocketNotification* pNotification); - /// Returns true if there is at least one observer for the given notification. - - void dispatch(SocketNotification* pNotification); - /// Dispatches the notification to all observers. - - bool hasObservers() const; - /// Returns true if there are subscribers. - -protected: - ~SocketNotifier(); - /// Destroys the SocketNotifier. - -private: - typedef std::multiset EventSet; - - EventSet _events; - Poco::NotificationCenter _nc; - Socket _socket; -}; - - -// -// inlines -// -inline bool SocketNotifier::accepts(SocketNotification* pNotification) -{ - return _events.find(pNotification) != _events.end(); -} - - -inline bool SocketNotifier::hasObservers() const -{ - return _nc.hasObservers(); -} - - -} } // namespace Poco::Net - - -#endif // Net_SocketNotifier_INCLUDED +// +// SocketNotifier.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketNotifier.h#1 $ +// +// Library: Net +// Package: Reactor +// Module: SocketNotifier +// +// Definition of the SocketNotifier 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_SocketNotifier_INCLUDED +#define Net_SocketNotifier_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/Socket.h" +#include "Poco/RefCountedObject.h" +#include "Poco/NotificationCenter.h" +#include "Poco/Observer.h" +#include + + +namespace Poco { +namespace Net { + + +class Socket; +class SocketReactor; +class SocketNotification; + + +class Net_API SocketNotifier: public Poco::RefCountedObject + /// This class is used internally by SocketReactor + /// to notify registered event handlers of socket events. +{ +public: + SocketNotifier(const Socket& socket); + /// Creates the SocketNotifier for the given socket. + + void addObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer); + /// Adds the given observer. + + void removeObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer); + /// Removes the given observer. + + bool accepts(SocketNotification* pNotification); + /// Returns true if there is at least one observer for the given notification. + + void dispatch(SocketNotification* pNotification); + /// Dispatches the notification to all observers. + + bool hasObservers() const; + /// Returns true if there are subscribers. + +protected: + ~SocketNotifier(); + /// Destroys the SocketNotifier. + +private: + typedef std::multiset EventSet; + + EventSet _events; + Poco::NotificationCenter _nc; + Socket _socket; +}; + + +// +// inlines +// +inline bool SocketNotifier::accepts(SocketNotification* pNotification) +{ + return _events.find(pNotification) != _events.end(); +} + + +inline bool SocketNotifier::hasObservers() const +{ + return _nc.hasObservers(); +} + + +} } // namespace Poco::Net + + +#endif // Net_SocketNotifier_INCLUDED diff --git a/Net/include/Poco/Net/SocketReactor.h b/Net/include/Poco/Net/SocketReactor.h index 299fbf83b..1966e1e0f 100644 --- a/Net/include/Poco/Net/SocketReactor.h +++ b/Net/include/Poco/Net/SocketReactor.h @@ -1,221 +1,221 @@ -// -// SocketReactor.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketReactor.h#2 $ -// -// Library: Net -// Package: Reactor -// Module: SocketReactor -// -// Definition of the SocketReactor 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_SocketReactor_INCLUDED -#define Net_SocketReactor_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/Socket.h" -#include "Poco/Runnable.h" -#include "Poco/Timespan.h" -#include "Poco/Observer.h" -#include "Poco/AutoPtr.h" -#include - - -namespace Poco { -namespace Net { - - -class Socket; -class SocketNotification; -class SocketNotifier; - - -class Net_API SocketReactor: public Poco::Runnable - /// This class, which is part of the Reactor pattern, - /// implements the "Initiation Dispatcher". - /// - /// The Reactor pattern has been described in the book - /// "Pattern Languages of Program Design" by Jim Coplien - /// and Douglas C. Schmidt (Addison Wesley, 1995). - /// - /// The Reactor design pattern handles service requests that - /// are delivered concurrently to an application by one or more - /// clients. Each service in an application may consist of several - /// methods and is represented by a separate event handler. The event - /// handler is responsible for servicing service-specific requests. - /// The SocketReactor dispatches the event handlers. - /// - /// Event handlers (any class can be an event handler - there - /// is no base class for event handlers) can be registered - /// with the addEventHandler() method and deregistered with - /// the removeEventHandler() method. - /// - /// An event handler is always registered for a certain socket, - /// which is given in the call to addEventHandler(). Any method - /// of the event handler class can be registered to handle the - /// event - the only requirement is that the method takes - /// a pointer to an instance of SocketNotification (or a subclass of it) - /// as argument. - /// - /// Once started, the SocketReactor waits for events - /// on the registered sockets, using Socket::select(). - /// If an event is detected, the corresponding event handler - /// is invoked. There are five event types (and corresponding - /// notification classes) defined: ReadableNotification, WritableNotification, - /// ErrorNotification, TimeoutNotification and ShutdownNotification. - /// - /// The ReadableNotification will be dispatched if a socket becomes - /// readable. The WritableNotification will be dispatched if a socket - /// becomes writable. The ErrorNotification will be dispatched if - /// there is an error condition on a socket. - /// - /// If the timeout expires and no event has occured, a - /// TimeoutNotification will be dispatched to all event handlers - /// registered for it. This is done in the onTimeout() method - /// which can be overridded by subclasses to perform custom - /// timeout processing. - /// - /// Finally, when the SocketReactor is about to shut down (as a result - /// of stop() being called), it dispatches a ShutdownNotification - /// to all event handlers. This is done in the onShutdown() method - /// which can be overridded by subclasses to perform custom - /// shutdown processing. - /// - /// The SocketReactor is implemented so that it can - /// run in its own thread. It is also possible to run - /// multiple SocketReactors in parallel, as long as - /// they work on different sockets. - /// - /// It is safe to call addEventHandler() and removeEventHandler() - /// from another thread while the SocketReactor is running. Also, - /// it is safe to call addEventHandler() and removeEventHandler() - /// from event handlers. -{ -public: - SocketReactor(); - /// Creates the SocketReactor. - - SocketReactor(const Poco::Timespan& timeout); - /// Creates the SocketReactor, using the given timeout. - - virtual ~SocketReactor(); - /// Destroys the SocketReactor. - - void run(); - /// Runs the SocketReactor. The reactor will run - /// until stop() is called (in a separate thread). - - void stop(); - /// Stops the SocketReactor. - /// - /// The reactor will be stopped when the next event - /// (including a timeout event) occurs. - - void setTimeout(const Poco::Timespan& timeout); - /// Sets the timeout. - /// - /// If no other event occurs for the given timeout - /// interval, a timeout event is sent to all event listeners. - /// - /// The default timeout is 250 milliseconds; - /// - /// The timeout is passed to the Socket::select() - /// method. - - const Poco::Timespan& getTimeout() const; - /// Returns the timeout. - - void addEventHandler(const Socket& socket, const Poco::AbstractObserver& observer); - /// Registers an event handler with the SocketReactor. - /// - /// Usage: - /// Poco::Observer obs(*this, &MyEventHandler::handleMyEvent); - /// reactor.addEventHandler(obs); - - void removeEventHandler(const Socket& socket, const Poco::AbstractObserver& observer); - /// Unregisters an event handler with the SocketReactor. - /// - /// Usage: - /// Poco::Observer obs(*this, &MyEventHandler::handleMyEvent); - /// reactor.removeEventHandler(obs); - -protected: - virtual void onTimeout(); - /// Called if the timeout expires and no other events are available. - /// - /// Can be overridden by subclasses. The default implementation - /// dispatches the TimeoutNotification and thus should be called by overriding - /// implementations. - - virtual void onShutdown(); - /// Called when the SocketReactor is about to terminate. - /// - /// Can be overridden by subclasses. The default implementation - /// dispatches the ShutdownNotification and thus should be called by overriding - /// implementations. - - void dispatch(const Socket& socket, SocketNotification* pNotification); - /// Dispatches the given notification to all observers - /// registered for the given socket. - - void dispatch(SocketNotification* pNotification); - /// Dispatches the given notification to all observers. - -private: - typedef Poco::AutoPtr NotifierPtr; - typedef Poco::AutoPtr NotificationPtr; - typedef std::map EventHandlerMap; - - void dispatch(NotifierPtr& pNotifier, SocketNotification* pNotification); - - enum - { - DEFAULT_TIMEOUT = 250000 - }; - - bool _stop; - Poco::Timespan _timeout; - EventHandlerMap _handlers; - NotificationPtr _pReadableNotification; - NotificationPtr _pWritableNotification; - NotificationPtr _pErrorNotification; - NotificationPtr _pTimeoutNotification; - NotificationPtr _pShutdownNotification; - Poco::FastMutex _mutex; - - friend class SocketNotifier; -}; - - -} } // namespace Poco::Net - - -#endif // Net_SocketReactor_INCLUDED +// +// SocketReactor.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketReactor.h#2 $ +// +// Library: Net +// Package: Reactor +// Module: SocketReactor +// +// Definition of the SocketReactor 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_SocketReactor_INCLUDED +#define Net_SocketReactor_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/Socket.h" +#include "Poco/Runnable.h" +#include "Poco/Timespan.h" +#include "Poco/Observer.h" +#include "Poco/AutoPtr.h" +#include + + +namespace Poco { +namespace Net { + + +class Socket; +class SocketNotification; +class SocketNotifier; + + +class Net_API SocketReactor: public Poco::Runnable + /// This class, which is part of the Reactor pattern, + /// implements the "Initiation Dispatcher". + /// + /// The Reactor pattern has been described in the book + /// "Pattern Languages of Program Design" by Jim Coplien + /// and Douglas C. Schmidt (Addison Wesley, 1995). + /// + /// The Reactor design pattern handles service requests that + /// are delivered concurrently to an application by one or more + /// clients. Each service in an application may consist of several + /// methods and is represented by a separate event handler. The event + /// handler is responsible for servicing service-specific requests. + /// The SocketReactor dispatches the event handlers. + /// + /// Event handlers (any class can be an event handler - there + /// is no base class for event handlers) can be registered + /// with the addEventHandler() method and deregistered with + /// the removeEventHandler() method. + /// + /// An event handler is always registered for a certain socket, + /// which is given in the call to addEventHandler(). Any method + /// of the event handler class can be registered to handle the + /// event - the only requirement is that the method takes + /// a pointer to an instance of SocketNotification (or a subclass of it) + /// as argument. + /// + /// Once started, the SocketReactor waits for events + /// on the registered sockets, using Socket::select(). + /// If an event is detected, the corresponding event handler + /// is invoked. There are five event types (and corresponding + /// notification classes) defined: ReadableNotification, WritableNotification, + /// ErrorNotification, TimeoutNotification and ShutdownNotification. + /// + /// The ReadableNotification will be dispatched if a socket becomes + /// readable. The WritableNotification will be dispatched if a socket + /// becomes writable. The ErrorNotification will be dispatched if + /// there is an error condition on a socket. + /// + /// If the timeout expires and no event has occured, a + /// TimeoutNotification will be dispatched to all event handlers + /// registered for it. This is done in the onTimeout() method + /// which can be overridded by subclasses to perform custom + /// timeout processing. + /// + /// Finally, when the SocketReactor is about to shut down (as a result + /// of stop() being called), it dispatches a ShutdownNotification + /// to all event handlers. This is done in the onShutdown() method + /// which can be overridded by subclasses to perform custom + /// shutdown processing. + /// + /// The SocketReactor is implemented so that it can + /// run in its own thread. It is also possible to run + /// multiple SocketReactors in parallel, as long as + /// they work on different sockets. + /// + /// It is safe to call addEventHandler() and removeEventHandler() + /// from another thread while the SocketReactor is running. Also, + /// it is safe to call addEventHandler() and removeEventHandler() + /// from event handlers. +{ +public: + SocketReactor(); + /// Creates the SocketReactor. + + SocketReactor(const Poco::Timespan& timeout); + /// Creates the SocketReactor, using the given timeout. + + virtual ~SocketReactor(); + /// Destroys the SocketReactor. + + void run(); + /// Runs the SocketReactor. The reactor will run + /// until stop() is called (in a separate thread). + + void stop(); + /// Stops the SocketReactor. + /// + /// The reactor will be stopped when the next event + /// (including a timeout event) occurs. + + void setTimeout(const Poco::Timespan& timeout); + /// Sets the timeout. + /// + /// If no other event occurs for the given timeout + /// interval, a timeout event is sent to all event listeners. + /// + /// The default timeout is 250 milliseconds; + /// + /// The timeout is passed to the Socket::select() + /// method. + + const Poco::Timespan& getTimeout() const; + /// Returns the timeout. + + void addEventHandler(const Socket& socket, const Poco::AbstractObserver& observer); + /// Registers an event handler with the SocketReactor. + /// + /// Usage: + /// Poco::Observer obs(*this, &MyEventHandler::handleMyEvent); + /// reactor.addEventHandler(obs); + + void removeEventHandler(const Socket& socket, const Poco::AbstractObserver& observer); + /// Unregisters an event handler with the SocketReactor. + /// + /// Usage: + /// Poco::Observer obs(*this, &MyEventHandler::handleMyEvent); + /// reactor.removeEventHandler(obs); + +protected: + virtual void onTimeout(); + /// Called if the timeout expires and no other events are available. + /// + /// Can be overridden by subclasses. The default implementation + /// dispatches the TimeoutNotification and thus should be called by overriding + /// implementations. + + virtual void onShutdown(); + /// Called when the SocketReactor is about to terminate. + /// + /// Can be overridden by subclasses. The default implementation + /// dispatches the ShutdownNotification and thus should be called by overriding + /// implementations. + + void dispatch(const Socket& socket, SocketNotification* pNotification); + /// Dispatches the given notification to all observers + /// registered for the given socket. + + void dispatch(SocketNotification* pNotification); + /// Dispatches the given notification to all observers. + +private: + typedef Poco::AutoPtr NotifierPtr; + typedef Poco::AutoPtr NotificationPtr; + typedef std::map EventHandlerMap; + + void dispatch(NotifierPtr& pNotifier, SocketNotification* pNotification); + + enum + { + DEFAULT_TIMEOUT = 250000 + }; + + bool _stop; + Poco::Timespan _timeout; + EventHandlerMap _handlers; + NotificationPtr _pReadableNotification; + NotificationPtr _pWritableNotification; + NotificationPtr _pErrorNotification; + NotificationPtr _pTimeoutNotification; + NotificationPtr _pShutdownNotification; + Poco::FastMutex _mutex; + + friend class SocketNotifier; +}; + + +} } // namespace Poco::Net + + +#endif // Net_SocketReactor_INCLUDED diff --git a/Net/include/Poco/Net/SocketStream.h b/Net/include/Poco/Net/SocketStream.h index 815acfc54..3358e1f9f 100644 --- a/Net/include/Poco/Net/SocketStream.h +++ b/Net/include/Poco/Net/SocketStream.h @@ -1,199 +1,199 @@ -// -// SocketStream.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/SocketStream.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: SocketStream -// -// Definition of the SocketStream 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_SocketStream_INCLUDED -#define Net_SocketStream_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/BufferedBidirectionalStreamBuf.h" -#include -#include - - -namespace Poco { -namespace Net { - - -class StreamSocketImpl; - - -class Net_API SocketStreamBuf: public Poco::BufferedBidirectionalStreamBuf - /// This is the streambuf class used for reading from and writing to a socket. -{ -public: - SocketStreamBuf(const Socket& socket); - /// Creates a SocketStreamBuf with the given socket. - /// - /// The socket's SocketImpl must be a StreamSocketImpl, - /// otherwise an InvalidArgumentException is thrown. - - ~SocketStreamBuf(); - /// Destroys the SocketStreamBuf. - - StreamSocketImpl* socketImpl() const; - /// Returns the internal SocketImpl. - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - enum - { - STREAM_BUFFER_SIZE = 1024 - }; - - StreamSocketImpl* _pImpl; -}; - - -class Net_API SocketIOS: public virtual std::ios - /// The base class for SocketStream, SocketInputStream and - /// SocketOutputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - SocketIOS(const Socket& socket); - /// Creates the SocketIOS with the given socket. - /// - /// The socket's SocketImpl must be a StreamSocketImpl, - /// otherwise an InvalidArgumentException is thrown. - - ~SocketIOS(); - /// Destroys the SocketIOS. - /// - /// Flushes the buffer, but does not close the socket. - - SocketStreamBuf* rdbuf(); - /// Returns a pointer to the internal SocketStreamBuf. - - void close(); - /// Flushes the stream and closes the socket. - - StreamSocket socket() const; - /// Returns the underlying socket. - -protected: - SocketStreamBuf _buf; -}; - - -class Net_API SocketOutputStream: public SocketIOS, public std::ostream - /// An output stream for writing to a socket. -{ -public: - SocketOutputStream(const Socket& socket); - /// Creates the SocketOutputStream with the given socket. - /// - /// The socket's SocketImpl must be a StreamSocketImpl, - /// otherwise an InvalidArgumentException is thrown. - - ~SocketOutputStream(); - /// Destroys the SocketOutputStream. - /// - /// Flushes the buffer, but does not close the socket. -}; - - -class Net_API SocketInputStream: public SocketIOS, public std::istream - /// An input stream for reading from a socket. - /// - /// When using formatted input from a SocketInputStream, - /// always ensure that a receive timeout is set for the - /// socket. Otherwise your program might unexpectedly - /// hang. - /// - /// However, using formatted input from a SocketInputStream - /// is not recommended, due to the read-ahead behavior of - /// istream with formatted reads. -{ -public: - SocketInputStream(const Socket& socket); - /// Creates the SocketInputStream with the given socket. - /// - /// The socket's SocketImpl must be a StreamSocketImpl, - /// otherwise an InvalidArgumentException is thrown. - - ~SocketInputStream(); - /// Destroys the SocketInputStream. -}; - - -class Net_API SocketStream: public SocketIOS, public std::iostream - /// An bidirectional stream for reading from and writing to a socket. - /// - /// When using formatted input from a SocketStream, - /// always ensure that a receive timeout is set for the - /// socket. Otherwise your program might unexpectedly - /// hang. - /// - /// However, using formatted input from a SocketStream - /// is not recommended, due to the read-ahead behavior of - /// istream with formatted reads. -{ -public: - SocketStream(const Socket& socket); - /// Creates the SocketStream with the given socket. - /// - /// The socket's SocketImpl must be a StreamSocketImpl, - /// otherwise an InvalidArgumentException is thrown. - - ~SocketStream(); - /// Destroys the SocketStream. - /// - /// Flushes the buffer, but does not close the socket. -}; - - -// -// inlines -// -inline StreamSocketImpl* SocketStreamBuf::socketImpl() const -{ - return _pImpl; -} - - -} } // namespace Poco::Net - - -#endif // Net_SocketStream_INCLUDED +// +// SocketStream.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/SocketStream.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: SocketStream +// +// Definition of the SocketStream 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_SocketStream_INCLUDED +#define Net_SocketStream_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/BufferedBidirectionalStreamBuf.h" +#include +#include + + +namespace Poco { +namespace Net { + + +class StreamSocketImpl; + + +class Net_API SocketStreamBuf: public Poco::BufferedBidirectionalStreamBuf + /// This is the streambuf class used for reading from and writing to a socket. +{ +public: + SocketStreamBuf(const Socket& socket); + /// Creates a SocketStreamBuf with the given socket. + /// + /// The socket's SocketImpl must be a StreamSocketImpl, + /// otherwise an InvalidArgumentException is thrown. + + ~SocketStreamBuf(); + /// Destroys the SocketStreamBuf. + + StreamSocketImpl* socketImpl() const; + /// Returns the internal SocketImpl. + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024 + }; + + StreamSocketImpl* _pImpl; +}; + + +class Net_API SocketIOS: public virtual std::ios + /// The base class for SocketStream, SocketInputStream and + /// SocketOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + SocketIOS(const Socket& socket); + /// Creates the SocketIOS with the given socket. + /// + /// The socket's SocketImpl must be a StreamSocketImpl, + /// otherwise an InvalidArgumentException is thrown. + + ~SocketIOS(); + /// Destroys the SocketIOS. + /// + /// Flushes the buffer, but does not close the socket. + + SocketStreamBuf* rdbuf(); + /// Returns a pointer to the internal SocketStreamBuf. + + void close(); + /// Flushes the stream and closes the socket. + + StreamSocket socket() const; + /// Returns the underlying socket. + +protected: + SocketStreamBuf _buf; +}; + + +class Net_API SocketOutputStream: public SocketIOS, public std::ostream + /// An output stream for writing to a socket. +{ +public: + SocketOutputStream(const Socket& socket); + /// Creates the SocketOutputStream with the given socket. + /// + /// The socket's SocketImpl must be a StreamSocketImpl, + /// otherwise an InvalidArgumentException is thrown. + + ~SocketOutputStream(); + /// Destroys the SocketOutputStream. + /// + /// Flushes the buffer, but does not close the socket. +}; + + +class Net_API SocketInputStream: public SocketIOS, public std::istream + /// An input stream for reading from a socket. + /// + /// When using formatted input from a SocketInputStream, + /// always ensure that a receive timeout is set for the + /// socket. Otherwise your program might unexpectedly + /// hang. + /// + /// However, using formatted input from a SocketInputStream + /// is not recommended, due to the read-ahead behavior of + /// istream with formatted reads. +{ +public: + SocketInputStream(const Socket& socket); + /// Creates the SocketInputStream with the given socket. + /// + /// The socket's SocketImpl must be a StreamSocketImpl, + /// otherwise an InvalidArgumentException is thrown. + + ~SocketInputStream(); + /// Destroys the SocketInputStream. +}; + + +class Net_API SocketStream: public SocketIOS, public std::iostream + /// An bidirectional stream for reading from and writing to a socket. + /// + /// When using formatted input from a SocketStream, + /// always ensure that a receive timeout is set for the + /// socket. Otherwise your program might unexpectedly + /// hang. + /// + /// However, using formatted input from a SocketStream + /// is not recommended, due to the read-ahead behavior of + /// istream with formatted reads. +{ +public: + SocketStream(const Socket& socket); + /// Creates the SocketStream with the given socket. + /// + /// The socket's SocketImpl must be a StreamSocketImpl, + /// otherwise an InvalidArgumentException is thrown. + + ~SocketStream(); + /// Destroys the SocketStream. + /// + /// Flushes the buffer, but does not close the socket. +}; + + +// +// inlines +// +inline StreamSocketImpl* SocketStreamBuf::socketImpl() const +{ + return _pImpl; +} + + +} } // namespace Poco::Net + + +#endif // Net_SocketStream_INCLUDED diff --git a/Net/include/Poco/Net/StreamSocket.h b/Net/include/Poco/Net/StreamSocket.h index eda0d2408..f6120a97a 100644 --- a/Net/include/Poco/Net/StreamSocket.h +++ b/Net/include/Poco/Net/StreamSocket.h @@ -1,156 +1,156 @@ -// -// StreamSocket.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/StreamSocket.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: StreamSocket -// -// Definition of the StreamSocket 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_StreamSocket_INCLUDED -#define Net_StreamSocket_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/Socket.h" - - -namespace Poco { -namespace Net { - - -class StreamSocketImpl; - - -class Net_API StreamSocket: public Socket - /// This class provides an interface to a - /// TCP stream socket. -{ -public: - StreamSocket(); - /// Creates an unconnected stream socket. - /// - /// Before sending or receiving data, the socket - /// must be connected with a call to connect(). - - StreamSocket(const SocketAddress& address); - /// Creates a stream socket and connects it to - /// the socket specified by address. - - StreamSocket(const Socket& socket); - /// Creates the StreamSocket with the SocketImpl - /// from another socket. The SocketImpl must be - /// a StreamSocketImpl, otherwise an InvalidArgumentException - /// will be thrown. - - virtual ~StreamSocket(); - /// Destroys the StreamSocket. - - StreamSocket& operator = (const Socket& socket); - /// Assignment operator. - /// - /// Releases the socket's SocketImpl and - /// attaches the SocketImpl from the other socket and - /// increments the reference count of the SocketImpl. - - void connect(const SocketAddress& address); - /// Initializes the socket and establishes a connection to - /// the TCP server at the given address. - /// - /// Can also be used for UDP sockets. In this case, no - /// connection is established. Instead, incoming and outgoing - /// packets are restricted to the specified address. - - void connect(const SocketAddress& address, const Poco::Timespan& timeout); - /// Initializes the socket, sets the socket timeout and - /// establishes a connection to the TCP server at the given address. - - void connectNB(const SocketAddress& address); - /// Initializes the socket and establishes a connection to - /// the TCP server at the given address. Prior to opening the - /// connection the socket is set to nonblocking mode. - - void shutdownReceive(); - /// Shuts down the receiving part of the socket connection. - - void shutdownSend(); - /// Shuts down the sending part of the socket connection. - - void shutdown(); - /// Shuts down both the receiving and the sending part - /// of the socket connection. - - int sendBytes(const void* buffer, int length, int flags = 0); - /// Sends the contents of the given buffer through - /// the socket. - /// - /// Returns the number of bytes sent, which may be - /// less than the number of bytes specified. - - int receiveBytes(void* buffer, int length, int flags = 0); - /// Receives data from the socket and stores it - /// in buffer. Up to length bytes are received. - /// - /// Returns the number of bytes received. - /// A return value of 0 means a graceful shutdown - /// of the connection from the peer. - /// - /// Throws a TimeoutException if a receive timeout has - /// been set and nothing is received within that interval. - /// Throws a NetException (or a subclass) in case of other errors. - - void sendUrgent(unsigned char data); - /// Sends one byte of urgent data through - /// the socket. - /// - /// The data is sent with the MSG_OOB flag. - /// - /// The preferred way for a socket to receive urgent data - /// is by enabling the SO_OOBINLINE option. - -public: - StreamSocket(SocketImpl* pImpl); - /// Creates the Socket and attaches the given SocketImpl. - /// The socket takes owership of the SocketImpl. - /// - /// The SocketImpl must be a StreamSocketImpl, otherwise - /// an InvalidArgumentException will be thrown. - - friend class ServerSocket; - friend class SocketIOS; -}; - - -} } // namespace Poco::Net - - -#endif // Net_StreamSocket_INCLUDED +// +// StreamSocket.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/StreamSocket.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: StreamSocket +// +// Definition of the StreamSocket 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_StreamSocket_INCLUDED +#define Net_StreamSocket_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/Socket.h" + + +namespace Poco { +namespace Net { + + +class StreamSocketImpl; + + +class Net_API StreamSocket: public Socket + /// This class provides an interface to a + /// TCP stream socket. +{ +public: + StreamSocket(); + /// Creates an unconnected stream socket. + /// + /// Before sending or receiving data, the socket + /// must be connected with a call to connect(). + + StreamSocket(const SocketAddress& address); + /// Creates a stream socket and connects it to + /// the socket specified by address. + + StreamSocket(const Socket& socket); + /// Creates the StreamSocket with the SocketImpl + /// from another socket. The SocketImpl must be + /// a StreamSocketImpl, otherwise an InvalidArgumentException + /// will be thrown. + + virtual ~StreamSocket(); + /// Destroys the StreamSocket. + + StreamSocket& operator = (const Socket& socket); + /// Assignment operator. + /// + /// Releases the socket's SocketImpl and + /// attaches the SocketImpl from the other socket and + /// increments the reference count of the SocketImpl. + + void connect(const SocketAddress& address); + /// Initializes the socket and establishes a connection to + /// the TCP server at the given address. + /// + /// Can also be used for UDP sockets. In this case, no + /// connection is established. Instead, incoming and outgoing + /// packets are restricted to the specified address. + + void connect(const SocketAddress& address, const Poco::Timespan& timeout); + /// Initializes the socket, sets the socket timeout and + /// establishes a connection to the TCP server at the given address. + + void connectNB(const SocketAddress& address); + /// Initializes the socket and establishes a connection to + /// the TCP server at the given address. Prior to opening the + /// connection the socket is set to nonblocking mode. + + void shutdownReceive(); + /// Shuts down the receiving part of the socket connection. + + void shutdownSend(); + /// Shuts down the sending part of the socket connection. + + void shutdown(); + /// Shuts down both the receiving and the sending part + /// of the socket connection. + + int sendBytes(const void* buffer, int length, int flags = 0); + /// Sends the contents of the given buffer through + /// the socket. + /// + /// Returns the number of bytes sent, which may be + /// less than the number of bytes specified. + + int receiveBytes(void* buffer, int length, int flags = 0); + /// Receives data from the socket and stores it + /// in buffer. Up to length bytes are received. + /// + /// Returns the number of bytes received. + /// A return value of 0 means a graceful shutdown + /// of the connection from the peer. + /// + /// Throws a TimeoutException if a receive timeout has + /// been set and nothing is received within that interval. + /// Throws a NetException (or a subclass) in case of other errors. + + void sendUrgent(unsigned char data); + /// Sends one byte of urgent data through + /// the socket. + /// + /// The data is sent with the MSG_OOB flag. + /// + /// The preferred way for a socket to receive urgent data + /// is by enabling the SO_OOBINLINE option. + +public: + StreamSocket(SocketImpl* pImpl); + /// Creates the Socket and attaches the given SocketImpl. + /// The socket takes owership of the SocketImpl. + /// + /// The SocketImpl must be a StreamSocketImpl, otherwise + /// an InvalidArgumentException will be thrown. + + friend class ServerSocket; + friend class SocketIOS; +}; + + +} } // namespace Poco::Net + + +#endif // Net_StreamSocket_INCLUDED diff --git a/Net/include/Poco/Net/StreamSocketImpl.h b/Net/include/Poco/Net/StreamSocketImpl.h index a0f42c783..7a43d2105 100644 --- a/Net/include/Poco/Net/StreamSocketImpl.h +++ b/Net/include/Poco/Net/StreamSocketImpl.h @@ -1,72 +1,72 @@ -// -// StreamSocketImpl.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/StreamSocketImpl.h#1 $ -// -// Library: Net -// Package: Sockets -// Module: StreamSocketImpl -// -// Definition of the StreamSocketImpl 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_StreamSocketImpl_INCLUDED -#define Net_StreamSocketImpl_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/SocketImpl.h" - - -namespace Poco { -namespace Net { - - -class Net_API StreamSocketImpl: public SocketImpl - /// This class implements a TCP socket. -{ -public: - StreamSocketImpl(); - /// Creates a StreamSocketImpl. - - StreamSocketImpl(poco_socket_t sockfd); - /// Creates a StreamSocketImpl using the given native socket. - - virtual int sendBytes(const void* buffer, int length, int flags = 0); - /// Ensures that all data in buffer is sent. - -protected: - virtual ~StreamSocketImpl(); -}; - - -} } // namespace Poco::Net - - -#endif // Net_StreamSocketImpl_INCLUDED +// +// StreamSocketImpl.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/StreamSocketImpl.h#1 $ +// +// Library: Net +// Package: Sockets +// Module: StreamSocketImpl +// +// Definition of the StreamSocketImpl 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_StreamSocketImpl_INCLUDED +#define Net_StreamSocketImpl_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/SocketImpl.h" + + +namespace Poco { +namespace Net { + + +class Net_API StreamSocketImpl: public SocketImpl + /// This class implements a TCP socket. +{ +public: + StreamSocketImpl(); + /// Creates a StreamSocketImpl. + + StreamSocketImpl(poco_socket_t sockfd); + /// Creates a StreamSocketImpl using the given native socket. + + virtual int sendBytes(const void* buffer, int length, int flags = 0); + /// Ensures that all data in buffer is sent. + +protected: + virtual ~StreamSocketImpl(); +}; + + +} } // namespace Poco::Net + + +#endif // Net_StreamSocketImpl_INCLUDED diff --git a/Net/include/Poco/Net/StringPartSource.h b/Net/include/Poco/Net/StringPartSource.h index 21f49d595..dddc94a48 100644 --- a/Net/include/Poco/Net/StringPartSource.h +++ b/Net/include/Poco/Net/StringPartSource.h @@ -1,87 +1,87 @@ -// -// StringPartSource.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/StringPartSource.h#1 $ -// -// Library: Net -// Package: Messages -// Module: StringPartSource -// -// Definition of the StringPartSource 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_StringPartSource_INCLUDED -#define Net_StringPartSource_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/PartSource.h" -#include - - -namespace Poco { -namespace Net { - - -class Net_API StringPartSource: public PartSource - /// An implementation of PartSource for strings. -{ -public: - StringPartSource(const std::string& str); - /// Creates the StringPartSource for the given string. - /// - /// The MIME type is set to text/plain. - - StringPartSource(const std::string& str, const std::string& mediaType); - /// Creates the StringPartSource for the given - /// string and MIME type. - - StringPartSource(const std::string& str, const std::string& mediaType, const std::string& filename); - /// Creates the StringPartSource for the given - /// string, MIME type and filename. - - ~StringPartSource(); - /// Destroys the StringPartSource. - - std::istream& stream(); - /// Returns a string input stream for the string. - - const std::string& filename(); - /// Returns the filename portion of the path. - -private: - std::istringstream _istr; - std::string _filename; -}; - - -} } // namespace Poco::Net - - -#endif // Net_StringPartSource_INCLUDED +// +// StringPartSource.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/StringPartSource.h#1 $ +// +// Library: Net +// Package: Messages +// Module: StringPartSource +// +// Definition of the StringPartSource 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_StringPartSource_INCLUDED +#define Net_StringPartSource_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/PartSource.h" +#include + + +namespace Poco { +namespace Net { + + +class Net_API StringPartSource: public PartSource + /// An implementation of PartSource for strings. +{ +public: + StringPartSource(const std::string& str); + /// Creates the StringPartSource for the given string. + /// + /// The MIME type is set to text/plain. + + StringPartSource(const std::string& str, const std::string& mediaType); + /// Creates the StringPartSource for the given + /// string and MIME type. + + StringPartSource(const std::string& str, const std::string& mediaType, const std::string& filename); + /// Creates the StringPartSource for the given + /// string, MIME type and filename. + + ~StringPartSource(); + /// Destroys the StringPartSource. + + std::istream& stream(); + /// Returns a string input stream for the string. + + const std::string& filename(); + /// Returns the filename portion of the path. + +private: + std::istringstream _istr; + std::string _filename; +}; + + +} } // namespace Poco::Net + + +#endif // Net_StringPartSource_INCLUDED diff --git a/Net/include/Poco/Net/TCPServer.h b/Net/include/Poco/Net/TCPServer.h index f5278e140..810d413c4 100644 --- a/Net/include/Poco/Net/TCPServer.h +++ b/Net/include/Poco/Net/TCPServer.h @@ -1,191 +1,191 @@ -// -// TCPServer.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/TCPServer.h#1 $ -// -// Library: Net -// Package: TCPServer -// Module: TCPServer -// -// Definition of the TCPServer 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_TCPServer_INCLUDED -#define Net_TCPServer_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Runnable.h" -#include "Poco/Thread.h" -#include "Poco/ThreadPool.h" - - -namespace Poco { -namespace Net { - - -class TCPServerParams; -class TCPServerDispatcher; -class TCPServerConnectionFactory; - - -class Net_API TCPServer: public Poco::Runnable - /// This class implements a multithreaded TCP server. - /// - /// The server uses a ServerSocket to listen for incoming - /// connections. The ServerSocket must have been bound to - /// an address before it is passed to the TCPServer constructor. - /// Additionally, the ServerSocket must be put into listening - /// state before the TCPServer is started by calling the start() - /// method. - /// - /// The server uses a thread pool to assign threads to incoming - /// connections. Before incoming connections are assigned to - /// a connection thread, they are put into a queue. - /// Connection threads fetch new connections from the queue as soon - /// as they become free. Thus, a connection thread may serve more - /// than one connection. - /// - /// As soon as a connection thread fetches the next connection from - /// the queue, it creates a TCPServerConnection object for it - /// (using the TCPServerConnectionFactory passed to the constructor) - /// and calls the TCPServerConnection's start() method. When the - /// start() method returns, the connection object is deleted. - /// - /// The number of connection threads is adjusted dynamically, depending - /// on the number of connections waiting to be served. - /// - /// It is possible to specify a maximum number of queued connections. - /// This prevents the connection queue from overflowing in the - /// case of an extreme server load. In such a case, connections that - /// cannot be queued are silently and immediately closed. - /// - /// TCPServer uses a separate thread to accept incoming connections. - /// Thus, the call to start() returns immediately, and the server - /// continues to run in the background. - /// - /// To stop the server from accepting new connections, call stop(). - /// - /// After calling stop(), no new connections will be accepted and - /// all queued connections will be discarded. - /// Already served connections, however, will continue being served. -{ -public: - TCPServer(TCPServerConnectionFactory* pFactory, const ServerSocket& socket, TCPServerParams* pParams = 0); - /// Creates the TCPServer, using the given ServerSocket. - /// - /// The server takes ownership of the TCPServerConnectionFactory - /// and deletes it when it's no longer needed. - /// - /// The server also takes ownership of the TCPServerParams object. - /// If no TCPServerParams object is given, the server's TCPServerDispatcher - /// creates its own one. - /// - /// News threads are taken from the default thread pool. - - TCPServer(TCPServerConnectionFactory* pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, TCPServerParams* pParams = 0); - /// Creates the TCPServer, using the given ServerSocket. - /// - /// The server takes ownership of the TCPServerConnectionFactory - /// and deletes it when it's no longer needed. - /// - /// The server also takes ownership of the TCPServerParams object. - /// If no TCPServerParams object is given, the server's TCPServerDispatcher - /// creates its own one. - /// - /// News threads are taken from the given thread pool. - - virtual ~TCPServer(); - /// Destroys the TCPServer and its TCPServerConnectionFactory. - - const TCPServerParams& params() const; - /// Returns a const reference to the TCPServerParam object - /// used by the server's TCPServerDispatcher. - - void start(); - /// Starts the server. A new thread will be - /// created that waits for and accepts incoming - /// connections. - /// - /// Before start() is called, the ServerSocket passed to - /// TCPServer must have been bound and put into listening state. - - void stop(); - /// Stops the server. - /// - /// No new connections will be accepted. - /// Already handled connections will continue to be served. - /// - /// Once the server is stopped, it cannot be restarted. - - int currentThreads() const; - /// Returns the number of currently used connection threads. - - int totalConnections() const; - /// Returns the total number of handled connections. - - int currentConnections() const; - /// Returns the number of currently handled connections. - - int maxConcurrentConnections() const; - /// Returns the maximum number of concurrently handled connections. - - int queuedConnections() const; - /// Returns the number of queued connections. - - int refusedConnections() const; - /// Returns the number of refused connections. - -protected: - void run(); - /// Runs the server. The server will run until - /// the stop() method is called, or the server - /// object is destroyed, which implicitly calls - /// the stop() method. - - static std::string threadName(const ServerSocket& socket); - /// Returns a thread name for the server thread. - -private: - TCPServer(); - TCPServer(const TCPServer&); - TCPServer& operator = (const TCPServer&); - - ServerSocket _socket; - TCPServerDispatcher* _pDispatcher; - Poco::Thread _thread; - bool _stopped; -}; - - -} } // namespace Poco::Net - - -#endif // Net_TCPServer_INCLUDED +// +// TCPServer.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/TCPServer.h#1 $ +// +// Library: Net +// Package: TCPServer +// Module: TCPServer +// +// Definition of the TCPServer 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_TCPServer_INCLUDED +#define Net_TCPServer_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Runnable.h" +#include "Poco/Thread.h" +#include "Poco/ThreadPool.h" + + +namespace Poco { +namespace Net { + + +class TCPServerParams; +class TCPServerDispatcher; +class TCPServerConnectionFactory; + + +class Net_API TCPServer: public Poco::Runnable + /// This class implements a multithreaded TCP server. + /// + /// The server uses a ServerSocket to listen for incoming + /// connections. The ServerSocket must have been bound to + /// an address before it is passed to the TCPServer constructor. + /// Additionally, the ServerSocket must be put into listening + /// state before the TCPServer is started by calling the start() + /// method. + /// + /// The server uses a thread pool to assign threads to incoming + /// connections. Before incoming connections are assigned to + /// a connection thread, they are put into a queue. + /// Connection threads fetch new connections from the queue as soon + /// as they become free. Thus, a connection thread may serve more + /// than one connection. + /// + /// As soon as a connection thread fetches the next connection from + /// the queue, it creates a TCPServerConnection object for it + /// (using the TCPServerConnectionFactory passed to the constructor) + /// and calls the TCPServerConnection's start() method. When the + /// start() method returns, the connection object is deleted. + /// + /// The number of connection threads is adjusted dynamically, depending + /// on the number of connections waiting to be served. + /// + /// It is possible to specify a maximum number of queued connections. + /// This prevents the connection queue from overflowing in the + /// case of an extreme server load. In such a case, connections that + /// cannot be queued are silently and immediately closed. + /// + /// TCPServer uses a separate thread to accept incoming connections. + /// Thus, the call to start() returns immediately, and the server + /// continues to run in the background. + /// + /// To stop the server from accepting new connections, call stop(). + /// + /// After calling stop(), no new connections will be accepted and + /// all queued connections will be discarded. + /// Already served connections, however, will continue being served. +{ +public: + TCPServer(TCPServerConnectionFactory* pFactory, const ServerSocket& socket, TCPServerParams* pParams = 0); + /// Creates the TCPServer, using the given ServerSocket. + /// + /// The server takes ownership of the TCPServerConnectionFactory + /// and deletes it when it's no longer needed. + /// + /// The server also takes ownership of the TCPServerParams object. + /// If no TCPServerParams object is given, the server's TCPServerDispatcher + /// creates its own one. + /// + /// News threads are taken from the default thread pool. + + TCPServer(TCPServerConnectionFactory* pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, TCPServerParams* pParams = 0); + /// Creates the TCPServer, using the given ServerSocket. + /// + /// The server takes ownership of the TCPServerConnectionFactory + /// and deletes it when it's no longer needed. + /// + /// The server also takes ownership of the TCPServerParams object. + /// If no TCPServerParams object is given, the server's TCPServerDispatcher + /// creates its own one. + /// + /// News threads are taken from the given thread pool. + + virtual ~TCPServer(); + /// Destroys the TCPServer and its TCPServerConnectionFactory. + + const TCPServerParams& params() const; + /// Returns a const reference to the TCPServerParam object + /// used by the server's TCPServerDispatcher. + + void start(); + /// Starts the server. A new thread will be + /// created that waits for and accepts incoming + /// connections. + /// + /// Before start() is called, the ServerSocket passed to + /// TCPServer must have been bound and put into listening state. + + void stop(); + /// Stops the server. + /// + /// No new connections will be accepted. + /// Already handled connections will continue to be served. + /// + /// Once the server is stopped, it cannot be restarted. + + int currentThreads() const; + /// Returns the number of currently used connection threads. + + int totalConnections() const; + /// Returns the total number of handled connections. + + int currentConnections() const; + /// Returns the number of currently handled connections. + + int maxConcurrentConnections() const; + /// Returns the maximum number of concurrently handled connections. + + int queuedConnections() const; + /// Returns the number of queued connections. + + int refusedConnections() const; + /// Returns the number of refused connections. + +protected: + void run(); + /// Runs the server. The server will run until + /// the stop() method is called, or the server + /// object is destroyed, which implicitly calls + /// the stop() method. + + static std::string threadName(const ServerSocket& socket); + /// Returns a thread name for the server thread. + +private: + TCPServer(); + TCPServer(const TCPServer&); + TCPServer& operator = (const TCPServer&); + + ServerSocket _socket; + TCPServerDispatcher* _pDispatcher; + Poco::Thread _thread; + bool _stopped; +}; + + +} } // namespace Poco::Net + + +#endif // Net_TCPServer_INCLUDED diff --git a/Net/include/Poco/Net/TCPServerConnection.h b/Net/include/Poco/Net/TCPServerConnection.h index ba0212e76..ca0289f5d 100644 --- a/Net/include/Poco/Net/TCPServerConnection.h +++ b/Net/include/Poco/Net/TCPServerConnection.h @@ -1,108 +1,108 @@ -// -// TCPServerConnection.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/TCPServerConnection.h#1 $ -// -// Library: Net -// Package: TCPServer -// Module: TCPServerConnection -// -// Definition of the TCPServerConnection 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_TCPServerConnection_INCLUDED -#define Net_TCPServerConnection_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Runnable.h" - - -namespace Poco { -namespace Net { - - -class Net_API TCPServerConnection: public Poco::Runnable - /// The abstract base class for TCP server connections - /// created by TCPServer. - /// - /// Derived classes must override the run() method - /// (inherited from Runnable). Furthermore, a - /// TCPServerConnectionFactory must be provided for the subclass. - /// - /// The run() method must perform the complete handling - /// of the client connection. As soon as the run() method - /// returns, the server connection object is destroyed and - /// the connection is automatically closed. - /// - /// A new TCPServerConnection object will be created for - /// each new client connection that is accepted by - /// TCPServer. -{ -public: - TCPServerConnection(const StreamSocket& socket); - /// Creates the TCPServerConnection using the given - /// stream socket. - - virtual ~TCPServerConnection(); - /// Destroys the TCPServerConnection. - -protected: - StreamSocket& socket(); - /// Returns a reference to the underlying socket. - - void start(); - /// Calls run() and catches any exceptions that - /// might be thrown by run(). - -private: - TCPServerConnection(); - TCPServerConnection(const TCPServerConnection&); - TCPServerConnection& operator = (const TCPServerConnection&); - - StreamSocket _socket; - - friend class TCPServerDispatcher; -}; - - -// -// inlines -// -inline StreamSocket& TCPServerConnection::socket() -{ - return _socket; -} - - -} } // namespace Poco::Net - - -#endif // Net_TCPServerConnection_INCLUDED +// +// TCPServerConnection.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/TCPServerConnection.h#1 $ +// +// Library: Net +// Package: TCPServer +// Module: TCPServerConnection +// +// Definition of the TCPServerConnection 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_TCPServerConnection_INCLUDED +#define Net_TCPServerConnection_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Runnable.h" + + +namespace Poco { +namespace Net { + + +class Net_API TCPServerConnection: public Poco::Runnable + /// The abstract base class for TCP server connections + /// created by TCPServer. + /// + /// Derived classes must override the run() method + /// (inherited from Runnable). Furthermore, a + /// TCPServerConnectionFactory must be provided for the subclass. + /// + /// The run() method must perform the complete handling + /// of the client connection. As soon as the run() method + /// returns, the server connection object is destroyed and + /// the connection is automatically closed. + /// + /// A new TCPServerConnection object will be created for + /// each new client connection that is accepted by + /// TCPServer. +{ +public: + TCPServerConnection(const StreamSocket& socket); + /// Creates the TCPServerConnection using the given + /// stream socket. + + virtual ~TCPServerConnection(); + /// Destroys the TCPServerConnection. + +protected: + StreamSocket& socket(); + /// Returns a reference to the underlying socket. + + void start(); + /// Calls run() and catches any exceptions that + /// might be thrown by run(). + +private: + TCPServerConnection(); + TCPServerConnection(const TCPServerConnection&); + TCPServerConnection& operator = (const TCPServerConnection&); + + StreamSocket _socket; + + friend class TCPServerDispatcher; +}; + + +// +// inlines +// +inline StreamSocket& TCPServerConnection::socket() +{ + return _socket; +} + + +} } // namespace Poco::Net + + +#endif // Net_TCPServerConnection_INCLUDED diff --git a/Net/include/Poco/Net/TCPServerConnectionFactory.h b/Net/include/Poco/Net/TCPServerConnectionFactory.h index b674f86df..2e123fe6c 100644 --- a/Net/include/Poco/Net/TCPServerConnectionFactory.h +++ b/Net/include/Poco/Net/TCPServerConnectionFactory.h @@ -1,108 +1,108 @@ -// -// TCPServerConnectionFactory.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/TCPServerConnectionFactory.h#1 $ -// -// Library: Net -// Package: TCPServer -// Module: TCPServerConnectionFactory -// -// Definition of the TCPServerConnectionFactory 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_TCPServerConnectionFactory_INCLUDED -#define Net_TCPServerConnectionFactory_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/TCPServerConnection.h" - - -namespace Poco { -namespace Net { - - -class Net_API TCPServerConnectionFactory - /// A factory for TCPServerConnection objects. - /// - /// The TCPServer class uses a TCPServerConnectionFactory - /// to create a connection object for each new connection - /// it accepts. - /// - /// Subclasses must override the createConnection() - /// method. - /// - /// The TCPServerConnectionFactoryImpl template class - /// can be used to automatically instantiate a - /// TCPServerConnectionFactory for a given subclass - /// of TCPServerConnection. -{ -public: - virtual ~TCPServerConnectionFactory(); - /// Destroys the TCPServerConnectionFactory. - - virtual TCPServerConnection* createConnection(const StreamSocket& socket) = 0; - /// Creates an instance of a subclass of TCPServerConnection, - /// using the given StreamSocket. - -protected: - TCPServerConnectionFactory(); - /// Creates the TCPServerConnectionFactory. - -private: - TCPServerConnectionFactory(const TCPServerConnectionFactory&); - TCPServerConnectionFactory& operator = (const TCPServerConnectionFactory&); -}; - - -template -class TCPServerConnectionFactoryImpl: public TCPServerConnectionFactory - /// This template provides a basic implementation of - /// TCPServerConnectionFactory. -{ -public: - TCPServerConnectionFactoryImpl() - { - } - - ~TCPServerConnectionFactoryImpl() - { - } - - TCPServerConnection* createConnection(const StreamSocket& socket) - { - return new S(socket); - } -}; - - -} } // namespace Poco::Net - - -#endif // Net_TCPServerConnectionFactory_INCLUDED +// +// TCPServerConnectionFactory.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/TCPServerConnectionFactory.h#1 $ +// +// Library: Net +// Package: TCPServer +// Module: TCPServerConnectionFactory +// +// Definition of the TCPServerConnectionFactory 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_TCPServerConnectionFactory_INCLUDED +#define Net_TCPServerConnectionFactory_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/TCPServerConnection.h" + + +namespace Poco { +namespace Net { + + +class Net_API TCPServerConnectionFactory + /// A factory for TCPServerConnection objects. + /// + /// The TCPServer class uses a TCPServerConnectionFactory + /// to create a connection object for each new connection + /// it accepts. + /// + /// Subclasses must override the createConnection() + /// method. + /// + /// The TCPServerConnectionFactoryImpl template class + /// can be used to automatically instantiate a + /// TCPServerConnectionFactory for a given subclass + /// of TCPServerConnection. +{ +public: + virtual ~TCPServerConnectionFactory(); + /// Destroys the TCPServerConnectionFactory. + + virtual TCPServerConnection* createConnection(const StreamSocket& socket) = 0; + /// Creates an instance of a subclass of TCPServerConnection, + /// using the given StreamSocket. + +protected: + TCPServerConnectionFactory(); + /// Creates the TCPServerConnectionFactory. + +private: + TCPServerConnectionFactory(const TCPServerConnectionFactory&); + TCPServerConnectionFactory& operator = (const TCPServerConnectionFactory&); +}; + + +template +class TCPServerConnectionFactoryImpl: public TCPServerConnectionFactory + /// This template provides a basic implementation of + /// TCPServerConnectionFactory. +{ +public: + TCPServerConnectionFactoryImpl() + { + } + + ~TCPServerConnectionFactoryImpl() + { + } + + TCPServerConnection* createConnection(const StreamSocket& socket) + { + return new S(socket); + } +}; + + +} } // namespace Poco::Net + + +#endif // Net_TCPServerConnectionFactory_INCLUDED diff --git a/Net/include/Poco/Net/TCPServerDispatcher.h b/Net/include/Poco/Net/TCPServerDispatcher.h index 10be978c6..ae1263c6b 100644 --- a/Net/include/Poco/Net/TCPServerDispatcher.h +++ b/Net/include/Poco/Net/TCPServerDispatcher.h @@ -1,151 +1,151 @@ -// -// TCPServerDispatcher.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/TCPServerDispatcher.h#1 $ -// -// Library: Net -// Package: TCPServer -// Module: TCPServerDispatcher -// -// Definition of the TCPServerDispatcher 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_TCPServerDispatcher_INCLUDED -#define Net_TCPServerDispatcher_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Runnable.h" -#include "Poco/NotificationQueue.h" -#include "Poco/ThreadPool.h" -#include "Poco/Mutex.h" - - -namespace Poco { -namespace Net { - - -class TCPServerParams; -class TCPServerConnectionFactory; - - -class Net_API TCPServerDispatcher: public Poco::Runnable - /// A helper class for TCPServer that dispatches - /// connections to server connection threads. -{ -public: - TCPServerDispatcher(TCPServerConnectionFactory* pFactory, Poco::ThreadPool& threadPool, TCPServerParams* pParams); - /// Creates the TCPServerDispatcher. - /// - /// The dispatcher takes ownership of the TCPServerParams object. - /// If no TCPServerParams object is supplied, the TCPServerDispatcher - /// creates one. - - void duplicate(); - /// Increments the object's reference count. - - void release(); - /// Decrements the object's reference count - /// and deletes the object if the count - /// reaches zero. - - void run(); - /// Runs the dispatcher. - - void enqueue(const StreamSocket& socket); - /// Queues the given socket connection. - - void stop(); - /// Stops the dispatcher. - - int currentThreads() const; - /// Returns the number of currently used threads. - - int totalConnections() const; - /// Returns the total number of handled connections. - - int currentConnections() const; - /// Returns the number of currently handled connections. - - int maxConcurrentConnections() const; - /// Returns the maximum number of concurrently handled connections. - - int queuedConnections() const; - /// Returns the number of queued connections. - - int refusedConnections() const; - /// Returns the number of refused connections. - - const TCPServerParams& params() const; - /// Returns a const reference to the TCPServerParam object. - -protected: - ~TCPServerDispatcher(); - /// Destroys the TCPServerDispatcher. - - void beginConnection(); - /// Updates the performance counters. - - void endConnection(); - /// Updates the performance counters. - -private: - TCPServerDispatcher(); - TCPServerDispatcher(const TCPServerDispatcher&); - TCPServerDispatcher& operator = (const TCPServerDispatcher&); - - int _rc; - TCPServerParams* _pParams; - int _currentThreads; - int _totalConnections; - int _currentConnections; - int _maxConcurrentConnections; - int _refusedConnections; - bool _stopped; - Poco::NotificationQueue _queue; - TCPServerConnectionFactory* _pConnectionFactory; - Poco::ThreadPool& _threadPool; - mutable Poco::FastMutex _mutex; -}; - - -// -// inlines -// -inline const TCPServerParams& TCPServerDispatcher::params() const -{ - return *_pParams; -} - - -} } // namespace Poco::Net - - -#endif // Net_TCPServerDispatcher_INCLUDED +// +// TCPServerDispatcher.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/TCPServerDispatcher.h#1 $ +// +// Library: Net +// Package: TCPServer +// Module: TCPServerDispatcher +// +// Definition of the TCPServerDispatcher 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_TCPServerDispatcher_INCLUDED +#define Net_TCPServerDispatcher_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Runnable.h" +#include "Poco/NotificationQueue.h" +#include "Poco/ThreadPool.h" +#include "Poco/Mutex.h" + + +namespace Poco { +namespace Net { + + +class TCPServerParams; +class TCPServerConnectionFactory; + + +class Net_API TCPServerDispatcher: public Poco::Runnable + /// A helper class for TCPServer that dispatches + /// connections to server connection threads. +{ +public: + TCPServerDispatcher(TCPServerConnectionFactory* pFactory, Poco::ThreadPool& threadPool, TCPServerParams* pParams); + /// Creates the TCPServerDispatcher. + /// + /// The dispatcher takes ownership of the TCPServerParams object. + /// If no TCPServerParams object is supplied, the TCPServerDispatcher + /// creates one. + + void duplicate(); + /// Increments the object's reference count. + + void release(); + /// Decrements the object's reference count + /// and deletes the object if the count + /// reaches zero. + + void run(); + /// Runs the dispatcher. + + void enqueue(const StreamSocket& socket); + /// Queues the given socket connection. + + void stop(); + /// Stops the dispatcher. + + int currentThreads() const; + /// Returns the number of currently used threads. + + int totalConnections() const; + /// Returns the total number of handled connections. + + int currentConnections() const; + /// Returns the number of currently handled connections. + + int maxConcurrentConnections() const; + /// Returns the maximum number of concurrently handled connections. + + int queuedConnections() const; + /// Returns the number of queued connections. + + int refusedConnections() const; + /// Returns the number of refused connections. + + const TCPServerParams& params() const; + /// Returns a const reference to the TCPServerParam object. + +protected: + ~TCPServerDispatcher(); + /// Destroys the TCPServerDispatcher. + + void beginConnection(); + /// Updates the performance counters. + + void endConnection(); + /// Updates the performance counters. + +private: + TCPServerDispatcher(); + TCPServerDispatcher(const TCPServerDispatcher&); + TCPServerDispatcher& operator = (const TCPServerDispatcher&); + + int _rc; + TCPServerParams* _pParams; + int _currentThreads; + int _totalConnections; + int _currentConnections; + int _maxConcurrentConnections; + int _refusedConnections; + bool _stopped; + Poco::NotificationQueue _queue; + TCPServerConnectionFactory* _pConnectionFactory; + Poco::ThreadPool& _threadPool; + mutable Poco::FastMutex _mutex; +}; + + +// +// inlines +// +inline const TCPServerParams& TCPServerDispatcher::params() const +{ + return *_pParams; +} + + +} } // namespace Poco::Net + + +#endif // Net_TCPServerDispatcher_INCLUDED diff --git a/Net/include/Poco/Net/TCPServerParams.h b/Net/include/Poco/Net/TCPServerParams.h index f3905cf7a..e454922f1 100644 --- a/Net/include/Poco/Net/TCPServerParams.h +++ b/Net/include/Poco/Net/TCPServerParams.h @@ -1,140 +1,140 @@ -// -// TCPServerParams.h -// -// $Id: //poco/1.2/Net/include/Poco/Net/TCPServerParams.h#1 $ -// -// Library: Net -// Package: TCPServer -// Module: TCPServerParams -// -// Definition of the TCPServerParams 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_TCPServerParams_INCLUDED -#define Net_TCPServerParams_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/RefCountedObject.h" -#include "Poco/Timespan.h" - - -namespace Poco { -namespace Net { - - -class Net_API TCPServerParams: public Poco::RefCountedObject - /// This class is used to specify parameters to both the - /// TCPServer, as well as to TCPServerDispatcher objects. - /// - /// Subclasses may add new parameters to the class. -{ -public: - TCPServerParams(); - /// Creates the TCPServerParams. - /// - /// Sets the following default values: - /// - threadIdleTime: 10 seconds - /// - maxThreads: 0 - /// - maxQueued: 64 - - void setThreadIdleTime(const Poco::Timespan& idleTime); - /// Sets the maximum idle time for a thread before - /// it is terminated. - /// - /// The default idle time is 10 seconds; - - const Poco::Timespan& getThreadIdleTime() const; - /// Returns the maximum thread idle time. - - void setMaxQueued(int count); - /// Sets the maximum number of queued connections. - /// Must be greater than 0. - /// - /// If there are already the maximum number of connections - /// in the queue, new connections will be silently discarded. - /// - /// The default number is 64. - - int getMaxQueued() const; - /// Returns the maximum number of queued connections. - - void setMaxThreads(int count); - /// Sets the maximum number of simultaneous threads - /// available for this TCPServerDispatcher. - /// - /// Must be greater than or equal to 0. - /// If 0 is specified, the TCPServerDispatcher will - /// set this parameter to the number of available threads - /// in its thread pool. - /// - /// The thread pool used by the TCPServerDispatcher - /// must at least have the capacity for the given - /// number of threads. - - int getMaxThreads() const; - /// Returns the maximum number of simultaneous threads - /// available for this TCPServerDispatcher. - -protected: - virtual ~TCPServerParams(); - /// Destroys the TCPServerParams. - -private: - Poco::Timespan _threadIdleTime; - int _maxThreads; - int _maxQueued; -}; - - -// -// inlines -// -inline const Poco::Timespan& TCPServerParams::getThreadIdleTime() const -{ - return _threadIdleTime; -} - - -inline int TCPServerParams::getMaxThreads() const -{ - return _maxThreads; -} - - -inline int TCPServerParams::getMaxQueued() const -{ - return _maxQueued; -} - - -} } // namespace Poco::Net - - -#endif // Net_TCPServerParams_INCLUDED +// +// TCPServerParams.h +// +// $Id: //poco/1.2/Net/include/Poco/Net/TCPServerParams.h#1 $ +// +// Library: Net +// Package: TCPServer +// Module: TCPServerParams +// +// Definition of the TCPServerParams 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_TCPServerParams_INCLUDED +#define Net_TCPServerParams_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/RefCountedObject.h" +#include "Poco/Timespan.h" + + +namespace Poco { +namespace Net { + + +class Net_API TCPServerParams: public Poco::RefCountedObject + /// This class is used to specify parameters to both the + /// TCPServer, as well as to TCPServerDispatcher objects. + /// + /// Subclasses may add new parameters to the class. +{ +public: + TCPServerParams(); + /// Creates the TCPServerParams. + /// + /// Sets the following default values: + /// - threadIdleTime: 10 seconds + /// - maxThreads: 0 + /// - maxQueued: 64 + + void setThreadIdleTime(const Poco::Timespan& idleTime); + /// Sets the maximum idle time for a thread before + /// it is terminated. + /// + /// The default idle time is 10 seconds; + + const Poco::Timespan& getThreadIdleTime() const; + /// Returns the maximum thread idle time. + + void setMaxQueued(int count); + /// Sets the maximum number of queued connections. + /// Must be greater than 0. + /// + /// If there are already the maximum number of connections + /// in the queue, new connections will be silently discarded. + /// + /// The default number is 64. + + int getMaxQueued() const; + /// Returns the maximum number of queued connections. + + void setMaxThreads(int count); + /// Sets the maximum number of simultaneous threads + /// available for this TCPServerDispatcher. + /// + /// Must be greater than or equal to 0. + /// If 0 is specified, the TCPServerDispatcher will + /// set this parameter to the number of available threads + /// in its thread pool. + /// + /// The thread pool used by the TCPServerDispatcher + /// must at least have the capacity for the given + /// number of threads. + + int getMaxThreads() const; + /// Returns the maximum number of simultaneous threads + /// available for this TCPServerDispatcher. + +protected: + virtual ~TCPServerParams(); + /// Destroys the TCPServerParams. + +private: + Poco::Timespan _threadIdleTime; + int _maxThreads; + int _maxQueued; +}; + + +// +// inlines +// +inline const Poco::Timespan& TCPServerParams::getThreadIdleTime() const +{ + return _threadIdleTime; +} + + +inline int TCPServerParams::getMaxThreads() const +{ + return _maxThreads; +} + + +inline int TCPServerParams::getMaxQueued() const +{ + return _maxQueued; +} + + +} } // namespace Poco::Net + + +#endif // Net_TCPServerParams_INCLUDED diff --git a/Net/samples/EchoServer/EchoServer.properties b/Net/samples/EchoServer/EchoServer.properties index 5a4a48057..19e56d889 100644 --- a/Net/samples/EchoServer/EchoServer.properties +++ b/Net/samples/EchoServer/EchoServer.properties @@ -1,10 +1,10 @@ -# This is a sample configuration file for EchoServer - -logging.loggers.root.channel.class = ConsoleChannel -logging.loggers.app.name = Application -logging.loggers.app.channel = c1 -logging.formatters.f1.class = PatternFormatter -logging.formatters.f1.pattern = [%p] %t -logging.channels.c1.class = ConsoleChannel -logging.channels.c1.formatter = f1 -# EchoServer.port = 9911 +# This is a sample configuration file for EchoServer + +logging.loggers.root.channel.class = ConsoleChannel +logging.loggers.app.name = Application +logging.loggers.app.channel = c1 +logging.formatters.f1.class = PatternFormatter +logging.formatters.f1.pattern = [%p] %t +logging.channels.c1.class = ConsoleChannel +logging.channels.c1.formatter = f1 +# EchoServer.port = 9911 diff --git a/Net/samples/EchoServer/EchoServer.vmsbuild b/Net/samples/EchoServer/EchoServer.vmsbuild index 02df6f26d..4a00a897f 100644 --- a/Net/samples/EchoServer/EchoServer.vmsbuild +++ b/Net/samples/EchoServer/EchoServer.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Net/samples/EchoServer/EchoServer.vmsbuild#1 $ -# -EXE=EchoServer -EchoServer - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Net/samples/EchoServer/EchoServer.vmsbuild#1 $ +# +EXE=EchoServer +EchoServer + diff --git a/Net/samples/EchoServer/EchoServer_vs71.vcproj b/Net/samples/EchoServer/EchoServer_vs71.vcproj index 801da1c25..275673e52 100644 --- a/Net/samples/EchoServer/EchoServer_vs71.vcproj +++ b/Net/samples/EchoServer/EchoServer_vs71.vcproj @@ -1,152 +1,152 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/EchoServer/EchoServer_vs80.vcproj b/Net/samples/EchoServer/EchoServer_vs80.vcproj index 6a1d5dfb2..dcb9906ef 100644 --- a/Net/samples/EchoServer/EchoServer_vs80.vcproj +++ b/Net/samples/EchoServer/EchoServer_vs80.vcproj @@ -1,218 +1,218 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/EchoServer/Makefile b/Net/samples/EchoServer/Makefile index a91670703..f5c770226 100644 --- a/Net/samples/EchoServer/Makefile +++ b/Net/samples/EchoServer/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/EchoServer/Makefile#1 $ -# -# Makefile for Poco EchoServer -# - -include $(POCO_BASE)/build/rules/global - -objects = EchoServer - -target = EchoServer -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/EchoServer/Makefile#1 $ +# +# Makefile for Poco EchoServer +# + +include $(POCO_BASE)/build/rules/global + +objects = EchoServer + +target = EchoServer +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/EchoServer/src/EchoServer.cpp b/Net/samples/EchoServer/src/EchoServer.cpp index b29d817f0..927b8efac 100644 --- a/Net/samples/EchoServer/src/EchoServer.cpp +++ b/Net/samples/EchoServer/src/EchoServer.cpp @@ -1,228 +1,228 @@ -// -// EchoServer.cpp -// -// $Id: //poco/1.2/Net/samples/EchoServer/src/EchoServer.cpp#3 $ -// -// This sample demonstrates the SocketReactor and SocketAcceptor classes. -// -// 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/SocketAcceptor.h" -#include "Poco/Net/SocketNotification.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/NObserver.h" -#include "Poco/Exception.h" -#include "Poco/Thread.h" -#include "Poco/Util/ServerApplication.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/HelpFormatter.h" -#include - - -using Poco::Net::SocketReactor; -using Poco::Net::SocketAcceptor; -using Poco::Net::ReadableNotification; -using Poco::Net::ShutdownNotification; -using Poco::Net::ServerSocket; -using Poco::Net::StreamSocket; -using Poco::NObserver; -using Poco::AutoPtr; -using Poco::Thread; -using Poco::Util::ServerApplication; -using Poco::Util::Application; -using Poco::Util::Option; -using Poco::Util::OptionSet; -using Poco::Util::HelpFormatter; - - -class EchoServiceHandler -{ -public: - EchoServiceHandler(StreamSocket& socket, SocketReactor& reactor): - _socket(socket), - _reactor(reactor), - _pBuffer(new char[BUFFER_SIZE]) - { - Application& app = Application::instance(); - app.logger().information("Connection from " + socket.peerAddress().toString()); - - _reactor.addEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onReadable)); - _reactor.addEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onShutdown)); - } - - ~EchoServiceHandler() - { - Application& app = Application::instance(); - try - { - app.logger().information("Disconnecting " + _socket.peerAddress().toString()); - } - catch (...) - { - } - _reactor.removeEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onReadable)); - _reactor.removeEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onShutdown)); - delete [] _pBuffer; - } - - void onReadable(const AutoPtr& pNf) - { - int n = _socket.receiveBytes(_pBuffer, BUFFER_SIZE); - if (n > 0) - _socket.sendBytes(_pBuffer, n); - else - delete this; - } - - void onShutdown(const AutoPtr& pNf) - { - delete this; - } - -private: - enum - { - BUFFER_SIZE = 1024 - }; - - StreamSocket _socket; - SocketReactor& _reactor; - char* _pBuffer; -}; - - -class EchoServer: public Poco::Util::ServerApplication - /// The main application class. - /// - /// This class handles command-line arguments and - /// configuration files. - /// Start the EchoServer executable with the help - /// option (/help on Windows, --help on Unix) for - /// the available command line options. - /// - /// To use the sample configuration file (EchoServer.properties), - /// copy the file to the directory where the EchoServer executable - /// resides. If you start the debug version of the EchoServer - /// (EchoServerd[.exe]), you must also create a copy of the configuration - /// file named EchoServerd.properties. In the configuration file, you - /// can specify the port on which the server is listening (default - /// 9977) and the format of the date/time string sent back to the client. - /// - /// To test the EchoServer you can use any telnet client (telnet localhost 9977). -{ -public: - EchoServer(): _helpRequested(false) - { - } - - ~EchoServer() - { - } - -protected: - void initialize(Application& self) - { - loadConfiguration(); // load default configuration files, if present - ServerApplication::initialize(self); - } - - void uninitialize() - { - ServerApplication::uninitialize(); - } - - void defineOptions(OptionSet& options) - { - ServerApplication::defineOptions(options); - - options.addOption( - Option("help", "h", "display help information on command line arguments") - .required(false) - .repeatable(false)); - } - - void handleOption(const std::string& name, const std::string& value) - { - ServerApplication::handleOption(name, value); - - if (name == "help") - _helpRequested = true; - } - - void displayHelp() - { - HelpFormatter helpFormatter(options()); - helpFormatter.setCommand(commandName()); - helpFormatter.setUsage("OPTIONS"); - helpFormatter.setHeader("An echo server implemented using the Reactor and Acceptor patterns."); - helpFormatter.format(std::cout); - } - - int main(const std::vector& args) - { - if (_helpRequested) - { - displayHelp(); - } - else - { - // get parameters from configuration file - unsigned short port = (unsigned short) config().getInt("EchoServer.port", 9977); - - // set-up a server socket - ServerSocket svs(port); - // set-up a SocketReactor... - SocketReactor reactor; - // ... and a SocketAcceptor - SocketAcceptor acceptor(svs, reactor); - // run the reactor in its own thread so that we can wait for - // a termination request - Thread thread; - thread.start(reactor); - // wait for CTRL-C or kill - waitForTerminationRequest(); - // Stop the SocketReactor - reactor.stop(); - thread.join(); - } - return Application::EXIT_OK; - } - -private: - bool _helpRequested; -}; - - -int main(int argc, char** argv) -{ - EchoServer app; - return app.run(argc, argv); -} +// +// EchoServer.cpp +// +// $Id: //poco/1.2/Net/samples/EchoServer/src/EchoServer.cpp#3 $ +// +// This sample demonstrates the SocketReactor and SocketAcceptor classes. +// +// 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/SocketAcceptor.h" +#include "Poco/Net/SocketNotification.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/NObserver.h" +#include "Poco/Exception.h" +#include "Poco/Thread.h" +#include "Poco/Util/ServerApplication.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/HelpFormatter.h" +#include + + +using Poco::Net::SocketReactor; +using Poco::Net::SocketAcceptor; +using Poco::Net::ReadableNotification; +using Poco::Net::ShutdownNotification; +using Poco::Net::ServerSocket; +using Poco::Net::StreamSocket; +using Poco::NObserver; +using Poco::AutoPtr; +using Poco::Thread; +using Poco::Util::ServerApplication; +using Poco::Util::Application; +using Poco::Util::Option; +using Poco::Util::OptionSet; +using Poco::Util::HelpFormatter; + + +class EchoServiceHandler +{ +public: + EchoServiceHandler(StreamSocket& socket, SocketReactor& reactor): + _socket(socket), + _reactor(reactor), + _pBuffer(new char[BUFFER_SIZE]) + { + Application& app = Application::instance(); + app.logger().information("Connection from " + socket.peerAddress().toString()); + + _reactor.addEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onReadable)); + _reactor.addEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onShutdown)); + } + + ~EchoServiceHandler() + { + Application& app = Application::instance(); + try + { + app.logger().information("Disconnecting " + _socket.peerAddress().toString()); + } + catch (...) + { + } + _reactor.removeEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onReadable)); + _reactor.removeEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onShutdown)); + delete [] _pBuffer; + } + + void onReadable(const AutoPtr& pNf) + { + int n = _socket.receiveBytes(_pBuffer, BUFFER_SIZE); + if (n > 0) + _socket.sendBytes(_pBuffer, n); + else + delete this; + } + + void onShutdown(const AutoPtr& pNf) + { + delete this; + } + +private: + enum + { + BUFFER_SIZE = 1024 + }; + + StreamSocket _socket; + SocketReactor& _reactor; + char* _pBuffer; +}; + + +class EchoServer: public Poco::Util::ServerApplication + /// The main application class. + /// + /// This class handles command-line arguments and + /// configuration files. + /// Start the EchoServer executable with the help + /// option (/help on Windows, --help on Unix) for + /// the available command line options. + /// + /// To use the sample configuration file (EchoServer.properties), + /// copy the file to the directory where the EchoServer executable + /// resides. If you start the debug version of the EchoServer + /// (EchoServerd[.exe]), you must also create a copy of the configuration + /// file named EchoServerd.properties. In the configuration file, you + /// can specify the port on which the server is listening (default + /// 9977) and the format of the date/time string sent back to the client. + /// + /// To test the EchoServer you can use any telnet client (telnet localhost 9977). +{ +public: + EchoServer(): _helpRequested(false) + { + } + + ~EchoServer() + { + } + +protected: + void initialize(Application& self) + { + loadConfiguration(); // load default configuration files, if present + ServerApplication::initialize(self); + } + + void uninitialize() + { + ServerApplication::uninitialize(); + } + + void defineOptions(OptionSet& options) + { + ServerApplication::defineOptions(options); + + options.addOption( + Option("help", "h", "display help information on command line arguments") + .required(false) + .repeatable(false)); + } + + void handleOption(const std::string& name, const std::string& value) + { + ServerApplication::handleOption(name, value); + + if (name == "help") + _helpRequested = true; + } + + void displayHelp() + { + HelpFormatter helpFormatter(options()); + helpFormatter.setCommand(commandName()); + helpFormatter.setUsage("OPTIONS"); + helpFormatter.setHeader("An echo server implemented using the Reactor and Acceptor patterns."); + helpFormatter.format(std::cout); + } + + int main(const std::vector& args) + { + if (_helpRequested) + { + displayHelp(); + } + else + { + // get parameters from configuration file + unsigned short port = (unsigned short) config().getInt("EchoServer.port", 9977); + + // set-up a server socket + ServerSocket svs(port); + // set-up a SocketReactor... + SocketReactor reactor; + // ... and a SocketAcceptor + SocketAcceptor acceptor(svs, reactor); + // run the reactor in its own thread so that we can wait for + // a termination request + Thread thread; + thread.start(reactor); + // wait for CTRL-C or kill + waitForTerminationRequest(); + // Stop the SocketReactor + reactor.stop(); + thread.join(); + } + return Application::EXIT_OK; + } + +private: + bool _helpRequested; +}; + + +int main(int argc, char** argv) +{ + EchoServer app; + return app.run(argc, argv); +} diff --git a/Net/samples/HTTPFormServer/HTTPFormServer.properties b/Net/samples/HTTPFormServer/HTTPFormServer.properties index d32ffdc4f..0d86a6814 100644 --- a/Net/samples/HTTPFormServer/HTTPFormServer.properties +++ b/Net/samples/HTTPFormServer/HTTPFormServer.properties @@ -1,10 +1,10 @@ -# This is a sample configuration file for HTTPFormServer - -logging.loggers.root.channel.class = ConsoleChannel -logging.loggers.app.name = Application -logging.loggers.app.channel = c1 -logging.formatters.f1.class = PatternFormatter -logging.formatters.f1.pattern = [%p] %t -logging.channels.c1.class = ConsoleChannel -logging.channels.c1.formatter = f1 -HTTPFormServer.port = 9980 +# This is a sample configuration file for HTTPFormServer + +logging.loggers.root.channel.class = ConsoleChannel +logging.loggers.app.name = Application +logging.loggers.app.channel = c1 +logging.formatters.f1.class = PatternFormatter +logging.formatters.f1.pattern = [%p] %t +logging.channels.c1.class = ConsoleChannel +logging.channels.c1.formatter = f1 +HTTPFormServer.port = 9980 diff --git a/Net/samples/HTTPFormServer/HTTPFormServer.vmsbuild b/Net/samples/HTTPFormServer/HTTPFormServer.vmsbuild index 5d180e690..f22bd709b 100644 --- a/Net/samples/HTTPFormServer/HTTPFormServer.vmsbuild +++ b/Net/samples/HTTPFormServer/HTTPFormServer.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Net/samples/HTTPFormServer/HTTPFormServer.vmsbuild#1 $ -# -EXE=HTTPFormServer -HTTPFormServer - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Net/samples/HTTPFormServer/HTTPFormServer.vmsbuild#1 $ +# +EXE=HTTPFormServer +HTTPFormServer + diff --git a/Net/samples/HTTPFormServer/HTTPFormServer_vs71.vcproj b/Net/samples/HTTPFormServer/HTTPFormServer_vs71.vcproj index 9bb8e7734..e30e20507 100644 --- a/Net/samples/HTTPFormServer/HTTPFormServer_vs71.vcproj +++ b/Net/samples/HTTPFormServer/HTTPFormServer_vs71.vcproj @@ -1,152 +1,152 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/HTTPFormServer/HTTPFormServer_vs80.vcproj b/Net/samples/HTTPFormServer/HTTPFormServer_vs80.vcproj index 592170c64..1e379204d 100644 --- a/Net/samples/HTTPFormServer/HTTPFormServer_vs80.vcproj +++ b/Net/samples/HTTPFormServer/HTTPFormServer_vs80.vcproj @@ -1,217 +1,217 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/HTTPFormServer/Makefile b/Net/samples/HTTPFormServer/Makefile index b554cd7b2..22b22d870 100644 --- a/Net/samples/HTTPFormServer/Makefile +++ b/Net/samples/HTTPFormServer/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/HTTPFormServer/Makefile#1 $ -# -# Makefile for Poco HTTPFormServer -# - -include $(POCO_BASE)/build/rules/global - -objects = HTTPFormServer - -target = HTTPFormServer -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/HTTPFormServer/Makefile#1 $ +# +# Makefile for Poco HTTPFormServer +# + +include $(POCO_BASE)/build/rules/global + +objects = HTTPFormServer + +target = HTTPFormServer +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/HTTPFormServer/src/HTTPFormServer.cpp b/Net/samples/HTTPFormServer/src/HTTPFormServer.cpp index fbb344329..e164646fd 100644 --- a/Net/samples/HTTPFormServer/src/HTTPFormServer.cpp +++ b/Net/samples/HTTPFormServer/src/HTTPFormServer.cpp @@ -1,326 +1,326 @@ -// -// HTTPFormServer.cpp -// -// $Id: //poco/Main/Net/samples/HTTPFormServer/src/HTTPFormServer.cpp#5 $ -// -// This sample demonstrates the HTTPServer and HTMLForm classes. -// -// 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/HTTPServer.h" -#include "Poco/Net/HTTPRequestHandler.h" -#include "Poco/Net/HTTPRequestHandlerFactory.h" -#include "Poco/Net/HTTPServerParams.h" -#include "Poco/Net/HTTPServerRequest.h" -#include "Poco/Net/HTTPServerResponse.h" -#include "Poco/Net/HTTPServerParams.h" -#include "Poco/Net/HTMLForm.h" -#include "Poco/Net/PartHandler.h" -#include "Poco/Net/MessageHeader.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/CountingStream.h" -#include "Poco/NullStream.h" -#include "Poco/StreamCopier.h" -#include "Poco/Exception.h" -#include "Poco/Util/ServerApplication.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/HelpFormatter.h" -#include - - -using Poco::Net::ServerSocket; -using Poco::Net::HTTPRequestHandler; -using Poco::Net::HTTPRequestHandlerFactory; -using Poco::Net::HTTPServer; -using Poco::Net::HTTPServerRequest; -using Poco::Net::HTTPServerResponse; -using Poco::Net::HTTPServerParams; -using Poco::Net::MessageHeader; -using Poco::Net::HTMLForm; -using Poco::Net::NameValueCollection; -using Poco::Util::ServerApplication; -using Poco::Util::Application; -using Poco::Util::Option; -using Poco::Util::OptionSet; -using Poco::Util::HelpFormatter; -using Poco::CountingInputStream; -using Poco::NullOutputStream; -using Poco::StreamCopier; - - -class MyPartHandler: public Poco::Net::PartHandler -{ -public: - MyPartHandler(): - _length(0) - { - } - - void handlePart(const MessageHeader& header, std::istream& stream) - { - _type = header.get("Content-Type", "(unspecified)"); - if (header.has("Content-Disposition")) - { - std::string disp; - NameValueCollection params; - MessageHeader::splitParameters(header["Content-Disposition"], disp, params); - _name = params.get("name", "(unnamed)"); - _fileName = params.get("filename", "(unnamed)"); - } - - CountingInputStream istr(stream); - NullOutputStream ostr; - StreamCopier::copyStream(istr, ostr); - _length = istr.chars(); - } - - int length() const - { - return _length; - } - - const std::string& name() const - { - return _name; - } - - const std::string& fileName() const - { - return _fileName; - } - - const std::string& contentType() const - { - return _type; - } - -private: - int _length; - std::string _type; - std::string _name; - std::string _fileName; -}; - - -class FormRequestHandler: public HTTPRequestHandler - /// Return a HTML document with the current date and time. -{ -public: - FormRequestHandler() - { - } - - void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) - { - Application& app = Application::instance(); - app.logger().information("Request from " + request.clientAddress().toString()); - - MyPartHandler partHandler; - HTMLForm form(request, request.stream(), partHandler); - - response.setChunkedTransferEncoding(true); - response.setContentType("text/html"); - - std::ostream& ostr = response.send(); - - ostr << - "\n" - "\n" - "POCO Form Server Sample\n" - "\n" - "\n" - "

POCO Form Server Sample

\n" - "

GET Form

\n" - "
\n" - "\n" - "\n" - "
\n" - "

POST Form

\n" - "
\n" - "\n" - "\n" - "
\n" - "

File Upload

\n" - "
\n" - " \n" - "\n" - "
\n"; - - ostr << "

Request

\n"; - ostr << "Method: " << request.getMethod() << "
\n"; - ostr << "URI: " << request.getURI() << "
\n"; - NameValueCollection::ConstIterator it = request.begin(); - NameValueCollection::ConstIterator end = request.end(); - for (; it != end; ++it) - { - ostr << it->first << ": " << it->second << "
\n"; - } - ostr << "

"; - - if (!form.empty()) - { - ostr << "

Form

\n"; - it = form.begin(); - end = form.end(); - for (; it != end; ++it) - { - ostr << it->first << ": " << it->second << "
\n"; - } - ostr << "

"; - } - - if (!partHandler.name().empty()) - { - ostr << "

Upload

\n"; - ostr << "Name: " << partHandler.name() << "
\n"; - ostr << "File Name: " << partHandler.fileName() << "
\n"; - ostr << "Type: " << partHandler.contentType() << "
\n"; - ostr << "Size: " << partHandler.length() << "
\n"; - ostr << "

"; - } - ostr << "\n"; - } -}; - - -class FormRequestHandlerFactory: public HTTPRequestHandlerFactory -{ -public: - FormRequestHandlerFactory() - { - } - - HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) - { - return new FormRequestHandler; - } -}; - - -class HTTPFormServer: public Poco::Util::ServerApplication - /// The main application class. - /// - /// This class handles command-line arguments and - /// configuration files. - /// Start the HTTPFormServer executable with the help - /// option (/help on Windows, --help on Unix) for - /// the available command line options. - /// - /// To use the sample configuration file (HTTPFormServer.properties), - /// copy the file to the directory where the HTTPFormServer executable - /// resides. If you start the debug version of the HTTPFormServer - /// (HTTPFormServerd[.exe]), you must also create a copy of the configuration - /// file named HTTPFormServerd.properties. In the configuration file, you - /// can specify the port on which the server is listening (default - /// 9980) and the format of the date/Form string sent back to the client. - /// - /// To test the FormServer you can use any web browser (http://localhost:9980/). -{ -public: - HTTPFormServer(): _helpRequested(false) - { - } - - ~HTTPFormServer() - { - } - -protected: - void initialize(Application& self) - { - loadConfiguration(); // load default configuration files, if present - ServerApplication::initialize(self); - } - - void uninitialize() - { - ServerApplication::uninitialize(); - } - - void defineOptions(OptionSet& options) - { - ServerApplication::defineOptions(options); - - options.addOption( - Option("help", "h", "display help information on command line arguments") - .required(false) - .repeatable(false)); - } - - void handleOption(const std::string& name, const std::string& value) - { - ServerApplication::handleOption(name, value); - - if (name == "help") - _helpRequested = true; - } - - void displayHelp() - { - HelpFormatter helpFormatter(options()); - helpFormatter.setCommand(commandName()); - helpFormatter.setUsage("OPTIONS"); - helpFormatter.setHeader("A web server that shows how to work with HTML forms."); - helpFormatter.format(std::cout); - } - - int main(const std::vector& args) - { - if (_helpRequested) - { - displayHelp(); - } - else - { - unsigned short port = (unsigned short) config().getInt("HTTPFormServer.port", 9980); - - // set-up a server socket - ServerSocket svs(port); - // set-up a HTTPServer instance - HTTPServer srv(new FormRequestHandlerFactory, svs, new HTTPServerParams); - // start the HTTPServer - srv.start(); - // wait for CTRL-C or kill - waitForTerminationRequest(); - // Stop the HTTPServer - srv.stop(); - } - return Application::EXIT_OK; - } - -private: - bool _helpRequested; -}; - - -int main(int argc, char** argv) -{ - HTTPFormServer app; - return app.run(argc, argv); -} +// +// HTTPFormServer.cpp +// +// $Id: //poco/Main/Net/samples/HTTPFormServer/src/HTTPFormServer.cpp#5 $ +// +// This sample demonstrates the HTTPServer and HTMLForm classes. +// +// 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/HTTPServer.h" +#include "Poco/Net/HTTPRequestHandler.h" +#include "Poco/Net/HTTPRequestHandlerFactory.h" +#include "Poco/Net/HTTPServerParams.h" +#include "Poco/Net/HTTPServerRequest.h" +#include "Poco/Net/HTTPServerResponse.h" +#include "Poco/Net/HTTPServerParams.h" +#include "Poco/Net/HTMLForm.h" +#include "Poco/Net/PartHandler.h" +#include "Poco/Net/MessageHeader.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/CountingStream.h" +#include "Poco/NullStream.h" +#include "Poco/StreamCopier.h" +#include "Poco/Exception.h" +#include "Poco/Util/ServerApplication.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/HelpFormatter.h" +#include + + +using Poco::Net::ServerSocket; +using Poco::Net::HTTPRequestHandler; +using Poco::Net::HTTPRequestHandlerFactory; +using Poco::Net::HTTPServer; +using Poco::Net::HTTPServerRequest; +using Poco::Net::HTTPServerResponse; +using Poco::Net::HTTPServerParams; +using Poco::Net::MessageHeader; +using Poco::Net::HTMLForm; +using Poco::Net::NameValueCollection; +using Poco::Util::ServerApplication; +using Poco::Util::Application; +using Poco::Util::Option; +using Poco::Util::OptionSet; +using Poco::Util::HelpFormatter; +using Poco::CountingInputStream; +using Poco::NullOutputStream; +using Poco::StreamCopier; + + +class MyPartHandler: public Poco::Net::PartHandler +{ +public: + MyPartHandler(): + _length(0) + { + } + + void handlePart(const MessageHeader& header, std::istream& stream) + { + _type = header.get("Content-Type", "(unspecified)"); + if (header.has("Content-Disposition")) + { + std::string disp; + NameValueCollection params; + MessageHeader::splitParameters(header["Content-Disposition"], disp, params); + _name = params.get("name", "(unnamed)"); + _fileName = params.get("filename", "(unnamed)"); + } + + CountingInputStream istr(stream); + NullOutputStream ostr; + StreamCopier::copyStream(istr, ostr); + _length = istr.chars(); + } + + int length() const + { + return _length; + } + + const std::string& name() const + { + return _name; + } + + const std::string& fileName() const + { + return _fileName; + } + + const std::string& contentType() const + { + return _type; + } + +private: + int _length; + std::string _type; + std::string _name; + std::string _fileName; +}; + + +class FormRequestHandler: public HTTPRequestHandler + /// Return a HTML document with the current date and time. +{ +public: + FormRequestHandler() + { + } + + void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) + { + Application& app = Application::instance(); + app.logger().information("Request from " + request.clientAddress().toString()); + + MyPartHandler partHandler; + HTMLForm form(request, request.stream(), partHandler); + + response.setChunkedTransferEncoding(true); + response.setContentType("text/html"); + + std::ostream& ostr = response.send(); + + ostr << + "\n" + "\n" + "POCO Form Server Sample\n" + "\n" + "\n" + "

POCO Form Server Sample

\n" + "

GET Form

\n" + "
\n" + "\n" + "\n" + "
\n" + "

POST Form

\n" + "
\n" + "\n" + "\n" + "
\n" + "

File Upload

\n" + "
\n" + " \n" + "\n" + "
\n"; + + ostr << "

Request

\n"; + ostr << "Method: " << request.getMethod() << "
\n"; + ostr << "URI: " << request.getURI() << "
\n"; + NameValueCollection::ConstIterator it = request.begin(); + NameValueCollection::ConstIterator end = request.end(); + for (; it != end; ++it) + { + ostr << it->first << ": " << it->second << "
\n"; + } + ostr << "

"; + + if (!form.empty()) + { + ostr << "

Form

\n"; + it = form.begin(); + end = form.end(); + for (; it != end; ++it) + { + ostr << it->first << ": " << it->second << "
\n"; + } + ostr << "

"; + } + + if (!partHandler.name().empty()) + { + ostr << "

Upload

\n"; + ostr << "Name: " << partHandler.name() << "
\n"; + ostr << "File Name: " << partHandler.fileName() << "
\n"; + ostr << "Type: " << partHandler.contentType() << "
\n"; + ostr << "Size: " << partHandler.length() << "
\n"; + ostr << "

"; + } + ostr << "\n"; + } +}; + + +class FormRequestHandlerFactory: public HTTPRequestHandlerFactory +{ +public: + FormRequestHandlerFactory() + { + } + + HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) + { + return new FormRequestHandler; + } +}; + + +class HTTPFormServer: public Poco::Util::ServerApplication + /// The main application class. + /// + /// This class handles command-line arguments and + /// configuration files. + /// Start the HTTPFormServer executable with the help + /// option (/help on Windows, --help on Unix) for + /// the available command line options. + /// + /// To use the sample configuration file (HTTPFormServer.properties), + /// copy the file to the directory where the HTTPFormServer executable + /// resides. If you start the debug version of the HTTPFormServer + /// (HTTPFormServerd[.exe]), you must also create a copy of the configuration + /// file named HTTPFormServerd.properties. In the configuration file, you + /// can specify the port on which the server is listening (default + /// 9980) and the format of the date/Form string sent back to the client. + /// + /// To test the FormServer you can use any web browser (http://localhost:9980/). +{ +public: + HTTPFormServer(): _helpRequested(false) + { + } + + ~HTTPFormServer() + { + } + +protected: + void initialize(Application& self) + { + loadConfiguration(); // load default configuration files, if present + ServerApplication::initialize(self); + } + + void uninitialize() + { + ServerApplication::uninitialize(); + } + + void defineOptions(OptionSet& options) + { + ServerApplication::defineOptions(options); + + options.addOption( + Option("help", "h", "display help information on command line arguments") + .required(false) + .repeatable(false)); + } + + void handleOption(const std::string& name, const std::string& value) + { + ServerApplication::handleOption(name, value); + + if (name == "help") + _helpRequested = true; + } + + void displayHelp() + { + HelpFormatter helpFormatter(options()); + helpFormatter.setCommand(commandName()); + helpFormatter.setUsage("OPTIONS"); + helpFormatter.setHeader("A web server that shows how to work with HTML forms."); + helpFormatter.format(std::cout); + } + + int main(const std::vector& args) + { + if (_helpRequested) + { + displayHelp(); + } + else + { + unsigned short port = (unsigned short) config().getInt("HTTPFormServer.port", 9980); + + // set-up a server socket + ServerSocket svs(port); + // set-up a HTTPServer instance + HTTPServer srv(new FormRequestHandlerFactory, svs, new HTTPServerParams); + // start the HTTPServer + srv.start(); + // wait for CTRL-C or kill + waitForTerminationRequest(); + // Stop the HTTPServer + srv.stop(); + } + return Application::EXIT_OK; + } + +private: + bool _helpRequested; +}; + + +int main(int argc, char** argv) +{ + HTTPFormServer app; + return app.run(argc, argv); +} diff --git a/Net/samples/HTTPLoadTest/HTTPLoadTest.vmsbuild b/Net/samples/HTTPLoadTest/HTTPLoadTest.vmsbuild index a690def50..74f119a31 100644 --- a/Net/samples/HTTPLoadTest/HTTPLoadTest.vmsbuild +++ b/Net/samples/HTTPLoadTest/HTTPLoadTest.vmsbuild @@ -1,7 +1,7 @@ -# -# HTTPLoadTest.vmsbuild -# -# $Id: //poco/1.2/Net/samples/HTTPLoadTest/HTTPLoadTest.vmsbuild#1 $ -# -EXE=HTTPLoadTest -HTTPLoadTest +# +# HTTPLoadTest.vmsbuild +# +# $Id: //poco/1.2/Net/samples/HTTPLoadTest/HTTPLoadTest.vmsbuild#1 $ +# +EXE=HTTPLoadTest +HTTPLoadTest diff --git a/Net/samples/HTTPLoadTest/HTTPLoadTest_vs71.vcproj b/Net/samples/HTTPLoadTest/HTTPLoadTest_vs71.vcproj index 8fa45a471..7529f4d74 100644 --- a/Net/samples/HTTPLoadTest/HTTPLoadTest_vs71.vcproj +++ b/Net/samples/HTTPLoadTest/HTTPLoadTest_vs71.vcproj @@ -1,145 +1,145 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/HTTPLoadTest/HTTPLoadTest_vs80.vcproj b/Net/samples/HTTPLoadTest/HTTPLoadTest_vs80.vcproj index 597370997..ba73d4f8c 100644 --- a/Net/samples/HTTPLoadTest/HTTPLoadTest_vs80.vcproj +++ b/Net/samples/HTTPLoadTest/HTTPLoadTest_vs80.vcproj @@ -1,209 +1,209 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/HTTPLoadTest/Makefile b/Net/samples/HTTPLoadTest/Makefile index cb36bcbda..dd74d76dd 100644 --- a/Net/samples/HTTPLoadTest/Makefile +++ b/Net/samples/HTTPLoadTest/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/HTTPLoadTest/Makefile#1 $ -# -# Makefile for Poco HTTPLoadTest -# - -include $(POCO_BASE)/build/rules/global - -objects = HTTPLoadTest - -target = HTTPLoadTest -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/HTTPLoadTest/Makefile#1 $ +# +# Makefile for Poco HTTPLoadTest +# + +include $(POCO_BASE)/build/rules/global + +objects = HTTPLoadTest + +target = HTTPLoadTest +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/HTTPLoadTest/src/HTTPLoadTest.cpp b/Net/samples/HTTPLoadTest/src/HTTPLoadTest.cpp index eeeec7e5c..6c088a6ec 100644 --- a/Net/samples/HTTPLoadTest/src/HTTPLoadTest.cpp +++ b/Net/samples/HTTPLoadTest/src/HTTPLoadTest.cpp @@ -1,388 +1,388 @@ -// -// HTTPLoadTest.cpp -// -// $Id: //poco/1.2/Net/samples/HTTPLoadTest/src/HTTPLoadTest.cpp#1 $ -// -// This sample demonstrates the HTTPClientSession 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. -// - - -#include "Poco/Net/HTTPClientSession.h" -#include "Poco/Net/HTTPRequest.h" -#include "Poco/Net/HTTPResponse.h" -#include "Poco/Net/HTTPCookie.h" -#include "Poco/Net/NameValueCollection.h" -#include "Poco/Path.h" -#include "Poco/URI.h" -#include "Poco/AutoPtr.h" -#include "Poco/Thread.h" -#include "Poco/Mutex.h" -#include "Poco/Runnable.h" -#include "Poco/Stopwatch.h" -#include "Poco/NumberParser.h" -#include "Poco/Exception.h" -#include "Poco/Util/Application.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/HelpFormatter.h" -#include "Poco/Util/AbstractConfiguration.h" -#include - - -using Poco::Net::HTTPClientSession; -using Poco::Net::HTTPRequest; -using Poco::Net::HTTPResponse; -using Poco::Net::HTTPMessage; -using Poco::Net::HTTPCookie; -using Poco::Net::NameValueCollection; -using Poco::Util::Application; -using Poco::Util::Option; -using Poco::Util::OptionSet; -using Poco::Util::HelpFormatter; -using Poco::Util::AbstractConfiguration; -using Poco::AutoPtr; -using Poco::Thread; -using Poco::FastMutex; -using Poco::Runnable; -using Poco::Stopwatch; -using Poco::NumberParser; -using Poco::Path; -using Poco::URI; -using Poco::Exception; - -class HTTPClient : public Runnable -{ -public: - HTTPClient(const URI& uri, int repetitions, bool cookies=false, bool verbose=false): - _uri(uri), - _cookies(cookies), - _verbose(verbose), - _repetitions(repetitions), - _usec(0), - _success(0) - { - _gRepetitions += _repetitions; - } - - ~HTTPClient() - { - } - - void run() - { - Stopwatch sw; - std::vector cookies; - - for (int i = 0; i < _repetitions; ++i) - { - try - { - int usec = 0; - std::string path(_uri.getPathAndQuery()); - if (path.empty()) path = "/"; - - HTTPClientSession session(_uri.getHost(), _uri.getPort()); - HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1); - - if (_cookies) - { - NameValueCollection nvc; - std::vector::iterator it = cookies.begin(); - for(; it != cookies.end(); ++it) - nvc.add((*it).getName(), (*it).getValue()); - - req.setCookies(nvc); - } - - HTTPResponse res; - sw.restart(); - session.sendRequest(req); - std::istream& rs = session.receiveResponse(res); - sw.stop(); - _success += HTTPResponse::HTTP_OK == res.getStatus() ? 1 : 0; - if (_cookies) res.getCookies(cookies); - usec = sw.elapsed(); - - if (_verbose) - { - FastMutex::ScopedLock lock(_mutex); - std::cout - << _uri.toString() << ' ' << res.getStatus() << ' ' << res.getReason() - << ' ' << usec/1000.0 << "ms" << std::endl; - } - - _usec += usec; - } - catch (Exception& exc) - { - FastMutex::ScopedLock lock(_mutex); - std::cerr << exc.displayText() << std::endl; - } - } - - { - FastMutex::ScopedLock lock(_mutex); - _gSuccess += _success; - _gUsec += _usec; - } - if (_verbose) - printStats(_uri.toString(), _repetitions, _success, _usec); - } - - static void printStats(std::string uri, int repetitions, int success, Poco::UInt64 usec); - static int totalAttempts(); - static Poco::UInt64 totalMicroseconds(); - static int totalSuccessCount(); - -private: - HTTPClient(); - - URI _uri; - bool _verbose; - bool _cookies; - int _repetitions; - Poco::UInt64 _usec; - int _success; - static int _gRepetitions; - static Poco::UInt64 _gUsec; - static int _gSuccess; - static FastMutex _mutex; -}; - -FastMutex HTTPClient::_mutex; -int HTTPClient::_gRepetitions; -Poco::UInt64 HTTPClient::_gUsec; -int HTTPClient::_gSuccess; - -int HTTPClient::totalAttempts() -{ - return _gRepetitions; -} - -Poco::UInt64 HTTPClient::totalMicroseconds() -{ - return _gUsec; -} - -int HTTPClient::totalSuccessCount() -{ - return _gSuccess; -} - -void HTTPClient::printStats(std::string uri, int repetitions, int success, Poco::UInt64 usec) -{ - FastMutex::ScopedLock lock(_mutex); - - std::cout << std::endl << "--------------" << std::endl - << "Statistics for " << uri << std::endl << "--------------" - << std::endl - << repetitions << " attempts, " << success << " succesful (" - << ((float) success / (float) repetitions) * 100.0 << "%)" << std::endl - << "Avg response time: " << ((float) usec / (float) repetitions) / 1000.0 << "ms, " << std::endl - << "Avg requests/second handled: " << ((float) success /((float) usec / 1000000.0)) << std::endl - << "Total time: " << (float) usec / 1000000.0 << std::endl; -} - -class HTTPLoadTest: public Application - /// This sample demonstrates some of the features of the Poco::Util::Application class, - /// such as configuration file handling and command line arguments processing. - /// - /// Try HTTPLoadTest --help (on Unix platforms) or HTTPLoadTest /help (elsewhere) for - /// more information. -{ -public: - HTTPLoadTest(): - _helpRequested(false), - _repetitions(1), - _threads(1), - _verbose(false), - _cookies(false) - { - } - -protected: - void initialize(Application& self) - { - loadConfiguration(); // load default configuration files, if present - Application::initialize(self); - // add your own initialization code here - } - - void uninitialize() - { - // add your own uninitialization code here - Application::uninitialize(); - } - - void reinitialize(Application& self) - { - Application::reinitialize(self); - // add your own reinitialization code here - } - - void defineOptions(OptionSet& options) - { - Application::defineOptions(options); - - options.addOption( - Option("help", "h", "display help information on command line arguments") - .required(false) - .repeatable(false)); - - options.addOption( - Option("verbose", "v", "display messages on stdout") - .required(false) - .repeatable(false)); - - options.addOption( - Option("cookies", "c", "resend cookies") - .required(false) - .repeatable(false)); - - options.addOption( - Option("uri", "u", "HTTP URI") - .required(true) - .repeatable(false) - .argument("uri")); - - options.addOption( - Option("repetitions", "r", "fetch repetitions") - .required(false) - .repeatable(false) - .argument("repetitions")); - - options.addOption( - Option("threads", "t", "thread count") - .required(false) - .repeatable(false) - .argument("threads")); - } - - void handleOption(const std::string& name, const std::string& value) - { - Application::handleOption(name, value); - - if (name == "help") - _helpRequested = true; - else if (name == "verbose") - _verbose = true; - else if (name == "cookies") - _cookies = true; - else if (name == "uri") - _uri = value; - else if (name == "repetitions") - _repetitions = NumberParser::parse(value); - else if (name == "threads") - _threads = NumberParser::parse(value); - } - - void displayHelp() - { - HelpFormatter helpFormatter(options()); - helpFormatter.setCommand(commandName()); - helpFormatter.setUsage("OPTIONS"); - helpFormatter.setHeader("A sample application that demonstrates some of the features of the Poco::Util::Application class."); - helpFormatter.format(std::cout); - } - - void defineProperty(const std::string& def) - { - std::string name; - std::string value; - std::string::size_type pos = def.find('='); - if (pos != std::string::npos) - { - name.assign(def, 0, pos); - value.assign(def, pos + 1, def.length() - pos); - } - else name = def; - config().setString(name, value); - } - - int main(const std::vector& args) - { - if (_helpRequested) - { - displayHelp(); - } - else - { - URI uri(_uri); - std::vector threads; - - Stopwatch sw; - sw.start(); - for (int i = 0; i < _threads; ++i) - { - Thread* pt = new Thread(_uri); - poco_check_ptr(pt); - threads.push_back(pt); - HTTPClient* pHTTPClient = new HTTPClient(uri, _repetitions, _cookies, _verbose); - poco_check_ptr(pHTTPClient); - threads.back()->start(*pHTTPClient); - } - - std::vector::iterator it = threads.begin(); - for(; it != threads.end(); ++it) - { - (*it)->join(); - delete *it; - } - sw.stop(); - - HTTPClient::printStats(_uri, HTTPClient::totalAttempts(), HTTPClient::totalSuccessCount(), sw.elapsed()); - } - - return Application::EXIT_OK; - } - -private: - bool _helpRequested; - bool _verbose; - bool _cookies; - std::string _uri; - int _repetitions; - int _threads; -}; - - -int main(int argc, char** argv) -{ - AutoPtr pApp = new HTTPLoadTest; - try - { - pApp->init(argc, argv); - } - catch (Poco::Exception& exc) - { - pApp->logger().log(exc); - return Application::EXIT_CONFIG; - } - return pApp->run(); -} - +// +// HTTPLoadTest.cpp +// +// $Id: //poco/1.2/Net/samples/HTTPLoadTest/src/HTTPLoadTest.cpp#1 $ +// +// This sample demonstrates the HTTPClientSession 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. +// + + +#include "Poco/Net/HTTPClientSession.h" +#include "Poco/Net/HTTPRequest.h" +#include "Poco/Net/HTTPResponse.h" +#include "Poco/Net/HTTPCookie.h" +#include "Poco/Net/NameValueCollection.h" +#include "Poco/Path.h" +#include "Poco/URI.h" +#include "Poco/AutoPtr.h" +#include "Poco/Thread.h" +#include "Poco/Mutex.h" +#include "Poco/Runnable.h" +#include "Poco/Stopwatch.h" +#include "Poco/NumberParser.h" +#include "Poco/Exception.h" +#include "Poco/Util/Application.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/HelpFormatter.h" +#include "Poco/Util/AbstractConfiguration.h" +#include + + +using Poco::Net::HTTPClientSession; +using Poco::Net::HTTPRequest; +using Poco::Net::HTTPResponse; +using Poco::Net::HTTPMessage; +using Poco::Net::HTTPCookie; +using Poco::Net::NameValueCollection; +using Poco::Util::Application; +using Poco::Util::Option; +using Poco::Util::OptionSet; +using Poco::Util::HelpFormatter; +using Poco::Util::AbstractConfiguration; +using Poco::AutoPtr; +using Poco::Thread; +using Poco::FastMutex; +using Poco::Runnable; +using Poco::Stopwatch; +using Poco::NumberParser; +using Poco::Path; +using Poco::URI; +using Poco::Exception; + +class HTTPClient : public Runnable +{ +public: + HTTPClient(const URI& uri, int repetitions, bool cookies=false, bool verbose=false): + _uri(uri), + _cookies(cookies), + _verbose(verbose), + _repetitions(repetitions), + _usec(0), + _success(0) + { + _gRepetitions += _repetitions; + } + + ~HTTPClient() + { + } + + void run() + { + Stopwatch sw; + std::vector cookies; + + for (int i = 0; i < _repetitions; ++i) + { + try + { + int usec = 0; + std::string path(_uri.getPathAndQuery()); + if (path.empty()) path = "/"; + + HTTPClientSession session(_uri.getHost(), _uri.getPort()); + HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1); + + if (_cookies) + { + NameValueCollection nvc; + std::vector::iterator it = cookies.begin(); + for(; it != cookies.end(); ++it) + nvc.add((*it).getName(), (*it).getValue()); + + req.setCookies(nvc); + } + + HTTPResponse res; + sw.restart(); + session.sendRequest(req); + std::istream& rs = session.receiveResponse(res); + sw.stop(); + _success += HTTPResponse::HTTP_OK == res.getStatus() ? 1 : 0; + if (_cookies) res.getCookies(cookies); + usec = sw.elapsed(); + + if (_verbose) + { + FastMutex::ScopedLock lock(_mutex); + std::cout + << _uri.toString() << ' ' << res.getStatus() << ' ' << res.getReason() + << ' ' << usec/1000.0 << "ms" << std::endl; + } + + _usec += usec; + } + catch (Exception& exc) + { + FastMutex::ScopedLock lock(_mutex); + std::cerr << exc.displayText() << std::endl; + } + } + + { + FastMutex::ScopedLock lock(_mutex); + _gSuccess += _success; + _gUsec += _usec; + } + if (_verbose) + printStats(_uri.toString(), _repetitions, _success, _usec); + } + + static void printStats(std::string uri, int repetitions, int success, Poco::UInt64 usec); + static int totalAttempts(); + static Poco::UInt64 totalMicroseconds(); + static int totalSuccessCount(); + +private: + HTTPClient(); + + URI _uri; + bool _verbose; + bool _cookies; + int _repetitions; + Poco::UInt64 _usec; + int _success; + static int _gRepetitions; + static Poco::UInt64 _gUsec; + static int _gSuccess; + static FastMutex _mutex; +}; + +FastMutex HTTPClient::_mutex; +int HTTPClient::_gRepetitions; +Poco::UInt64 HTTPClient::_gUsec; +int HTTPClient::_gSuccess; + +int HTTPClient::totalAttempts() +{ + return _gRepetitions; +} + +Poco::UInt64 HTTPClient::totalMicroseconds() +{ + return _gUsec; +} + +int HTTPClient::totalSuccessCount() +{ + return _gSuccess; +} + +void HTTPClient::printStats(std::string uri, int repetitions, int success, Poco::UInt64 usec) +{ + FastMutex::ScopedLock lock(_mutex); + + std::cout << std::endl << "--------------" << std::endl + << "Statistics for " << uri << std::endl << "--------------" + << std::endl + << repetitions << " attempts, " << success << " succesful (" + << ((float) success / (float) repetitions) * 100.0 << "%)" << std::endl + << "Avg response time: " << ((float) usec / (float) repetitions) / 1000.0 << "ms, " << std::endl + << "Avg requests/second handled: " << ((float) success /((float) usec / 1000000.0)) << std::endl + << "Total time: " << (float) usec / 1000000.0 << std::endl; +} + +class HTTPLoadTest: public Application + /// This sample demonstrates some of the features of the Poco::Util::Application class, + /// such as configuration file handling and command line arguments processing. + /// + /// Try HTTPLoadTest --help (on Unix platforms) or HTTPLoadTest /help (elsewhere) for + /// more information. +{ +public: + HTTPLoadTest(): + _helpRequested(false), + _repetitions(1), + _threads(1), + _verbose(false), + _cookies(false) + { + } + +protected: + void initialize(Application& self) + { + loadConfiguration(); // load default configuration files, if present + Application::initialize(self); + // add your own initialization code here + } + + void uninitialize() + { + // add your own uninitialization code here + Application::uninitialize(); + } + + void reinitialize(Application& self) + { + Application::reinitialize(self); + // add your own reinitialization code here + } + + void defineOptions(OptionSet& options) + { + Application::defineOptions(options); + + options.addOption( + Option("help", "h", "display help information on command line arguments") + .required(false) + .repeatable(false)); + + options.addOption( + Option("verbose", "v", "display messages on stdout") + .required(false) + .repeatable(false)); + + options.addOption( + Option("cookies", "c", "resend cookies") + .required(false) + .repeatable(false)); + + options.addOption( + Option("uri", "u", "HTTP URI") + .required(true) + .repeatable(false) + .argument("uri")); + + options.addOption( + Option("repetitions", "r", "fetch repetitions") + .required(false) + .repeatable(false) + .argument("repetitions")); + + options.addOption( + Option("threads", "t", "thread count") + .required(false) + .repeatable(false) + .argument("threads")); + } + + void handleOption(const std::string& name, const std::string& value) + { + Application::handleOption(name, value); + + if (name == "help") + _helpRequested = true; + else if (name == "verbose") + _verbose = true; + else if (name == "cookies") + _cookies = true; + else if (name == "uri") + _uri = value; + else if (name == "repetitions") + _repetitions = NumberParser::parse(value); + else if (name == "threads") + _threads = NumberParser::parse(value); + } + + void displayHelp() + { + HelpFormatter helpFormatter(options()); + helpFormatter.setCommand(commandName()); + helpFormatter.setUsage("OPTIONS"); + helpFormatter.setHeader("A sample application that demonstrates some of the features of the Poco::Util::Application class."); + helpFormatter.format(std::cout); + } + + void defineProperty(const std::string& def) + { + std::string name; + std::string value; + std::string::size_type pos = def.find('='); + if (pos != std::string::npos) + { + name.assign(def, 0, pos); + value.assign(def, pos + 1, def.length() - pos); + } + else name = def; + config().setString(name, value); + } + + int main(const std::vector& args) + { + if (_helpRequested) + { + displayHelp(); + } + else + { + URI uri(_uri); + std::vector threads; + + Stopwatch sw; + sw.start(); + for (int i = 0; i < _threads; ++i) + { + Thread* pt = new Thread(_uri); + poco_check_ptr(pt); + threads.push_back(pt); + HTTPClient* pHTTPClient = new HTTPClient(uri, _repetitions, _cookies, _verbose); + poco_check_ptr(pHTTPClient); + threads.back()->start(*pHTTPClient); + } + + std::vector::iterator it = threads.begin(); + for(; it != threads.end(); ++it) + { + (*it)->join(); + delete *it; + } + sw.stop(); + + HTTPClient::printStats(_uri, HTTPClient::totalAttempts(), HTTPClient::totalSuccessCount(), sw.elapsed()); + } + + return Application::EXIT_OK; + } + +private: + bool _helpRequested; + bool _verbose; + bool _cookies; + std::string _uri; + int _repetitions; + int _threads; +}; + + +int main(int argc, char** argv) +{ + AutoPtr pApp = new HTTPLoadTest; + try + { + pApp->init(argc, argv); + } + catch (Poco::Exception& exc) + { + pApp->logger().log(exc); + return Application::EXIT_CONFIG; + } + return pApp->run(); +} + diff --git a/Net/samples/HTTPTimeServer/HTTPTimeServer.properties b/Net/samples/HTTPTimeServer/HTTPTimeServer.properties index deaa2e8b7..2db69e5d0 100644 --- a/Net/samples/HTTPTimeServer/HTTPTimeServer.properties +++ b/Net/samples/HTTPTimeServer/HTTPTimeServer.properties @@ -1,13 +1,13 @@ -# This is a sample configuration file for HTTPTimeServer - -logging.loggers.root.channel.class = ConsoleChannel -logging.loggers.app.name = Application -logging.loggers.app.channel = c1 -logging.formatters.f1.class = PatternFormatter -logging.formatters.f1.pattern = [%p] %t -logging.channels.c1.class = ConsoleChannel -logging.channels.c1.formatter = f1 -HTTPTimeServer.format = %W, %e %b %y %H:%M:%S %Z -HTTPTimeServer.port = 9980 -HTTPTimeServer.maxQueued = 100 -HTTPTimeServer.maxThreads = 200 +# This is a sample configuration file for HTTPTimeServer + +logging.loggers.root.channel.class = ConsoleChannel +logging.loggers.app.name = Application +logging.loggers.app.channel = c1 +logging.formatters.f1.class = PatternFormatter +logging.formatters.f1.pattern = [%p] %t +logging.channels.c1.class = ConsoleChannel +logging.channels.c1.formatter = f1 +HTTPTimeServer.format = %W, %e %b %y %H:%M:%S %Z +HTTPTimeServer.port = 9980 +HTTPTimeServer.maxQueued = 100 +HTTPTimeServer.maxThreads = 200 diff --git a/Net/samples/HTTPTimeServer/HTTPTimeServer.vmsbuild b/Net/samples/HTTPTimeServer/HTTPTimeServer.vmsbuild index 2a2e57dd6..f2f5206a9 100644 --- a/Net/samples/HTTPTimeServer/HTTPTimeServer.vmsbuild +++ b/Net/samples/HTTPTimeServer/HTTPTimeServer.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Net/samples/HTTPTimeServer/HTTPTimeServer.vmsbuild#1 $ -# -EXE=HTTPTimeServer -HTTPTimeServer - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Net/samples/HTTPTimeServer/HTTPTimeServer.vmsbuild#1 $ +# +EXE=HTTPTimeServer +HTTPTimeServer + diff --git a/Net/samples/HTTPTimeServer/HTTPTimeServer_vs71.vcproj b/Net/samples/HTTPTimeServer/HTTPTimeServer_vs71.vcproj index 2a153eb03..31b62cebd 100644 --- a/Net/samples/HTTPTimeServer/HTTPTimeServer_vs71.vcproj +++ b/Net/samples/HTTPTimeServer/HTTPTimeServer_vs71.vcproj @@ -1,152 +1,152 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/HTTPTimeServer/HTTPTimeServer_vs80.vcproj b/Net/samples/HTTPTimeServer/HTTPTimeServer_vs80.vcproj index 72ffd6df0..c22293eff 100644 --- a/Net/samples/HTTPTimeServer/HTTPTimeServer_vs80.vcproj +++ b/Net/samples/HTTPTimeServer/HTTPTimeServer_vs80.vcproj @@ -1,217 +1,217 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/HTTPTimeServer/Makefile b/Net/samples/HTTPTimeServer/Makefile index a6975012a..686b3c70a 100644 --- a/Net/samples/HTTPTimeServer/Makefile +++ b/Net/samples/HTTPTimeServer/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/HTTPTimeServer/Makefile#1 $ -# -# Makefile for Poco HTTPTimeServer -# - -include $(POCO_BASE)/build/rules/global - -objects = HTTPTimeServer - -target = HTTPTimeServer -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/HTTPTimeServer/Makefile#1 $ +# +# Makefile for Poco HTTPTimeServer +# + +include $(POCO_BASE)/build/rules/global + +objects = HTTPTimeServer + +target = HTTPTimeServer +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/HTTPTimeServer/src/HTTPTimeServer.cpp b/Net/samples/HTTPTimeServer/src/HTTPTimeServer.cpp index 12aaa6f76..a2046c091 100644 --- a/Net/samples/HTTPTimeServer/src/HTTPTimeServer.cpp +++ b/Net/samples/HTTPTimeServer/src/HTTPTimeServer.cpp @@ -1,236 +1,236 @@ -// -// HTTPTimeServer.cpp -// -// $Id: //poco/1.2/Net/samples/HTTPTimeServer/src/HTTPTimeServer.cpp#1 $ -// -// This sample demonstrates the HTTPServer and related classes. -// -// 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/HTTPRequestHandler.h" -#include "Poco/Net/HTTPRequestHandlerFactory.h" -#include "Poco/Net/HTTPServerParams.h" -#include "Poco/Net/HTTPServerRequest.h" -#include "Poco/Net/HTTPServerResponse.h" -#include "Poco/Net/HTTPServerParams.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Timestamp.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/Exception.h" -#include "Poco/ThreadPool.h" -#include "Poco/Util/ServerApplication.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/HelpFormatter.h" -#include - - -using Poco::Net::ServerSocket; -using Poco::Net::HTTPRequestHandler; -using Poco::Net::HTTPRequestHandlerFactory; -using Poco::Net::HTTPServer; -using Poco::Net::HTTPServerRequest; -using Poco::Net::HTTPServerResponse; -using Poco::Net::HTTPServerParams; -using Poco::Timestamp; -using Poco::DateTimeFormatter; -using Poco::DateTimeFormat; -using Poco::ThreadPool; -using Poco::Util::ServerApplication; -using Poco::Util::Application; -using Poco::Util::Option; -using Poco::Util::OptionSet; -using Poco::Util::HelpFormatter; - - -class TimeRequestHandler: public HTTPRequestHandler - /// Return a HTML document with the current date and time. -{ -public: - TimeRequestHandler(const std::string& format): - _format(format) - { - } - - void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) - { - Application& app = Application::instance(); - app.logger().information("Request from " + request.clientAddress().toString()); - - Timestamp now; - std::string dt(DateTimeFormatter::format(now, _format)); - - response.setChunkedTransferEncoding(true); - response.setContentType("text/html"); - - std::ostream& ostr = response.send(); - ostr << "HTTPTimeServer powered by C++ Portable Components"; - ostr << ""; - ostr << "

"; - ostr << dt; - ostr << "

"; - } - -private: - std::string _format; -}; - - -class TimeRequestHandlerFactory: public HTTPRequestHandlerFactory -{ -public: - TimeRequestHandlerFactory(const std::string& format): - _format(format) - { - } - - HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) - { - if (request.getURI() == "/") - return new TimeRequestHandler(_format); - else - return 0; - } - -private: - std::string _format; -}; - - -class HTTPTimeServer: public Poco::Util::ServerApplication - /// The main application class. - /// - /// This class handles command-line arguments and - /// configuration files. - /// Start the HTTPTimeServer executable with the help - /// option (/help on Windows, --help on Unix) for - /// the available command line options. - /// - /// To use the sample configuration file (HTTPTimeServer.properties), - /// copy the file to the directory where the HTTPTimeServer executable - /// resides. If you start the debug version of the HTTPTimeServer - /// (HTTPTimeServerd[.exe]), you must also create a copy of the configuration - /// file named HTTPTimeServerd.properties. In the configuration file, you - /// can specify the port on which the server is listening (default - /// 9980) and the format of the date/time string sent back to the client. - /// - /// To test the TimeServer you can use any web browser (http://localhost:9980/). -{ -public: - HTTPTimeServer(): _helpRequested(false) - { - } - - ~HTTPTimeServer() - { - } - -protected: - void initialize(Application& self) - { - loadConfiguration(); // load default configuration files, if present - ServerApplication::initialize(self); - } - - void uninitialize() - { - ServerApplication::uninitialize(); - } - - void defineOptions(OptionSet& options) - { - ServerApplication::defineOptions(options); - - options.addOption( - Option("help", "h", "display help information on command line arguments") - .required(false) - .repeatable(false)); - } - - void handleOption(const std::string& name, const std::string& value) - { - ServerApplication::handleOption(name, value); - - if (name == "help") - _helpRequested = true; - } - - void displayHelp() - { - HelpFormatter helpFormatter(options()); - helpFormatter.setCommand(commandName()); - helpFormatter.setUsage("OPTIONS"); - helpFormatter.setHeader("A web server that serves the current date and time."); - helpFormatter.format(std::cout); - } - - int main(const std::vector& args) - { - if (_helpRequested) - { - displayHelp(); - } - else - { - // get parameters from configuration file - unsigned short port = (unsigned short) config().getInt("HTTPTimeServer.port", 9980); - std::string format(config().getString("HTTPTimeServer.format", DateTimeFormat::SORTABLE_FORMAT)); - int maxQueued = config().getInt("HTTPTimeServer.maxQueued", 100); - int maxThreads = config().getInt("HTTPTimeServer.maxThreads", 16); - ThreadPool::defaultPool().addCapacity(maxThreads); - - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setMaxQueued(maxQueued); - pParams->setMaxThreads(maxThreads); - - // set-up a server socket - ServerSocket svs(port); - // set-up a HTTPServer instance - HTTPServer srv(new TimeRequestHandlerFactory(format), svs, pParams); - // start the HTTPServer - srv.start(); - // wait for CTRL-C or kill - waitForTerminationRequest(); - // Stop the HTTPServer - srv.stop(); - } - return Application::EXIT_OK; - } - -private: - bool _helpRequested; -}; - - -int main(int argc, char** argv) -{ - HTTPTimeServer app; - return app.run(argc, argv); -} +// +// HTTPTimeServer.cpp +// +// $Id: //poco/1.2/Net/samples/HTTPTimeServer/src/HTTPTimeServer.cpp#1 $ +// +// This sample demonstrates the HTTPServer and related classes. +// +// 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/HTTPRequestHandler.h" +#include "Poco/Net/HTTPRequestHandlerFactory.h" +#include "Poco/Net/HTTPServerParams.h" +#include "Poco/Net/HTTPServerRequest.h" +#include "Poco/Net/HTTPServerResponse.h" +#include "Poco/Net/HTTPServerParams.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Timestamp.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/Exception.h" +#include "Poco/ThreadPool.h" +#include "Poco/Util/ServerApplication.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/HelpFormatter.h" +#include + + +using Poco::Net::ServerSocket; +using Poco::Net::HTTPRequestHandler; +using Poco::Net::HTTPRequestHandlerFactory; +using Poco::Net::HTTPServer; +using Poco::Net::HTTPServerRequest; +using Poco::Net::HTTPServerResponse; +using Poco::Net::HTTPServerParams; +using Poco::Timestamp; +using Poco::DateTimeFormatter; +using Poco::DateTimeFormat; +using Poco::ThreadPool; +using Poco::Util::ServerApplication; +using Poco::Util::Application; +using Poco::Util::Option; +using Poco::Util::OptionSet; +using Poco::Util::HelpFormatter; + + +class TimeRequestHandler: public HTTPRequestHandler + /// Return a HTML document with the current date and time. +{ +public: + TimeRequestHandler(const std::string& format): + _format(format) + { + } + + void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) + { + Application& app = Application::instance(); + app.logger().information("Request from " + request.clientAddress().toString()); + + Timestamp now; + std::string dt(DateTimeFormatter::format(now, _format)); + + response.setChunkedTransferEncoding(true); + response.setContentType("text/html"); + + std::ostream& ostr = response.send(); + ostr << "HTTPTimeServer powered by C++ Portable Components"; + ostr << ""; + ostr << "

"; + ostr << dt; + ostr << "

"; + } + +private: + std::string _format; +}; + + +class TimeRequestHandlerFactory: public HTTPRequestHandlerFactory +{ +public: + TimeRequestHandlerFactory(const std::string& format): + _format(format) + { + } + + HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) + { + if (request.getURI() == "/") + return new TimeRequestHandler(_format); + else + return 0; + } + +private: + std::string _format; +}; + + +class HTTPTimeServer: public Poco::Util::ServerApplication + /// The main application class. + /// + /// This class handles command-line arguments and + /// configuration files. + /// Start the HTTPTimeServer executable with the help + /// option (/help on Windows, --help on Unix) for + /// the available command line options. + /// + /// To use the sample configuration file (HTTPTimeServer.properties), + /// copy the file to the directory where the HTTPTimeServer executable + /// resides. If you start the debug version of the HTTPTimeServer + /// (HTTPTimeServerd[.exe]), you must also create a copy of the configuration + /// file named HTTPTimeServerd.properties. In the configuration file, you + /// can specify the port on which the server is listening (default + /// 9980) and the format of the date/time string sent back to the client. + /// + /// To test the TimeServer you can use any web browser (http://localhost:9980/). +{ +public: + HTTPTimeServer(): _helpRequested(false) + { + } + + ~HTTPTimeServer() + { + } + +protected: + void initialize(Application& self) + { + loadConfiguration(); // load default configuration files, if present + ServerApplication::initialize(self); + } + + void uninitialize() + { + ServerApplication::uninitialize(); + } + + void defineOptions(OptionSet& options) + { + ServerApplication::defineOptions(options); + + options.addOption( + Option("help", "h", "display help information on command line arguments") + .required(false) + .repeatable(false)); + } + + void handleOption(const std::string& name, const std::string& value) + { + ServerApplication::handleOption(name, value); + + if (name == "help") + _helpRequested = true; + } + + void displayHelp() + { + HelpFormatter helpFormatter(options()); + helpFormatter.setCommand(commandName()); + helpFormatter.setUsage("OPTIONS"); + helpFormatter.setHeader("A web server that serves the current date and time."); + helpFormatter.format(std::cout); + } + + int main(const std::vector& args) + { + if (_helpRequested) + { + displayHelp(); + } + else + { + // get parameters from configuration file + unsigned short port = (unsigned short) config().getInt("HTTPTimeServer.port", 9980); + std::string format(config().getString("HTTPTimeServer.format", DateTimeFormat::SORTABLE_FORMAT)); + int maxQueued = config().getInt("HTTPTimeServer.maxQueued", 100); + int maxThreads = config().getInt("HTTPTimeServer.maxThreads", 16); + ThreadPool::defaultPool().addCapacity(maxThreads); + + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setMaxQueued(maxQueued); + pParams->setMaxThreads(maxThreads); + + // set-up a server socket + ServerSocket svs(port); + // set-up a HTTPServer instance + HTTPServer srv(new TimeRequestHandlerFactory(format), svs, pParams); + // start the HTTPServer + srv.start(); + // wait for CTRL-C or kill + waitForTerminationRequest(); + // Stop the HTTPServer + srv.stop(); + } + return Application::EXIT_OK; + } + +private: + bool _helpRequested; +}; + + +int main(int argc, char** argv) +{ + HTTPTimeServer app; + return app.run(argc, argv); +} diff --git a/Net/samples/Mail/Mail.vmsbuild b/Net/samples/Mail/Mail.vmsbuild index 384f53df7..672be4f97 100644 --- a/Net/samples/Mail/Mail.vmsbuild +++ b/Net/samples/Mail/Mail.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Net/samples/Mail/Mail.vmsbuild#1 $ -# -EXE=Mail -Mail - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Net/samples/Mail/Mail.vmsbuild#1 $ +# +EXE=Mail +Mail + diff --git a/Net/samples/Mail/Mail_vs71.vcproj b/Net/samples/Mail/Mail_vs71.vcproj index 4e9993651..ac6a8b005 100644 --- a/Net/samples/Mail/Mail_vs71.vcproj +++ b/Net/samples/Mail/Mail_vs71.vcproj @@ -1,148 +1,148 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/Mail/Mail_vs80.vcproj b/Net/samples/Mail/Mail_vs80.vcproj index 2f29a18b0..6a555f83c 100644 --- a/Net/samples/Mail/Mail_vs80.vcproj +++ b/Net/samples/Mail/Mail_vs80.vcproj @@ -1,214 +1,214 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/Mail/Makefile b/Net/samples/Mail/Makefile index 2bc2c2a01..569133ddf 100644 --- a/Net/samples/Mail/Makefile +++ b/Net/samples/Mail/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/Mail/Makefile#1 $ -# -# Makefile for Poco Mail -# - -include $(POCO_BASE)/build/rules/global - -objects = Mail - -target = Mail -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/Mail/Makefile#1 $ +# +# Makefile for Poco Mail +# + +include $(POCO_BASE)/build/rules/global + +objects = Mail + +target = Mail +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/Mail/src/Mail.cpp b/Net/samples/Mail/src/Mail.cpp index e4a82d1bf..2a5c9d594 100644 --- a/Net/samples/Mail/src/Mail.cpp +++ b/Net/samples/Mail/src/Mail.cpp @@ -1,99 +1,99 @@ -// -// Mail.cpp -// -// $Id: //poco/1.2/Net/samples/Mail/src/Mail.cpp#1 $ -// -// This sample demonstrates the MailMessage and SMTPClientSession classes. -// -// 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/MailMessage.h" -#include "Poco/Net/MailRecipient.h" -#include "Poco/Net/SMTPClientSession.h" -#include "Poco/Net/StringPartSource.h" -#include "Poco/Path.h" -#include "Poco/Exception.h" -#include - - -using Poco::Net::MailMessage; -using Poco::Net::MailRecipient; -using Poco::Net::SMTPClientSession; -using Poco::Net::StringPartSource; -using Poco::Path; -using Poco::Exception; - - -const unsigned char PocoLogo[] = -{ - #include "PocoLogo.hpp" -}; - - -int main(int argc, char** argv) -{ - if (argc != 4) - { - Path p(argv[0]); - std::cerr << "usage: " << p.getBaseName() << " " << std::endl; - std::cerr << " Send an email greeting from to ," << std::endl; - std::cerr << " the SMTP server at ." << std::endl; - return 1; - } - - std::string mailhost(argv[1]); - std::string sender(argv[2]); - std::string recipient(argv[3]); - - try - { - MailMessage message; - message.setSender(sender); - message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, recipient)); - message.setSubject("Hello from the C++ Portable Components"); - std::string content; - content += "Hello "; - content += recipient; - content += ",\r\n\r\n"; - content += "This is a greeting from the C++ Portable Components.\r\n\r\n"; - std::string logo(reinterpret_cast(PocoLogo), sizeof(PocoLogo)); - message.addContent(new StringPartSource(content)); - message.addAttachment("logo", new StringPartSource(logo, "image/gif")); - - SMTPClientSession session(mailhost); - session.login(); - session.sendMessage(message); - session.close(); - } - catch (Exception& exc) - { - std::cerr << exc.displayText() << std::endl; - return 1; - } - return 0; -} +// +// Mail.cpp +// +// $Id: //poco/1.2/Net/samples/Mail/src/Mail.cpp#1 $ +// +// This sample demonstrates the MailMessage and SMTPClientSession classes. +// +// 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/MailMessage.h" +#include "Poco/Net/MailRecipient.h" +#include "Poco/Net/SMTPClientSession.h" +#include "Poco/Net/StringPartSource.h" +#include "Poco/Path.h" +#include "Poco/Exception.h" +#include + + +using Poco::Net::MailMessage; +using Poco::Net::MailRecipient; +using Poco::Net::SMTPClientSession; +using Poco::Net::StringPartSource; +using Poco::Path; +using Poco::Exception; + + +const unsigned char PocoLogo[] = +{ + #include "PocoLogo.hpp" +}; + + +int main(int argc, char** argv) +{ + if (argc != 4) + { + Path p(argv[0]); + std::cerr << "usage: " << p.getBaseName() << " " << std::endl; + std::cerr << " Send an email greeting from to ," << std::endl; + std::cerr << " the SMTP server at ." << std::endl; + return 1; + } + + std::string mailhost(argv[1]); + std::string sender(argv[2]); + std::string recipient(argv[3]); + + try + { + MailMessage message; + message.setSender(sender); + message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, recipient)); + message.setSubject("Hello from the C++ Portable Components"); + std::string content; + content += "Hello "; + content += recipient; + content += ",\r\n\r\n"; + content += "This is a greeting from the C++ Portable Components.\r\n\r\n"; + std::string logo(reinterpret_cast(PocoLogo), sizeof(PocoLogo)); + message.addContent(new StringPartSource(content)); + message.addAttachment("logo", new StringPartSource(logo, "image/gif")); + + SMTPClientSession session(mailhost); + session.login(); + session.sendMessage(message); + session.close(); + } + catch (Exception& exc) + { + std::cerr << exc.displayText() << std::endl; + return 1; + } + return 0; +} diff --git a/Net/samples/Mail/src/PocoLogo.hpp b/Net/samples/Mail/src/PocoLogo.hpp index 08bbcd68f..a1b39a593 100644 --- a/Net/samples/Mail/src/PocoLogo.hpp +++ b/Net/samples/Mail/src/PocoLogo.hpp @@ -1,134 +1,134 @@ -// The C++ Portable Components logo in GIF format - -0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0xa0, 0x00, 0x85, 0x00, 0xa2, 0x00, 0x00, 0xd1, 0xdd, 0xe4, -0x45, 0x9b, 0xca, 0x41, 0x55, 0x61, 0x8a, 0x96, 0x9e, 0xa2, 0xbc, 0xcc, 0x00, 0x1b, 0x2c, 0x00, -0x75, 0xb6, 0xff, 0xff, 0xff, 0x21, 0xf9, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, -0x00, 0x00, 0xa0, 0x00, 0x85, 0x00, 0x00, 0x03, 0xff, 0x78, 0xba, 0xdc, 0xfe, 0x30, 0xca, 0x49, -0xab, 0xbd, 0x38, 0xeb, 0xcd, 0xbb, 0xff, 0x60, 0x28, 0x8e, 0x64, 0x69, 0x9e, 0x68, 0xaa, 0xae, -0x6c, 0xeb, 0xbe, 0x70, 0x2c, 0xcf, 0x2b, 0x40, 0xdc, 0x78, 0xae, 0xef, 0x04, 0xe0, 0xda, 0xbc, -0xe0, 0x0e, 0xe0, 0xeb, 0x00, 0x06, 0xc5, 0xc5, 0x6d, 0x72, 0x4b, 0x76, 0x08, 0x01, 0x83, 0x74, -0x4a, 0xad, 0x5a, 0xab, 0x01, 0x27, 0x09, 0x10, 0xbd, 0x7a, 0xbf, 0x86, 0x40, 0x6f, 0x33, 0x28, -0x10, 0x1a, 0x85, 0x82, 0x44, 0x90, 0x2e, 0x68, 0x2f, 0xb6, 0x2e, 0x78, 0x7e, 0x15, 0x8f, 0xe2, -0xf4, 0xbc, 0xd5, 0x8e, 0x29, 0x9f, 0x09, 0x48, 0x07, 0x69, 0x11, 0x65, 0x02, 0x6c, 0x03, 0x1b, -0x72, 0x7a, 0x8b, 0x54, 0x67, 0x1f, 0x8a, 0x8c, 0x8c, 0x59, 0x17, 0x7e, 0x82, 0x66, 0x96, 0x11, -0x69, 0x3e, 0x05, 0x02, 0x19, 0x5c, 0x91, 0xa0, 0x53, 0x8e, 0x1c, 0x90, 0xa1, 0x8b, 0xa3, 0x13, -0x95, 0x69, 0x67, 0x83, 0x0c, 0x36, 0x0a, 0x9a, 0x82, 0x9d, 0x70, 0xa6, 0xb5, 0x93, 0x19, 0x04, -0xb5, 0xb6, 0x15, 0xaa, 0x97, 0xad, 0x0b, 0x6c, 0xac, 0x6e, 0xb2, 0x17, 0xb9, 0xba, 0xb5, 0x6f, -0x12, 0xc6, 0xc7, 0xa6, 0xc9, 0x0c, 0xbd, 0x3d, 0xbf, 0x0a, 0xc1, 0x96, 0x3e, 0x44, 0x16, 0xcb, -0xcc, 0xa0, 0x01, 0xb4, 0xda, 0xa6, 0xdc, 0x12, 0x65, 0x9c, 0x69, 0x86, 0x9c, 0x0d, 0xd4, 0xb1, -0xdd, 0xde, 0xa1, 0xe0, 0x4c, 0xeb, 0xbb, 0xe1, 0x6d, 0x6d, 0x02, 0x5a, 0xe2, 0x6c, 0xb3, 0x17, -0xa5, 0xef, 0x7a, 0xed, 0x11, 0xfb, 0xb5, 0xa8, 0x1e, 0x10, 0x19, 0xe8, 0x8c, 0x0d, 0x27, 0x67, -0x10, 0xb2, 0xfd, 0x63, 0x84, 0xf0, 0x80, 0xc2, 0x85, 0x8b, 0x1a, 0xc2, 0x09, 0x48, 0x01, 0x00, -0xc4, 0x50, 0x14, 0x17, 0x58, 0xbc, 0xb8, 0x0d, 0xff, 0x83, 0x21, 0x11, 0xfa, 0xbc, 0x88, 0x21, -0x48, 0xb2, 0x24, 0x91, 0x1b, 0x21, 0xaf, 0x38, 0x7b, 0xf8, 0xa5, 0x87, 0xc9, 0x97, 0x04, 0xa1, -0x44, 0xbc, 0x20, 0x4d, 0xe3, 0x90, 0x09, 0xfc, 0x3e, 0x7c, 0xa2, 0x93, 0xf1, 0x80, 0x9e, 0x9e, -0x18, 0x36, 0xf2, 0xa4, 0xa9, 0xa6, 0x81, 0x38, 0x79, 0x35, 0x1b, 0x08, 0x05, 0x23, 0xb1, 0x58, -0x9e, 0x07, 0x2c, 0xad, 0x34, 0x75, 0x3a, 0xa7, 0xdf, 0x84, 0x9a, 0xe2, 0x06, 0x68, 0xdd, 0x8a, -0x28, 0x42, 0x54, 0x2a, 0x53, 0xf3, 0x0d, 0x6d, 0x90, 0x72, 0x4a, 0x58, 0xaa, 0x4c, 0x2d, 0xd4, -0x3c, 0x94, 0xa1, 0xac, 0x01, 0xa0, 0x1d, 0xdc, 0x5a, 0xf5, 0x39, 0x07, 0x2e, 0x87, 0xa5, 0x5e, -0xec, 0x2a, 0x00, 0xb0, 0xf6, 0x12, 0x06, 0xb7, 0x67, 0xd5, 0x7d, 0x51, 0x5a, 0x15, 0xc5, 0x57, -0x29, 0x73, 0x01, 0x71, 0x1d, 0x70, 0xef, 0x9c, 0xdf, 0x0b, 0x85, 0x4f, 0xb8, 0x25, 0x0c, 0x66, -0xae, 0x08, 0xbc, 0x7b, 0x1c, 0x1c, 0x45, 0x1a, 0x90, 0x9a, 0xe0, 0x3a, 0x28, 0x00, 0xbb, 0x8a, -0x2c, 0xb9, 0xb2, 0x03, 0x02, 0x86, 0x52, 0x0b, 0x08, 0xe4, 0x58, 0xef, 0x68, 0x30, 0xae, 0x13, -0xcd, 0x71, 0x82, 0xb9, 0x4a, 0x6c, 0xd9, 0x5f, 0x2c, 0x5b, 0xf0, 0x6c, 0xa1, 0x76, 0xa3, 0xd0, -0xb3, 0x5f, 0xb7, 0x4c, 0x51, 0x56, 0x77, 0x85, 0x57, 0x41, 0xeb, 0x02, 0x4f, 0xab, 0x51, 0xf9, -0x72, 0x91, 0x0f, 0xb2, 0xda, 0x0b, 0x0c, 0xc1, 0xb7, 0xa8, 0xe7, 0x5e, 0x28, 0x0f, 0xc7, 0x9e, -0xd9, 0x28, 0x39, 0xa4, 0xf8, 0x34, 0x1a, 0x94, 0x17, 0x5e, 0x7b, 0xde, 0x13, 0xd6, 0xa7, 0x98, -0xbf, 0x72, 0x5b, 0x43, 0x71, 0xcd, 0xbe, 0xcc, 0xf0, 0x2d, 0xcf, 0x17, 0x29, 0xb9, 0x08, 0xe9, -0xdf, 0x96, 0x36, 0x2d, 0xfc, 0x3c, 0x77, 0x2c, 0xff, 0xf0, 0x09, 0x23, 0x8c, 0x63, 0x02, 0xdc, -0x54, 0x9d, 0x73, 0x24, 0xb8, 0xa5, 0x5f, 0x7f, 0xec, 0x11, 0xc7, 0xdf, 0x33, 0xf1, 0x0d, 0xc8, -0x00, 0x6f, 0xc7, 0x21, 0x08, 0xd2, 0x53, 0xeb, 0x59, 0xd1, 0x5e, 0x5b, 0x0f, 0x2e, 0x00, 0x0d, -0x26, 0x13, 0x3e, 0x56, 0x21, 0x6c, 0x97, 0xc9, 0x44, 0xc7, 0x5c, 0xf9, 0x6d, 0xf8, 0x57, 0x87, -0x0a, 0xf8, 0x01, 0x80, 0x21, 0xd1, 0x14, 0x05, 0x8c, 0x88, 0x15, 0x39, 0xc7, 0x45, 0x00, 0x38, -0xe6, 0xa8, 0xe3, 0x8e, 0x3c, 0x46, 0x22, 0x90, 0x85, 0x25, 0xbc, 0xe7, 0x9d, 0x7d, 0x7d, 0xb5, -0x97, 0xa2, 0x02, 0x87, 0xbd, 0x93, 0xd1, 0x91, 0xff, 0x51, 0x31, 0xd7, 0x66, 0xe4, 0x11, 0x98, -0x1c, 0x89, 0x07, 0x28, 0xe8, 0x4d, 0x32, 0x4c, 0xee, 0x07, 0x9d, 0x52, 0x30, 0x35, 0x40, 0xc0, -0x3c, 0xa9, 0x99, 0x73, 0x20, 0x95, 0x56, 0x32, 0xd3, 0x53, 0x96, 0x26, 0x08, 0x79, 0x97, 0x6a, -0xe5, 0x94, 0xc7, 0xa0, 0x86, 0x0a, 0x94, 0xa9, 0x8b, 0x71, 0x68, 0x06, 0xc9, 0xa2, 0x87, 0x6c, -0x7e, 0xa4, 0x93, 0x73, 0x72, 0x9a, 0x02, 0x57, 0x9d, 0x09, 0xde, 0xf9, 0x22, 0x91, 0x32, 0x1a, -0xc1, 0x27, 0x47, 0xc6, 0xed, 0x05, 0x64, 0xa0, 0xb9, 0xc1, 0x47, 0xcf, 0x11, 0x05, 0x20, 0x51, -0x0f, 0x3d, 0xe7, 0x74, 0xf5, 0x23, 0x99, 0x17, 0x25, 0xaa, 0x28, 0x95, 0x5a, 0x82, 0xe6, 0x9d, -0x23, 0x65, 0x58, 0x1a, 0x62, 0x40, 0x49, 0x35, 0x87, 0xe9, 0x3f, 0xb7, 0x4c, 0x00, 0xe8, 0x08, -0x6a, 0x7a, 0xe8, 0x57, 0xa8, 0x0f, 0x50, 0x63, 0xc8, 0x26, 0x6e, 0x9a, 0xba, 0x5d, 0x9f, 0x3f, -0x7d, 0x06, 0x27, 0x0a, 0xa4, 0xb9, 0x0a, 0x6a, 0xa4, 0xb1, 0xc6, 0x47, 0x2b, 0x7e, 0x87, 0xae, -0x93, 0xea, 0x88, 0x8d, 0xa2, 0xd7, 0x6b, 0x8b, 0xff, 0xaf, 0x02, 0xeb, 0x00, 0x3a, 0xc3, 0x88, -0x79, 0xe9, 0x76, 0x37, 0xf2, 0x68, 0xed, 0xb5, 0x62, 0x8c, 0xa1, 0x41, 0x7e, 0x9a, 0x3e, 0xb1, -0xec, 0x01, 0x85, 0xf4, 0x10, 0xea, 0x35, 0xa3, 0x56, 0x43, 0xcc, 0x98, 0xdb, 0xd1, 0x60, 0xeb, -0x60, 0x27, 0x8c, 0xe5, 0x0a, 0xa1, 0xe5, 0x1d, 0x52, 0x9f, 0x0d, 0xd2, 0x3a, 0xb0, 0xea, 0x0c, -0xee, 0x8e, 0x90, 0xa4, 0x01, 0xc9, 0xa0, 0x66, 0x5f, 0x79, 0x50, 0xb6, 0x21, 0x6a, 0x86, 0xb6, -0xa9, 0x4b, 0x56, 0xbe, 0x20, 0xe4, 0x17, 0x86, 0x04, 0x26, 0x9d, 0x96, 0xe7, 0xc0, 0x04, 0xff, -0x66, 0xb0, 0x12, 0x79, 0x50, 0xe7, 0x55, 0x1e, 0x2a, 0xee, 0xc9, 0xe9, 0xc4, 0x74, 0x21, 0xbc, -0xc1, 0xbe, 0x52, 0x38, 0x73, 0x44, 0x9e, 0xb5, 0x7a, 0xb2, 0xa8, 0xba, 0x20, 0x23, 0x86, 0xed, -0xca, 0x38, 0x2e, 0xa2, 0x5b, 0x7d, 0xff, 0xda, 0xcb, 0x18, 0x9b, 0x10, 0xaf, 0xdb, 0x20, 0xc7, -0x0b, 0xe0, 0xca, 0x51, 0x4f, 0x85, 0x48, 0x34, 0x28, 0x91, 0xc4, 0x6e, 0xcc, 0x71, 0xca, 0x1c, -0x21, 0x46, 0x08, 0x8d, 0xd1, 0x71, 0x32, 0x80, 0x62, 0x5a, 0x01, 0x75, 0xaf, 0xba, 0x3a, 0xa3, -0x1a, 0x8f, 0x5e, 0x14, 0xd6, 0x28, 0x34, 0xc7, 0x0a, 0x17, 0xcd, 0xef, 0xd4, 0x14, 0x54, 0xad, -0xea, 0xc9, 0x13, 0x13, 0xbd, 0x90, 0xa6, 0x95, 0x4c, 0xe0, 0x35, 0xc3, 0x60, 0x4f, 0x9c, 0xf5, -0x42, 0x7a, 0x95, 0xbd, 0x06, 0xd2, 0x68, 0x5f, 0x8d, 0xb3, 0x43, 0x5a, 0xef, 0xca, 0x04, 0xa5, -0x66, 0xd7, 0x6b, 0x75, 0xba, 0x73, 0x33, 0x60, 0xa2, 0xd6, 0x7c, 0xe8, 0x4b, 0x0e, 0xcd, 0x41, -0xf3, 0xdd, 0xb7, 0xdf, 0x5a, 0xab, 0x38, 0xf3, 0x9f, 0xe3, 0xcd, 0x53, 0xb8, 0x7f, 0x87, 0xdb, -0x1b, 0x75, 0x1e, 0xc7, 0xee, 0x26, 0x4f, 0xc6, 0xff, 0x11, 0x94, 0x65, 0x31, 0x0d, 0x71, 0xb4, -0x6c, 0x0b, 0x8e, 0xda, 0xe2, 0xa2, 0xf4, 0x3d, 0x38, 0x44, 0x6e, 0xfa, 0x0c, 0x65, 0x37, 0x0e, -0x95, 0x6a, 0xac, 0x9d, 0xee, 0xfa, 0x07, 0xa9, 0x93, 0x03, 0x71, 0xe3, 0xe4, 0x6c, 0xfe, 0xfa, -0xed, 0xe0, 0xfa, 0xc5, 0x46, 0x32, 0xe1, 0xe2, 0xc0, 0x16, 0xee, 0xc0, 0x53, 0xa2, 0x7b, 0xa1, -0xe5, 0x6a, 0xa4, 0x77, 0xf0, 0xc8, 0x27, 0x4d, 0xa9, 0x56, 0x10, 0x54, 0x7d, 0xbc, 0x11, 0x4c, -0x2f, 0x26, 0xfd, 0xf4, 0xd4, 0x6b, 0x65, 0xbb, 0x40, 0xd1, 0x57, 0x4f, 0x7d, 0xe8, 0x1b, 0xfc, -0x0c, 0x5e, 0x6b, 0x68, 0x94, 0x3c, 0x11, 0xed, 0x84, 0x96, 0x6f, 0xfe, 0x7d, 0x1e, 0xd8, 0x40, -0xfe, 0xf9, 0xe5, 0xaf, 0x66, 0xfb, 0xc8, 0x79, 0x82, 0xcf, 0xc0, 0xf3, 0xbd, 0x05, 0xcc, 0xfe, -0xfd, 0x40, 0x77, 0x60, 0x3f, 0xfe, 0xe7, 0xb7, 0x5e, 0xc2, 0xef, 0x48, 0xa2, 0x9f, 0xaa, 0xd6, -0xc7, 0xbf, 0x02, 0x96, 0xaa, 0x22, 0x04, 0x34, 0xe0, 0xf9, 0xf0, 0x16, 0x94, 0x81, 0x24, 0x64, -0x70, 0xe5, 0x80, 0x1b, 0x13, 0x14, 0x48, 0x41, 0xa4, 0x6c, 0x2b, 0x81, 0x15, 0x34, 0x5f, 0xcd, -0x12, 0x42, 0xbb, 0x9a, 0xf9, 0x4b, 0x1e, 0x1b, 0x8c, 0x47, 0x06, 0x33, 0x28, 0xba, 0x11, 0x52, -0xd0, 0x35, 0x30, 0x43, 0xca, 0x06, 0x09, 0xb2, 0x01, 0x0c, 0x9a, 0xf0, 0x7c, 0x7d, 0x78, 0x61, -0x05, 0xc5, 0xe7, 0xaa, 0x47, 0x11, 0xa1, 0x10, 0x26, 0x70, 0xa1, 0x0c, 0xcb, 0x27, 0xbc, 0x1d, -0x52, 0x90, 0x86, 0xb9, 0x23, 0x15, 0xf1, 0x90, 0x64, 0x3d, 0x0d, 0xec, 0xcf, 0x87, 0x30, 0xac, -0xc0, 0x97, 0x90, 0x78, 0x42, 0xae, 0xcd, 0x6f, 0x88, 0xe3, 0x61, 0xa0, 0x12, 0x99, 0xa8, 0xc0, -0xe3, 0x50, 0xb1, 0x82, 0x08, 0x71, 0x1b, 0x2c, 0xff, 0x88, 0x17, 0xae, 0xc6, 0x5c, 0x40, 0x87, -0x57, 0x94, 0x07, 0x2f, 0xc2, 0xa8, 0x40, 0xf1, 0x69, 0xb1, 0x3e, 0xf2, 0x13, 0x20, 0x7c, 0xc8, -0x78, 0x3f, 0x20, 0x1e, 0x20, 0x85, 0x6c, 0xc4, 0xdf, 0x06, 0x7b, 0x77, 0x03, 0x2f, 0xce, 0xc8, -0x11, 0x7a, 0xaa, 0x08, 0xff, 0x0a, 0xe4, 0x12, 0x98, 0xf8, 0xb1, 0x4b, 0x5d, 0xc3, 0xdf, 0x6a, -0xfa, 0xf8, 0xc7, 0x98, 0x30, 0x86, 0x7f, 0x05, 0x21, 0x52, 0x67, 0x74, 0xe7, 0xc6, 0x69, 0xb4, -0xf1, 0x7a, 0x20, 0x58, 0x22, 0xfb, 0x42, 0xd8, 0x43, 0xf6, 0x01, 0x65, 0x66, 0x86, 0xf0, 0x9f, -0x23, 0x1d, 0x71, 0x40, 0xa5, 0x3c, 0xd2, 0x60, 0x3a, 0x94, 0xa2, 0x07, 0x3e, 0xa8, 0x41, 0x0f, -0xdc, 0x83, 0x08, 0xb3, 0x22, 0xd7, 0x03, 0x17, 0xa8, 0x36, 0xf6, 0x89, 0x12, 0x04, 0x2e, 0xa4, -0xa1, 0x2a, 0xa1, 0x02, 0x2f, 0x11, 0xb6, 0x0f, 0x6b, 0x96, 0x34, 0x81, 0x24, 0xcb, 0xd7, 0x2f, -0x81, 0x29, 0x83, 0x7c, 0x34, 0x3c, 0x62, 0x1a, 0x28, 0xe9, 0x82, 0x5d, 0x12, 0xa9, 0x91, 0x2d, -0x3c, 0x1f, 0x45, 0xea, 0x63, 0x10, 0x62, 0x66, 0xc0, 0x85, 0x90, 0x14, 0x81, 0x31, 0xed, 0xe3, -0x4c, 0x0e, 0x08, 0xd3, 0x59, 0x10, 0x42, 0x04, 0x1a, 0x47, 0x00, 0x4d, 0x8e, 0x5d, 0xb3, 0x9a, -0xdd, 0xeb, 0x5f, 0x80, 0x1c, 0xf9, 0x4b, 0xc2, 0x45, 0xc0, 0x85, 0x38, 0xfb, 0x66, 0x0a, 0x58, -0xf9, 0x29, 0x72, 0x0a, 0x64, 0x7d, 0x34, 0xc4, 0x20, 0x32, 0x57, 0xa0, 0x4e, 0x14, 0xb0, 0x13, -0x42, 0x78, 0x1c, 0xa2, 0x23, 0x0b, 0x54, 0x92, 0xb7, 0xdd, 0xd2, 0x9b, 0xe2, 0xb4, 0xa7, 0xf9, -0xdc, 0x04, 0xab, 0x03, 0xe4, 0x51, 0x7e, 0x5f, 0x1c, 0x68, 0x3a, 0x03, 0x7a, 0x82, 0x7b, 0x2a, -0x61, 0x98, 0xd2, 0x43, 0xa8, 0xe5, 0xfe, 0x39, 0xff, 0xb1, 0x7a, 0x36, 0x54, 0xa1, 0x6b, 0xb4, -0x8f, 0x44, 0x2b, 0x20, 0xcf, 0x85, 0x96, 0x52, 0xa0, 0x14, 0x55, 0x8a, 0xf4, 0x16, 0xb9, 0xa1, -0x8e, 0x02, 0xf4, 0xa3, 0x26, 0x80, 0x63, 0xcc, 0x38, 0x60, 0xc7, 0x89, 0xd6, 0xf2, 0xa4, 0xe5, -0x03, 0xe7, 0xb6, 0x1c, 0x5a, 0x42, 0x4e, 0xb0, 0xc9, 0x9f, 0x2f, 0xad, 0x28, 0x43, 0x4b, 0xa0, -0xd2, 0xef, 0xdd, 0x25, 0xa7, 0xc1, 0x0a, 0xa9, 0xba, 0x2c, 0xca, 0x53, 0x9a, 0x7a, 0xe4, 0x20, -0xfd, 0x3c, 0x27, 0x46, 0x75, 0x8a, 0xd2, 0xa2, 0x2e, 0x55, 0x03, 0x67, 0xc3, 0xe9, 0x31, 0x3d, -0x1a, 0x53, 0x14, 0xf4, 0x34, 0x4a, 0x2c, 0x95, 0xa0, 0x52, 0x85, 0x4a, 0x03, 0xa2, 0x6e, 0xc1, -0xa8, 0x46, 0xd9, 0xe0, 0x3d, 0x46, 0x2a, 0xd5, 0x95, 0x32, 0xb5, 0xaa, 0xe8, 0x01, 0xeb, 0x13, -0xab, 0xc3, 0xc3, 0xad, 0x02, 0x75, 0xa8, 0x3b, 0xfd, 0xea, 0x53, 0x95, 0xb2, 0xc4, 0x26, 0xd8, -0x8b, 0x64, 0xf1, 0x9c, 0x6b, 0x57, 0xe3, 0x7a, 0x07, 0xb5, 0x1a, 0x54, 0x85, 0x21, 0x30, 0xe9, -0x59, 0x09, 0x25, 0x53, 0x4f, 0xf8, 0xf5, 0x90, 0x91, 0xd2, 0x64, 0x56, 0xb9, 0x8a, 0x3a, 0xbe, -0x5e, 0xc6, 0xaf, 0x5b, 0xc4, 0x0f, 0x26, 0x07, 0x99, 0x37, 0xf3, 0x51, 0x95, 0xb0, 0x86, 0x81, -0x2c, 0xb8, 0x36, 0x38, 0xcd, 0x55, 0x94, 0xd5, 0x3e, 0xd1, 0x0c, 0x81, 0x57, 0x47, 0x30, 0xda, -0x84, 0xe2, 0x0d, 0x52, 0x79, 0x35, 0x5f, 0x68, 0x23, 0xa9, 0xd9, 0x0e, 0xb8, 0x90, 0x98, 0xb3, -0x2c, 0xde, 0x5e, 0xd4, 0x58, 0xda, 0x18, 0x74, 0x16, 0xab, 0x4e, 0x55, 0x6d, 0xde, 0x9a, 0x47, -0x23, 0xda, 0xb2, 0x6f, 0xb5, 0xe9, 0xfb, 0xad, 0x09, 0xae, 0xa9, 0x4f, 0x57, 0xec, 0x2e, 0x58, -0xa4, 0xa2, 0xe1, 0x6d, 0xc9, 0x03, 0xdc, 0x0e, 0xff, 0xb8, 0xb2, 0xb9, 0x0e, 0x71, 0x65, 0x59, -0x49, 0xfa, 0x2e, 0x59, 0xe2, 0x0f, 0xba, 0x46, 0xbc, 0x1f, 0x70, 0x89, 0xab, 0xd5, 0xbf, 0x0e, -0x6e, 0x91, 0x7c, 0xac, 0x23, 0x36, 0x79, 0x7b, 0xbf, 0xc2, 0x96, 0x60, 0xb9, 0xe4, 0xc1, 0x9c, -0x46, 0xb8, 0x3b, 0x8c, 0xab, 0x14, 0xf7, 0xaa, 0x76, 0x41, 0x2f, 0x35, 0xb5, 0x47, 0x5f, 0xfa, -0x4a, 0x04, 0x8c, 0x4a, 0xab, 0x2f, 0xf5, 0xf0, 0xab, 0x46, 0x60, 0x88, 0xef, 0x45, 0xe6, 0x4c, -0x45, 0x1c, 0xdb, 0xa8, 0xaa, 0x01, 0x17, 0x10, 0xbb, 0xcf, 0x34, 0xb0, 0x5e, 0x9f, 0xa5, 0xe0, -0x49, 0x86, 0xad, 0xc1, 0x6f, 0xa5, 0x25, 0x84, 0x23, 0xec, 0x37, 0x4d, 0x1e, 0xd4, 0x21, 0x16, -0x06, 0x27, 0x7f, 0xaf, 0xd8, 0x48, 0xf6, 0xb2, 0xb1, 0x21, 0x5a, 0x04, 0xd1, 0x1d, 0xd1, 0x50, -0xdc, 0xa0, 0x4e, 0x18, 0x7d, 0x81, 0x3c, 0xb1, 0x2f, 0x9d, 0xb8, 0x80, 0x22, 0x85, 0x2f, 0x86, -0x2a, 0x9e, 0xa7, 0x87, 0x99, 0xd8, 0xb6, 0xde, 0x12, 0xcf, 0x79, 0xf3, 0x74, 0xe4, 0x89, 0x73, -0xbc, 0xe1, 0x1d, 0xba, 0x26, 0xc4, 0x2e, 0x9e, 0x5f, 0x8e, 0x99, 0x35, 0xe1, 0x21, 0xcf, 0xf8, -0x85, 0xb1, 0x01, 0xf2, 0x8d, 0x7b, 0x3b, 0xe4, 0xbd, 0xf4, 0xd8, 0x84, 0x4d, 0xf6, 0x1e, 0x19, -0x0b, 0x4b, 0x47, 0x7f, 0xc5, 0x8b, 0x13, 0x39, 0x00, 0xe0, 0x05, 0x15, 0xdc, 0x64, 0x27, 0x87, -0x51, 0xb1, 0x05, 0x26, 0xd2, 0xc0, 0xe0, 0xab, 0x13, 0xc4, 0x4e, 0x79, 0x94, 0x66, 0x86, 0x32, -0x98, 0x8f, 0xd3, 0xb8, 0x02, 0xbd, 0x33, 0xbd, 0x77, 0x00, 0x82, 0x10, 0xe6, 0x4c, 0x67, 0xe0, -0x9e, 0x84, 0xce, 0x42, 0x70, 0x60, 0xf2, 0xf6, 0xcc, 0xe7, 0x3e, 0xfb, 0xf9, 0xcf, 0x80, 0x0e, -0xb4, 0xa0, 0x07, 0x4d, 0xe8, 0x42, 0x97, 0x20, 0x01, 0x01, 0x00, 0x3b +// The C++ Portable Components logo in GIF format + +0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0xa0, 0x00, 0x85, 0x00, 0xa2, 0x00, 0x00, 0xd1, 0xdd, 0xe4, +0x45, 0x9b, 0xca, 0x41, 0x55, 0x61, 0x8a, 0x96, 0x9e, 0xa2, 0xbc, 0xcc, 0x00, 0x1b, 0x2c, 0x00, +0x75, 0xb6, 0xff, 0xff, 0xff, 0x21, 0xf9, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, +0x00, 0x00, 0xa0, 0x00, 0x85, 0x00, 0x00, 0x03, 0xff, 0x78, 0xba, 0xdc, 0xfe, 0x30, 0xca, 0x49, +0xab, 0xbd, 0x38, 0xeb, 0xcd, 0xbb, 0xff, 0x60, 0x28, 0x8e, 0x64, 0x69, 0x9e, 0x68, 0xaa, 0xae, +0x6c, 0xeb, 0xbe, 0x70, 0x2c, 0xcf, 0x2b, 0x40, 0xdc, 0x78, 0xae, 0xef, 0x04, 0xe0, 0xda, 0xbc, +0xe0, 0x0e, 0xe0, 0xeb, 0x00, 0x06, 0xc5, 0xc5, 0x6d, 0x72, 0x4b, 0x76, 0x08, 0x01, 0x83, 0x74, +0x4a, 0xad, 0x5a, 0xab, 0x01, 0x27, 0x09, 0x10, 0xbd, 0x7a, 0xbf, 0x86, 0x40, 0x6f, 0x33, 0x28, +0x10, 0x1a, 0x85, 0x82, 0x44, 0x90, 0x2e, 0x68, 0x2f, 0xb6, 0x2e, 0x78, 0x7e, 0x15, 0x8f, 0xe2, +0xf4, 0xbc, 0xd5, 0x8e, 0x29, 0x9f, 0x09, 0x48, 0x07, 0x69, 0x11, 0x65, 0x02, 0x6c, 0x03, 0x1b, +0x72, 0x7a, 0x8b, 0x54, 0x67, 0x1f, 0x8a, 0x8c, 0x8c, 0x59, 0x17, 0x7e, 0x82, 0x66, 0x96, 0x11, +0x69, 0x3e, 0x05, 0x02, 0x19, 0x5c, 0x91, 0xa0, 0x53, 0x8e, 0x1c, 0x90, 0xa1, 0x8b, 0xa3, 0x13, +0x95, 0x69, 0x67, 0x83, 0x0c, 0x36, 0x0a, 0x9a, 0x82, 0x9d, 0x70, 0xa6, 0xb5, 0x93, 0x19, 0x04, +0xb5, 0xb6, 0x15, 0xaa, 0x97, 0xad, 0x0b, 0x6c, 0xac, 0x6e, 0xb2, 0x17, 0xb9, 0xba, 0xb5, 0x6f, +0x12, 0xc6, 0xc7, 0xa6, 0xc9, 0x0c, 0xbd, 0x3d, 0xbf, 0x0a, 0xc1, 0x96, 0x3e, 0x44, 0x16, 0xcb, +0xcc, 0xa0, 0x01, 0xb4, 0xda, 0xa6, 0xdc, 0x12, 0x65, 0x9c, 0x69, 0x86, 0x9c, 0x0d, 0xd4, 0xb1, +0xdd, 0xde, 0xa1, 0xe0, 0x4c, 0xeb, 0xbb, 0xe1, 0x6d, 0x6d, 0x02, 0x5a, 0xe2, 0x6c, 0xb3, 0x17, +0xa5, 0xef, 0x7a, 0xed, 0x11, 0xfb, 0xb5, 0xa8, 0x1e, 0x10, 0x19, 0xe8, 0x8c, 0x0d, 0x27, 0x67, +0x10, 0xb2, 0xfd, 0x63, 0x84, 0xf0, 0x80, 0xc2, 0x85, 0x8b, 0x1a, 0xc2, 0x09, 0x48, 0x01, 0x00, +0xc4, 0x50, 0x14, 0x17, 0x58, 0xbc, 0xb8, 0x0d, 0xff, 0x83, 0x21, 0x11, 0xfa, 0xbc, 0x88, 0x21, +0x48, 0xb2, 0x24, 0x91, 0x1b, 0x21, 0xaf, 0x38, 0x7b, 0xf8, 0xa5, 0x87, 0xc9, 0x97, 0x04, 0xa1, +0x44, 0xbc, 0x20, 0x4d, 0xe3, 0x90, 0x09, 0xfc, 0x3e, 0x7c, 0xa2, 0x93, 0xf1, 0x80, 0x9e, 0x9e, +0x18, 0x36, 0xf2, 0xa4, 0xa9, 0xa6, 0x81, 0x38, 0x79, 0x35, 0x1b, 0x08, 0x05, 0x23, 0xb1, 0x58, +0x9e, 0x07, 0x2c, 0xad, 0x34, 0x75, 0x3a, 0xa7, 0xdf, 0x84, 0x9a, 0xe2, 0x06, 0x68, 0xdd, 0x8a, +0x28, 0x42, 0x54, 0x2a, 0x53, 0xf3, 0x0d, 0x6d, 0x90, 0x72, 0x4a, 0x58, 0xaa, 0x4c, 0x2d, 0xd4, +0x3c, 0x94, 0xa1, 0xac, 0x01, 0xa0, 0x1d, 0xdc, 0x5a, 0xf5, 0x39, 0x07, 0x2e, 0x87, 0xa5, 0x5e, +0xec, 0x2a, 0x00, 0xb0, 0xf6, 0x12, 0x06, 0xb7, 0x67, 0xd5, 0x7d, 0x51, 0x5a, 0x15, 0xc5, 0x57, +0x29, 0x73, 0x01, 0x71, 0x1d, 0x70, 0xef, 0x9c, 0xdf, 0x0b, 0x85, 0x4f, 0xb8, 0x25, 0x0c, 0x66, +0xae, 0x08, 0xbc, 0x7b, 0x1c, 0x1c, 0x45, 0x1a, 0x90, 0x9a, 0xe0, 0x3a, 0x28, 0x00, 0xbb, 0x8a, +0x2c, 0xb9, 0xb2, 0x03, 0x02, 0x86, 0x52, 0x0b, 0x08, 0xe4, 0x58, 0xef, 0x68, 0x30, 0xae, 0x13, +0xcd, 0x71, 0x82, 0xb9, 0x4a, 0x6c, 0xd9, 0x5f, 0x2c, 0x5b, 0xf0, 0x6c, 0xa1, 0x76, 0xa3, 0xd0, +0xb3, 0x5f, 0xb7, 0x4c, 0x51, 0x56, 0x77, 0x85, 0x57, 0x41, 0xeb, 0x02, 0x4f, 0xab, 0x51, 0xf9, +0x72, 0x91, 0x0f, 0xb2, 0xda, 0x0b, 0x0c, 0xc1, 0xb7, 0xa8, 0xe7, 0x5e, 0x28, 0x0f, 0xc7, 0x9e, +0xd9, 0x28, 0x39, 0xa4, 0xf8, 0x34, 0x1a, 0x94, 0x17, 0x5e, 0x7b, 0xde, 0x13, 0xd6, 0xa7, 0x98, +0xbf, 0x72, 0x5b, 0x43, 0x71, 0xcd, 0xbe, 0xcc, 0xf0, 0x2d, 0xcf, 0x17, 0x29, 0xb9, 0x08, 0xe9, +0xdf, 0x96, 0x36, 0x2d, 0xfc, 0x3c, 0x77, 0x2c, 0xff, 0xf0, 0x09, 0x23, 0x8c, 0x63, 0x02, 0xdc, +0x54, 0x9d, 0x73, 0x24, 0xb8, 0xa5, 0x5f, 0x7f, 0xec, 0x11, 0xc7, 0xdf, 0x33, 0xf1, 0x0d, 0xc8, +0x00, 0x6f, 0xc7, 0x21, 0x08, 0xd2, 0x53, 0xeb, 0x59, 0xd1, 0x5e, 0x5b, 0x0f, 0x2e, 0x00, 0x0d, +0x26, 0x13, 0x3e, 0x56, 0x21, 0x6c, 0x97, 0xc9, 0x44, 0xc7, 0x5c, 0xf9, 0x6d, 0xf8, 0x57, 0x87, +0x0a, 0xf8, 0x01, 0x80, 0x21, 0xd1, 0x14, 0x05, 0x8c, 0x88, 0x15, 0x39, 0xc7, 0x45, 0x00, 0x38, +0xe6, 0xa8, 0xe3, 0x8e, 0x3c, 0x46, 0x22, 0x90, 0x85, 0x25, 0xbc, 0xe7, 0x9d, 0x7d, 0x7d, 0xb5, +0x97, 0xa2, 0x02, 0x87, 0xbd, 0x93, 0xd1, 0x91, 0xff, 0x51, 0x31, 0xd7, 0x66, 0xe4, 0x11, 0x98, +0x1c, 0x89, 0x07, 0x28, 0xe8, 0x4d, 0x32, 0x4c, 0xee, 0x07, 0x9d, 0x52, 0x30, 0x35, 0x40, 0xc0, +0x3c, 0xa9, 0x99, 0x73, 0x20, 0x95, 0x56, 0x32, 0xd3, 0x53, 0x96, 0x26, 0x08, 0x79, 0x97, 0x6a, +0xe5, 0x94, 0xc7, 0xa0, 0x86, 0x0a, 0x94, 0xa9, 0x8b, 0x71, 0x68, 0x06, 0xc9, 0xa2, 0x87, 0x6c, +0x7e, 0xa4, 0x93, 0x73, 0x72, 0x9a, 0x02, 0x57, 0x9d, 0x09, 0xde, 0xf9, 0x22, 0x91, 0x32, 0x1a, +0xc1, 0x27, 0x47, 0xc6, 0xed, 0x05, 0x64, 0xa0, 0xb9, 0xc1, 0x47, 0xcf, 0x11, 0x05, 0x20, 0x51, +0x0f, 0x3d, 0xe7, 0x74, 0xf5, 0x23, 0x99, 0x17, 0x25, 0xaa, 0x28, 0x95, 0x5a, 0x82, 0xe6, 0x9d, +0x23, 0x65, 0x58, 0x1a, 0x62, 0x40, 0x49, 0x35, 0x87, 0xe9, 0x3f, 0xb7, 0x4c, 0x00, 0xe8, 0x08, +0x6a, 0x7a, 0xe8, 0x57, 0xa8, 0x0f, 0x50, 0x63, 0xc8, 0x26, 0x6e, 0x9a, 0xba, 0x5d, 0x9f, 0x3f, +0x7d, 0x06, 0x27, 0x0a, 0xa4, 0xb9, 0x0a, 0x6a, 0xa4, 0xb1, 0xc6, 0x47, 0x2b, 0x7e, 0x87, 0xae, +0x93, 0xea, 0x88, 0x8d, 0xa2, 0xd7, 0x6b, 0x8b, 0xff, 0xaf, 0x02, 0xeb, 0x00, 0x3a, 0xc3, 0x88, +0x79, 0xe9, 0x76, 0x37, 0xf2, 0x68, 0xed, 0xb5, 0x62, 0x8c, 0xa1, 0x41, 0x7e, 0x9a, 0x3e, 0xb1, +0xec, 0x01, 0x85, 0xf4, 0x10, 0xea, 0x35, 0xa3, 0x56, 0x43, 0xcc, 0x98, 0xdb, 0xd1, 0x60, 0xeb, +0x60, 0x27, 0x8c, 0xe5, 0x0a, 0xa1, 0xe5, 0x1d, 0x52, 0x9f, 0x0d, 0xd2, 0x3a, 0xb0, 0xea, 0x0c, +0xee, 0x8e, 0x90, 0xa4, 0x01, 0xc9, 0xa0, 0x66, 0x5f, 0x79, 0x50, 0xb6, 0x21, 0x6a, 0x86, 0xb6, +0xa9, 0x4b, 0x56, 0xbe, 0x20, 0xe4, 0x17, 0x86, 0x04, 0x26, 0x9d, 0x96, 0xe7, 0xc0, 0x04, 0xff, +0x66, 0xb0, 0x12, 0x79, 0x50, 0xe7, 0x55, 0x1e, 0x2a, 0xee, 0xc9, 0xe9, 0xc4, 0x74, 0x21, 0xbc, +0xc1, 0xbe, 0x52, 0x38, 0x73, 0x44, 0x9e, 0xb5, 0x7a, 0xb2, 0xa8, 0xba, 0x20, 0x23, 0x86, 0xed, +0xca, 0x38, 0x2e, 0xa2, 0x5b, 0x7d, 0xff, 0xda, 0xcb, 0x18, 0x9b, 0x10, 0xaf, 0xdb, 0x20, 0xc7, +0x0b, 0xe0, 0xca, 0x51, 0x4f, 0x85, 0x48, 0x34, 0x28, 0x91, 0xc4, 0x6e, 0xcc, 0x71, 0xca, 0x1c, +0x21, 0x46, 0x08, 0x8d, 0xd1, 0x71, 0x32, 0x80, 0x62, 0x5a, 0x01, 0x75, 0xaf, 0xba, 0x3a, 0xa3, +0x1a, 0x8f, 0x5e, 0x14, 0xd6, 0x28, 0x34, 0xc7, 0x0a, 0x17, 0xcd, 0xef, 0xd4, 0x14, 0x54, 0xad, +0xea, 0xc9, 0x13, 0x13, 0xbd, 0x90, 0xa6, 0x95, 0x4c, 0xe0, 0x35, 0xc3, 0x60, 0x4f, 0x9c, 0xf5, +0x42, 0x7a, 0x95, 0xbd, 0x06, 0xd2, 0x68, 0x5f, 0x8d, 0xb3, 0x43, 0x5a, 0xef, 0xca, 0x04, 0xa5, +0x66, 0xd7, 0x6b, 0x75, 0xba, 0x73, 0x33, 0x60, 0xa2, 0xd6, 0x7c, 0xe8, 0x4b, 0x0e, 0xcd, 0x41, +0xf3, 0xdd, 0xb7, 0xdf, 0x5a, 0xab, 0x38, 0xf3, 0x9f, 0xe3, 0xcd, 0x53, 0xb8, 0x7f, 0x87, 0xdb, +0x1b, 0x75, 0x1e, 0xc7, 0xee, 0x26, 0x4f, 0xc6, 0xff, 0x11, 0x94, 0x65, 0x31, 0x0d, 0x71, 0xb4, +0x6c, 0x0b, 0x8e, 0xda, 0xe2, 0xa2, 0xf4, 0x3d, 0x38, 0x44, 0x6e, 0xfa, 0x0c, 0x65, 0x37, 0x0e, +0x95, 0x6a, 0xac, 0x9d, 0xee, 0xfa, 0x07, 0xa9, 0x93, 0x03, 0x71, 0xe3, 0xe4, 0x6c, 0xfe, 0xfa, +0xed, 0xe0, 0xfa, 0xc5, 0x46, 0x32, 0xe1, 0xe2, 0xc0, 0x16, 0xee, 0xc0, 0x53, 0xa2, 0x7b, 0xa1, +0xe5, 0x6a, 0xa4, 0x77, 0xf0, 0xc8, 0x27, 0x4d, 0xa9, 0x56, 0x10, 0x54, 0x7d, 0xbc, 0x11, 0x4c, +0x2f, 0x26, 0xfd, 0xf4, 0xd4, 0x6b, 0x65, 0xbb, 0x40, 0xd1, 0x57, 0x4f, 0x7d, 0xe8, 0x1b, 0xfc, +0x0c, 0x5e, 0x6b, 0x68, 0x94, 0x3c, 0x11, 0xed, 0x84, 0x96, 0x6f, 0xfe, 0x7d, 0x1e, 0xd8, 0x40, +0xfe, 0xf9, 0xe5, 0xaf, 0x66, 0xfb, 0xc8, 0x79, 0x82, 0xcf, 0xc0, 0xf3, 0xbd, 0x05, 0xcc, 0xfe, +0xfd, 0x40, 0x77, 0x60, 0x3f, 0xfe, 0xe7, 0xb7, 0x5e, 0xc2, 0xef, 0x48, 0xa2, 0x9f, 0xaa, 0xd6, +0xc7, 0xbf, 0x02, 0x96, 0xaa, 0x22, 0x04, 0x34, 0xe0, 0xf9, 0xf0, 0x16, 0x94, 0x81, 0x24, 0x64, +0x70, 0xe5, 0x80, 0x1b, 0x13, 0x14, 0x48, 0x41, 0xa4, 0x6c, 0x2b, 0x81, 0x15, 0x34, 0x5f, 0xcd, +0x12, 0x42, 0xbb, 0x9a, 0xf9, 0x4b, 0x1e, 0x1b, 0x8c, 0x47, 0x06, 0x33, 0x28, 0xba, 0x11, 0x52, +0xd0, 0x35, 0x30, 0x43, 0xca, 0x06, 0x09, 0xb2, 0x01, 0x0c, 0x9a, 0xf0, 0x7c, 0x7d, 0x78, 0x61, +0x05, 0xc5, 0xe7, 0xaa, 0x47, 0x11, 0xa1, 0x10, 0x26, 0x70, 0xa1, 0x0c, 0xcb, 0x27, 0xbc, 0x1d, +0x52, 0x90, 0x86, 0xb9, 0x23, 0x15, 0xf1, 0x90, 0x64, 0x3d, 0x0d, 0xec, 0xcf, 0x87, 0x30, 0xac, +0xc0, 0x97, 0x90, 0x78, 0x42, 0xae, 0xcd, 0x6f, 0x88, 0xe3, 0x61, 0xa0, 0x12, 0x99, 0xa8, 0xc0, +0xe3, 0x50, 0xb1, 0x82, 0x08, 0x71, 0x1b, 0x2c, 0xff, 0x88, 0x17, 0xae, 0xc6, 0x5c, 0x40, 0x87, +0x57, 0x94, 0x07, 0x2f, 0xc2, 0xa8, 0x40, 0xf1, 0x69, 0xb1, 0x3e, 0xf2, 0x13, 0x20, 0x7c, 0xc8, +0x78, 0x3f, 0x20, 0x1e, 0x20, 0x85, 0x6c, 0xc4, 0xdf, 0x06, 0x7b, 0x77, 0x03, 0x2f, 0xce, 0xc8, +0x11, 0x7a, 0xaa, 0x08, 0xff, 0x0a, 0xe4, 0x12, 0x98, 0xf8, 0xb1, 0x4b, 0x5d, 0xc3, 0xdf, 0x6a, +0xfa, 0xf8, 0xc7, 0x98, 0x30, 0x86, 0x7f, 0x05, 0x21, 0x52, 0x67, 0x74, 0xe7, 0xc6, 0x69, 0xb4, +0xf1, 0x7a, 0x20, 0x58, 0x22, 0xfb, 0x42, 0xd8, 0x43, 0xf6, 0x01, 0x65, 0x66, 0x86, 0xf0, 0x9f, +0x23, 0x1d, 0x71, 0x40, 0xa5, 0x3c, 0xd2, 0x60, 0x3a, 0x94, 0xa2, 0x07, 0x3e, 0xa8, 0x41, 0x0f, +0xdc, 0x83, 0x08, 0xb3, 0x22, 0xd7, 0x03, 0x17, 0xa8, 0x36, 0xf6, 0x89, 0x12, 0x04, 0x2e, 0xa4, +0xa1, 0x2a, 0xa1, 0x02, 0x2f, 0x11, 0xb6, 0x0f, 0x6b, 0x96, 0x34, 0x81, 0x24, 0xcb, 0xd7, 0x2f, +0x81, 0x29, 0x83, 0x7c, 0x34, 0x3c, 0x62, 0x1a, 0x28, 0xe9, 0x82, 0x5d, 0x12, 0xa9, 0x91, 0x2d, +0x3c, 0x1f, 0x45, 0xea, 0x63, 0x10, 0x62, 0x66, 0xc0, 0x85, 0x90, 0x14, 0x81, 0x31, 0xed, 0xe3, +0x4c, 0x0e, 0x08, 0xd3, 0x59, 0x10, 0x42, 0x04, 0x1a, 0x47, 0x00, 0x4d, 0x8e, 0x5d, 0xb3, 0x9a, +0xdd, 0xeb, 0x5f, 0x80, 0x1c, 0xf9, 0x4b, 0xc2, 0x45, 0xc0, 0x85, 0x38, 0xfb, 0x66, 0x0a, 0x58, +0xf9, 0x29, 0x72, 0x0a, 0x64, 0x7d, 0x34, 0xc4, 0x20, 0x32, 0x57, 0xa0, 0x4e, 0x14, 0xb0, 0x13, +0x42, 0x78, 0x1c, 0xa2, 0x23, 0x0b, 0x54, 0x92, 0xb7, 0xdd, 0xd2, 0x9b, 0xe2, 0xb4, 0xa7, 0xf9, +0xdc, 0x04, 0xab, 0x03, 0xe4, 0x51, 0x7e, 0x5f, 0x1c, 0x68, 0x3a, 0x03, 0x7a, 0x82, 0x7b, 0x2a, +0x61, 0x98, 0xd2, 0x43, 0xa8, 0xe5, 0xfe, 0x39, 0xff, 0xb1, 0x7a, 0x36, 0x54, 0xa1, 0x6b, 0xb4, +0x8f, 0x44, 0x2b, 0x20, 0xcf, 0x85, 0x96, 0x52, 0xa0, 0x14, 0x55, 0x8a, 0xf4, 0x16, 0xb9, 0xa1, +0x8e, 0x02, 0xf4, 0xa3, 0x26, 0x80, 0x63, 0xcc, 0x38, 0x60, 0xc7, 0x89, 0xd6, 0xf2, 0xa4, 0xe5, +0x03, 0xe7, 0xb6, 0x1c, 0x5a, 0x42, 0x4e, 0xb0, 0xc9, 0x9f, 0x2f, 0xad, 0x28, 0x43, 0x4b, 0xa0, +0xd2, 0xef, 0xdd, 0x25, 0xa7, 0xc1, 0x0a, 0xa9, 0xba, 0x2c, 0xca, 0x53, 0x9a, 0x7a, 0xe4, 0x20, +0xfd, 0x3c, 0x27, 0x46, 0x75, 0x8a, 0xd2, 0xa2, 0x2e, 0x55, 0x03, 0x67, 0xc3, 0xe9, 0x31, 0x3d, +0x1a, 0x53, 0x14, 0xf4, 0x34, 0x4a, 0x2c, 0x95, 0xa0, 0x52, 0x85, 0x4a, 0x03, 0xa2, 0x6e, 0xc1, +0xa8, 0x46, 0xd9, 0xe0, 0x3d, 0x46, 0x2a, 0xd5, 0x95, 0x32, 0xb5, 0xaa, 0xe8, 0x01, 0xeb, 0x13, +0xab, 0xc3, 0xc3, 0xad, 0x02, 0x75, 0xa8, 0x3b, 0xfd, 0xea, 0x53, 0x95, 0xb2, 0xc4, 0x26, 0xd8, +0x8b, 0x64, 0xf1, 0x9c, 0x6b, 0x57, 0xe3, 0x7a, 0x07, 0xb5, 0x1a, 0x54, 0x85, 0x21, 0x30, 0xe9, +0x59, 0x09, 0x25, 0x53, 0x4f, 0xf8, 0xf5, 0x90, 0x91, 0xd2, 0x64, 0x56, 0xb9, 0x8a, 0x3a, 0xbe, +0x5e, 0xc6, 0xaf, 0x5b, 0xc4, 0x0f, 0x26, 0x07, 0x99, 0x37, 0xf3, 0x51, 0x95, 0xb0, 0x86, 0x81, +0x2c, 0xb8, 0x36, 0x38, 0xcd, 0x55, 0x94, 0xd5, 0x3e, 0xd1, 0x0c, 0x81, 0x57, 0x47, 0x30, 0xda, +0x84, 0xe2, 0x0d, 0x52, 0x79, 0x35, 0x5f, 0x68, 0x23, 0xa9, 0xd9, 0x0e, 0xb8, 0x90, 0x98, 0xb3, +0x2c, 0xde, 0x5e, 0xd4, 0x58, 0xda, 0x18, 0x74, 0x16, 0xab, 0x4e, 0x55, 0x6d, 0xde, 0x9a, 0x47, +0x23, 0xda, 0xb2, 0x6f, 0xb5, 0xe9, 0xfb, 0xad, 0x09, 0xae, 0xa9, 0x4f, 0x57, 0xec, 0x2e, 0x58, +0xa4, 0xa2, 0xe1, 0x6d, 0xc9, 0x03, 0xdc, 0x0e, 0xff, 0xb8, 0xb2, 0xb9, 0x0e, 0x71, 0x65, 0x59, +0x49, 0xfa, 0x2e, 0x59, 0xe2, 0x0f, 0xba, 0x46, 0xbc, 0x1f, 0x70, 0x89, 0xab, 0xd5, 0xbf, 0x0e, +0x6e, 0x91, 0x7c, 0xac, 0x23, 0x36, 0x79, 0x7b, 0xbf, 0xc2, 0x96, 0x60, 0xb9, 0xe4, 0xc1, 0x9c, +0x46, 0xb8, 0x3b, 0x8c, 0xab, 0x14, 0xf7, 0xaa, 0x76, 0x41, 0x2f, 0x35, 0xb5, 0x47, 0x5f, 0xfa, +0x4a, 0x04, 0x8c, 0x4a, 0xab, 0x2f, 0xf5, 0xf0, 0xab, 0x46, 0x60, 0x88, 0xef, 0x45, 0xe6, 0x4c, +0x45, 0x1c, 0xdb, 0xa8, 0xaa, 0x01, 0x17, 0x10, 0xbb, 0xcf, 0x34, 0xb0, 0x5e, 0x9f, 0xa5, 0xe0, +0x49, 0x86, 0xad, 0xc1, 0x6f, 0xa5, 0x25, 0x84, 0x23, 0xec, 0x37, 0x4d, 0x1e, 0xd4, 0x21, 0x16, +0x06, 0x27, 0x7f, 0xaf, 0xd8, 0x48, 0xf6, 0xb2, 0xb1, 0x21, 0x5a, 0x04, 0xd1, 0x1d, 0xd1, 0x50, +0xdc, 0xa0, 0x4e, 0x18, 0x7d, 0x81, 0x3c, 0xb1, 0x2f, 0x9d, 0xb8, 0x80, 0x22, 0x85, 0x2f, 0x86, +0x2a, 0x9e, 0xa7, 0x87, 0x99, 0xd8, 0xb6, 0xde, 0x12, 0xcf, 0x79, 0xf3, 0x74, 0xe4, 0x89, 0x73, +0xbc, 0xe1, 0x1d, 0xba, 0x26, 0xc4, 0x2e, 0x9e, 0x5f, 0x8e, 0x99, 0x35, 0xe1, 0x21, 0xcf, 0xf8, +0x85, 0xb1, 0x01, 0xf2, 0x8d, 0x7b, 0x3b, 0xe4, 0xbd, 0xf4, 0xd8, 0x84, 0x4d, 0xf6, 0x1e, 0x19, +0x0b, 0x4b, 0x47, 0x7f, 0xc5, 0x8b, 0x13, 0x39, 0x00, 0xe0, 0x05, 0x15, 0xdc, 0x64, 0x27, 0x87, +0x51, 0xb1, 0x05, 0x26, 0xd2, 0xc0, 0xe0, 0xab, 0x13, 0xc4, 0x4e, 0x79, 0x94, 0x66, 0x86, 0x32, +0x98, 0x8f, 0xd3, 0xb8, 0x02, 0xbd, 0x33, 0xbd, 0x77, 0x00, 0x82, 0x10, 0xe6, 0x4c, 0x67, 0xe0, +0x9e, 0x84, 0xce, 0x42, 0x70, 0x60, 0xf2, 0xf6, 0xcc, 0xe7, 0x3e, 0xfb, 0xf9, 0xcf, 0x80, 0x0e, +0xb4, 0xa0, 0x07, 0x4d, 0xe8, 0x42, 0x97, 0x20, 0x01, 0x01, 0x00, 0x3b diff --git a/Net/samples/Makefile b/Net/samples/Makefile index 8df63d3ee..b3a970711 100644 --- a/Net/samples/Makefile +++ b/Net/samples/Makefile @@ -1,21 +1,21 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/Makefile#2 $ -# -# Makefile for Poco Net Samples -# - -.PHONY: projects -clean all: projects -projects: - $(MAKE) -C dict $(MAKECMDGOALS) - $(MAKE) -C TimeServer $(MAKECMDGOALS) - $(MAKE) -C httpget $(MAKECMDGOALS) - $(MAKE) -C HTTPTimeServer $(MAKECMDGOALS) - $(MAKE) -C HTTPFormServer $(MAKECMDGOALS) - $(MAKE) -C HTTPLoadTest $(MAKECMDGOALS) - $(MAKE) -C download $(MAKECMDGOALS) - $(MAKE) -C EchoServer $(MAKECMDGOALS) - $(MAKE) -C Mail $(MAKECMDGOALS) - $(MAKE) -C Ping $(MAKECMDGOALS) +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/Makefile#2 $ +# +# Makefile for Poco Net Samples +# + +.PHONY: projects +clean all: projects +projects: + $(MAKE) -C dict $(MAKECMDGOALS) + $(MAKE) -C TimeServer $(MAKECMDGOALS) + $(MAKE) -C httpget $(MAKECMDGOALS) + $(MAKE) -C HTTPTimeServer $(MAKECMDGOALS) + $(MAKE) -C HTTPFormServer $(MAKECMDGOALS) + $(MAKE) -C HTTPLoadTest $(MAKECMDGOALS) + $(MAKE) -C download $(MAKECMDGOALS) + $(MAKE) -C EchoServer $(MAKECMDGOALS) + $(MAKE) -C Mail $(MAKECMDGOALS) + $(MAKE) -C Ping $(MAKECMDGOALS) diff --git a/Net/samples/Ping/Makefile b/Net/samples/Ping/Makefile index 6909b02ed..1c5dd436c 100644 --- a/Net/samples/Ping/Makefile +++ b/Net/samples/Ping/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/Ping/Makefile#1 $ -# -# Makefile for Poco ping -# - -include $(POCO_BASE)/build/rules/global - -objects = Ping - -target = Ping -target_version = 1 -target_libs = PocoFoundation PocoXML PocoUtil PocoNet - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/Ping/Makefile#1 $ +# +# Makefile for Poco ping +# + +include $(POCO_BASE)/build/rules/global + +objects = Ping + +target = Ping +target_version = 1 +target_libs = PocoFoundation PocoXML PocoUtil PocoNet + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/Ping/Ping.vmsbuild b/Net/samples/Ping/Ping.vmsbuild index ab811c0c7..f5c3db3e0 100644 --- a/Net/samples/Ping/Ping.vmsbuild +++ b/Net/samples/Ping/Ping.vmsbuild @@ -1,7 +1,7 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Net/samples/Ping/Ping.vmsbuild#1 $ -# -EXE=Ping -Ping +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Net/samples/Ping/Ping.vmsbuild#1 $ +# +EXE=Ping +Ping diff --git a/Net/samples/Ping/Ping_vs71.vcproj b/Net/samples/Ping/Ping_vs71.vcproj index d5811545a..741d69bb9 100644 --- a/Net/samples/Ping/Ping_vs71.vcproj +++ b/Net/samples/Ping/Ping_vs71.vcproj @@ -1,152 +1,152 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/Ping/Ping_vs80.vcproj b/Net/samples/Ping/Ping_vs80.vcproj index aad1b1f5e..33098b71a 100644 --- a/Net/samples/Ping/Ping_vs80.vcproj +++ b/Net/samples/Ping/Ping_vs80.vcproj @@ -1,217 +1,217 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/Ping/ping.properties b/Net/samples/Ping/ping.properties index 58962c60a..4ec401d48 100644 --- a/Net/samples/Ping/ping.properties +++ b/Net/samples/Ping/ping.properties @@ -1,8 +1,8 @@ -# This is a sample configuration file. -logging.loggers.root.channel.class = ConsoleChannel -logging.loggers.app.name = Application -logging.loggers.app.channel = c1 -logging.formatters.f1.class = PatternFormatter -logging.formatters.f1.pattern = %t -logging.channels.c1.class = ConsoleChannel -logging.channels.c1.formatter = f1 +# This is a sample configuration file. +logging.loggers.root.channel.class = ConsoleChannel +logging.loggers.app.name = Application +logging.loggers.app.channel = c1 +logging.formatters.f1.class = PatternFormatter +logging.formatters.f1.pattern = %t +logging.channels.c1.class = ConsoleChannel +logging.channels.c1.formatter = f1 diff --git a/Net/samples/Ping/src/Ping.cpp b/Net/samples/Ping/src/Ping.cpp index f8307047a..013148278 100644 --- a/Net/samples/Ping/src/Ping.cpp +++ b/Net/samples/Ping/src/Ping.cpp @@ -1,219 +1,219 @@ -// -// Ping.cpp -// -// $Id: //poco/1.2/Net/samples/Ping/src/Ping.cpp#1 $ -// -// This sample demonstrates the Application class. -// -// Copyright (c) 2004-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/Util/Application.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/HelpFormatter.h" -#include "Poco/Util/AbstractConfiguration.h" -#include "Poco/Net/ICMPSocket.h" -#include "Poco/Net/ICMPClient.h" -#include "Poco/Net/IPAddress.h" -#include "Poco/Net/ICMPEventArgs.h" -#include "Poco/AutoPtr.h" -#include "Poco/NumberParser.h" -#include "Poco/Delegate.h" -#include -#include - - -using Poco::Util::Application; -using Poco::Util::Option; -using Poco::Util::OptionSet; -using Poco::Util::HelpFormatter; -using Poco::Util::AbstractConfiguration; -using Poco::Net::ICMPSocket; -using Poco::Net::ICMPClient; -using Poco::Net::IPAddress; -using Poco::Net::ICMPEventArgs; -using Poco::AutoPtr; -using Poco::NumberParser; -using Poco::Delegate; - - -class Ping: public Application - /// This sample demonstrates the Poco::Net::ICMPClient in conjunction with - /// Poco Foundation C#-like events functionality. - /// - /// Try Ping --help (on Unix platforms) or Ping /help (elsewhere) for - /// more information. -{ -public: - Ping(): - _helpRequested(false), - _icmpClient(IPAddress::IPv4), - _repetitions(4), - _target("localhost") - { - } - -protected: - void initialize(Application& self) - { - loadConfiguration(); // load default configuration files, if present - Application::initialize(self); - - _icmpClient.pingBegin += Delegate(this, &Ping::onBegin); - _icmpClient.pingReply += Delegate(this, &Ping::onReply); - _icmpClient.pingError += Delegate(this, &Ping::onError); - _icmpClient.pingEnd += Delegate(this, &Ping::onEnd); - } - - void uninitialize() - { - _icmpClient.pingBegin -= Delegate(this, &Ping::onBegin); - _icmpClient.pingReply -= Delegate(this, &Ping::onReply); - _icmpClient.pingError -= Delegate(this, &Ping::onError); - _icmpClient.pingEnd -= Delegate(this, &Ping::onEnd); - - Application::uninitialize(); - } - - void defineOptions(OptionSet& options) - { - Application::defineOptions(options); - - options.addOption( - Option("help", "h", "display help information on command line arguments") - .required(false) - .repeatable(false)); - - options.addOption( - Option("repetitions", "r", "define the number of repetitions") - .required(false) - .repeatable(false) - .argument("repetitions")); - - options.addOption( - Option("target", "t", "define the target address") - .required(false) - .repeatable(false) - .argument("target")); - } - - void handleOption(const std::string& name, const std::string& value) - { - Application::handleOption(name, value); - - if (name == "help") - _helpRequested = true; - else if (name == "repetitions") - _repetitions = NumberParser::parse(value); - else if (name == "target") - _target = value; - } - - void displayHelp() - { - HelpFormatter helpFormatter(options()); - helpFormatter.setCommand(commandName()); - helpFormatter.setUsage("OPTIONS"); - helpFormatter.setHeader( - "A sample application that demonstrates the functionality of the " - "Poco::Net::ICMPClient class in conjunction with Poco::Events package functionality."); - helpFormatter.format(std::cout); - } - - - int main(const std::vector& args) - { - if (_helpRequested) - displayHelp(); - else - _icmpClient.ping(_target, _repetitions); - - return Application::EXIT_OK; - } - - - void onBegin(const void* pSender, ICMPEventArgs& args) - { - std::ostringstream os; - os << "Pinging " << args.hostName() << " [" << args.hostAddress() << "] with " << args.dataSize() << " bytes of data:" - << std::endl << "---------------------------------------------" << std::endl; - logger().information(os.str()); - } - - void onReply(const void* pSender, ICMPEventArgs& args) - { - std::ostringstream os; - os << "Reply from " << args.hostAddress() - << " bytes=" << args.dataSize() - << " time=" << args.replyTime() << "ms" - << " TTL=" << args.ttl(); - logger().information(os.str()); - } - - void onError(const void* pSender, ICMPEventArgs& args) - { - std::ostringstream os; - os << args.error(); - logger().information(os.str()); - } - - void onEnd(const void* pSender, ICMPEventArgs& args) - { - std::ostringstream os; - os << std::endl << "--- Ping statistics for " << args.hostName() << " ---" - << std::endl << "Packets: Sent=" << args.sent() << ", Received=" << args.received() - << " Lost=" << args.repetitions() - args.received() << " (" << 100.0 - args.percent() << "% loss)," - << std::endl << "Approximate round trip times in milliseconds: " << std::endl - << "Minimum=" << args.minRTT() << "ms, Maximum=" << args.maxRTT() - << "ms, Average=" << args.avgRTT() << "ms" - << std::endl << "------------------------------------------"; - logger().information(os.str()); - } - -private: - bool _helpRequested; - ICMPClient _icmpClient; - int _repetitions; - std::string _target; -}; - - -int main(int argc, char** argv) -{ - AutoPtr pApp = new Ping; - try - { - pApp->init(argc, argv); - } - catch (Poco::Exception& exc) - { - pApp->logger().log(exc); - return Application::EXIT_CONFIG; - } - return pApp->run(); -} +// +// Ping.cpp +// +// $Id: //poco/1.2/Net/samples/Ping/src/Ping.cpp#1 $ +// +// This sample demonstrates the Application class. +// +// Copyright (c) 2004-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/Util/Application.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/HelpFormatter.h" +#include "Poco/Util/AbstractConfiguration.h" +#include "Poco/Net/ICMPSocket.h" +#include "Poco/Net/ICMPClient.h" +#include "Poco/Net/IPAddress.h" +#include "Poco/Net/ICMPEventArgs.h" +#include "Poco/AutoPtr.h" +#include "Poco/NumberParser.h" +#include "Poco/Delegate.h" +#include +#include + + +using Poco::Util::Application; +using Poco::Util::Option; +using Poco::Util::OptionSet; +using Poco::Util::HelpFormatter; +using Poco::Util::AbstractConfiguration; +using Poco::Net::ICMPSocket; +using Poco::Net::ICMPClient; +using Poco::Net::IPAddress; +using Poco::Net::ICMPEventArgs; +using Poco::AutoPtr; +using Poco::NumberParser; +using Poco::Delegate; + + +class Ping: public Application + /// This sample demonstrates the Poco::Net::ICMPClient in conjunction with + /// Poco Foundation C#-like events functionality. + /// + /// Try Ping --help (on Unix platforms) or Ping /help (elsewhere) for + /// more information. +{ +public: + Ping(): + _helpRequested(false), + _icmpClient(IPAddress::IPv4), + _repetitions(4), + _target("localhost") + { + } + +protected: + void initialize(Application& self) + { + loadConfiguration(); // load default configuration files, if present + Application::initialize(self); + + _icmpClient.pingBegin += Delegate(this, &Ping::onBegin); + _icmpClient.pingReply += Delegate(this, &Ping::onReply); + _icmpClient.pingError += Delegate(this, &Ping::onError); + _icmpClient.pingEnd += Delegate(this, &Ping::onEnd); + } + + void uninitialize() + { + _icmpClient.pingBegin -= Delegate(this, &Ping::onBegin); + _icmpClient.pingReply -= Delegate(this, &Ping::onReply); + _icmpClient.pingError -= Delegate(this, &Ping::onError); + _icmpClient.pingEnd -= Delegate(this, &Ping::onEnd); + + Application::uninitialize(); + } + + void defineOptions(OptionSet& options) + { + Application::defineOptions(options); + + options.addOption( + Option("help", "h", "display help information on command line arguments") + .required(false) + .repeatable(false)); + + options.addOption( + Option("repetitions", "r", "define the number of repetitions") + .required(false) + .repeatable(false) + .argument("repetitions")); + + options.addOption( + Option("target", "t", "define the target address") + .required(false) + .repeatable(false) + .argument("target")); + } + + void handleOption(const std::string& name, const std::string& value) + { + Application::handleOption(name, value); + + if (name == "help") + _helpRequested = true; + else if (name == "repetitions") + _repetitions = NumberParser::parse(value); + else if (name == "target") + _target = value; + } + + void displayHelp() + { + HelpFormatter helpFormatter(options()); + helpFormatter.setCommand(commandName()); + helpFormatter.setUsage("OPTIONS"); + helpFormatter.setHeader( + "A sample application that demonstrates the functionality of the " + "Poco::Net::ICMPClient class in conjunction with Poco::Events package functionality."); + helpFormatter.format(std::cout); + } + + + int main(const std::vector& args) + { + if (_helpRequested) + displayHelp(); + else + _icmpClient.ping(_target, _repetitions); + + return Application::EXIT_OK; + } + + + void onBegin(const void* pSender, ICMPEventArgs& args) + { + std::ostringstream os; + os << "Pinging " << args.hostName() << " [" << args.hostAddress() << "] with " << args.dataSize() << " bytes of data:" + << std::endl << "---------------------------------------------" << std::endl; + logger().information(os.str()); + } + + void onReply(const void* pSender, ICMPEventArgs& args) + { + std::ostringstream os; + os << "Reply from " << args.hostAddress() + << " bytes=" << args.dataSize() + << " time=" << args.replyTime() << "ms" + << " TTL=" << args.ttl(); + logger().information(os.str()); + } + + void onError(const void* pSender, ICMPEventArgs& args) + { + std::ostringstream os; + os << args.error(); + logger().information(os.str()); + } + + void onEnd(const void* pSender, ICMPEventArgs& args) + { + std::ostringstream os; + os << std::endl << "--- Ping statistics for " << args.hostName() << " ---" + << std::endl << "Packets: Sent=" << args.sent() << ", Received=" << args.received() + << " Lost=" << args.repetitions() - args.received() << " (" << 100.0 - args.percent() << "% loss)," + << std::endl << "Approximate round trip times in milliseconds: " << std::endl + << "Minimum=" << args.minRTT() << "ms, Maximum=" << args.maxRTT() + << "ms, Average=" << args.avgRTT() << "ms" + << std::endl << "------------------------------------------"; + logger().information(os.str()); + } + +private: + bool _helpRequested; + ICMPClient _icmpClient; + int _repetitions; + std::string _target; +}; + + +int main(int argc, char** argv) +{ + AutoPtr pApp = new Ping; + try + { + pApp->init(argc, argv); + } + catch (Poco::Exception& exc) + { + pApp->logger().log(exc); + return Application::EXIT_CONFIG; + } + return pApp->run(); +} diff --git a/Net/samples/TimeServer/Makefile b/Net/samples/TimeServer/Makefile index 3454bba37..121dc986e 100644 --- a/Net/samples/TimeServer/Makefile +++ b/Net/samples/TimeServer/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/TimeServer/Makefile#1 $ -# -# Makefile for Poco TimeServer -# - -include $(POCO_BASE)/build/rules/global - -objects = TimeServer - -target = TimeServer -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/TimeServer/Makefile#1 $ +# +# Makefile for Poco TimeServer +# + +include $(POCO_BASE)/build/rules/global + +objects = TimeServer + +target = TimeServer +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/TimeServer/TimeServer.properties b/Net/samples/TimeServer/TimeServer.properties index 54b1969e4..a32eefd2c 100644 --- a/Net/samples/TimeServer/TimeServer.properties +++ b/Net/samples/TimeServer/TimeServer.properties @@ -1,11 +1,11 @@ -# This is a sample configuration file for TimeServer - -logging.loggers.root.channel.class = ConsoleChannel -logging.loggers.app.name = Application -logging.loggers.app.channel = c1 -logging.formatters.f1.class = PatternFormatter -logging.formatters.f1.pattern = [%p] %t -logging.channels.c1.class = ConsoleChannel -logging.channels.c1.formatter = f1 -# TimeServer.format = %W, %e %b %y %H:%M:%S %Z -# TimeServer.port = 9911 +# This is a sample configuration file for TimeServer + +logging.loggers.root.channel.class = ConsoleChannel +logging.loggers.app.name = Application +logging.loggers.app.channel = c1 +logging.formatters.f1.class = PatternFormatter +logging.formatters.f1.pattern = [%p] %t +logging.channels.c1.class = ConsoleChannel +logging.channels.c1.formatter = f1 +# TimeServer.format = %W, %e %b %y %H:%M:%S %Z +# TimeServer.port = 9911 diff --git a/Net/samples/TimeServer/TimeServer.vmsbuild b/Net/samples/TimeServer/TimeServer.vmsbuild index 6a41765f0..c589f4c75 100644 --- a/Net/samples/TimeServer/TimeServer.vmsbuild +++ b/Net/samples/TimeServer/TimeServer.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Net/samples/TimeServer/TimeServer.vmsbuild#1 $ -# -EXE=TimeServer -TimeServer - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Net/samples/TimeServer/TimeServer.vmsbuild#1 $ +# +EXE=TimeServer +TimeServer + diff --git a/Net/samples/TimeServer/TimeServer_vs71.vcproj b/Net/samples/TimeServer/TimeServer_vs71.vcproj index af61aff58..9c5d25c1b 100644 --- a/Net/samples/TimeServer/TimeServer_vs71.vcproj +++ b/Net/samples/TimeServer/TimeServer_vs71.vcproj @@ -1,152 +1,152 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/TimeServer/TimeServer_vs80.vcproj b/Net/samples/TimeServer/TimeServer_vs80.vcproj index d12b35db5..05937672d 100644 --- a/Net/samples/TimeServer/TimeServer_vs80.vcproj +++ b/Net/samples/TimeServer/TimeServer_vs80.vcproj @@ -1,217 +1,217 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/TimeServer/src/TimeServer.cpp b/Net/samples/TimeServer/src/TimeServer.cpp index 118148075..3c2ca8b56 100644 --- a/Net/samples/TimeServer/src/TimeServer.cpp +++ b/Net/samples/TimeServer/src/TimeServer.cpp @@ -1,222 +1,222 @@ -// -// TimeServer.cpp -// -// $Id: //poco/1.2/Net/samples/TimeServer/src/TimeServer.cpp#1 $ -// -// This sample demonstrates the TCPServer and ServerSocket classes. -// -// 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/TCPServerConnection.h" -#include "Poco/Net/TCPServerConnectionFactory.h" -#include "Poco/Net/TCPServerParams.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Timestamp.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/Exception.h" -#include "Poco/Util/ServerApplication.h" -#include "Poco/Util/Option.h" -#include "Poco/Util/OptionSet.h" -#include "Poco/Util/HelpFormatter.h" -#include - - -using Poco::Net::ServerSocket; -using Poco::Net::StreamSocket; -using Poco::Net::TCPServerConnection; -using Poco::Net::TCPServerConnectionFactory; -using Poco::Net::TCPServer; -using Poco::Timestamp; -using Poco::DateTimeFormatter; -using Poco::DateTimeFormat; -using Poco::Util::ServerApplication; -using Poco::Util::Application; -using Poco::Util::Option; -using Poco::Util::OptionSet; -using Poco::Util::HelpFormatter; - - -class TimeServerConnection: public TCPServerConnection - /// This class handles all client connections. - /// - /// A string with the current date and time is sent back to the client. -{ -public: - TimeServerConnection(const StreamSocket& s, const std::string& format): - TCPServerConnection(s), - _format(format) - { - } - - void run() - { - Application& app = Application::instance(); - app.logger().information("Request from " + this->socket().peerAddress().toString()); - try - { - Timestamp now; - std::string dt(DateTimeFormatter::format(now, _format)); - dt.append("\r\n"); - socket().sendBytes(dt.data(), (int) dt.length()); - } - catch (Poco::Exception& exc) - { - app.logger().log(exc); - } - } - -private: - std::string _format; -}; - - -class TimeServerConnectionFactory: public TCPServerConnectionFactory - /// A factory for TimeServerConnection. -{ -public: - TimeServerConnectionFactory(const std::string& format): - _format(format) - { - } - - TCPServerConnection* createConnection(const StreamSocket& socket) - { - return new TimeServerConnection(socket, _format); - } - -private: - std::string _format; -}; - - -class TimeServer: public Poco::Util::ServerApplication - /// The main application class. - /// - /// This class handles command-line arguments and - /// configuration files. - /// Start the TimeServer executable with the help - /// option (/help on Windows, --help on Unix) for - /// the available command line options. - /// - /// To use the sample configuration file (TimeServer.properties), - /// copy the file to the directory where the TimeServer executable - /// resides. If you start the debug version of the TimeServer - /// (TimeServerd[.exe]), you must also create a copy of the configuration - /// file named TimeServerd.properties. In the configuration file, you - /// can specify the port on which the server is listening (default - /// 9911) and the format of the date/time string sent back to the client. - /// - /// To test the TimeServer you can use any telnet client (telnet localhost 9911). -{ -public: - TimeServer(): _helpRequested(false) - { - } - - ~TimeServer() - { - } - -protected: - void initialize(Application& self) - { - loadConfiguration(); // load default configuration files, if present - ServerApplication::initialize(self); - } - - void uninitialize() - { - ServerApplication::uninitialize(); - } - - void defineOptions(OptionSet& options) - { - ServerApplication::defineOptions(options); - - options.addOption( - Option("help", "h", "display help information on command line arguments") - .required(false) - .repeatable(false)); - } - - void handleOption(const std::string& name, const std::string& value) - { - ServerApplication::handleOption(name, value); - - if (name == "help") - _helpRequested = true; - } - - void displayHelp() - { - HelpFormatter helpFormatter(options()); - helpFormatter.setCommand(commandName()); - helpFormatter.setUsage("OPTIONS"); - helpFormatter.setHeader("A server application that serves the current date and time."); - helpFormatter.format(std::cout); - } - - int main(const std::vector& args) - { - if (_helpRequested) - { - displayHelp(); - } - else - { - // get parameters from configuration file - unsigned short port = (unsigned short) config().getInt("TimeServer.port", 9911); - std::string format(config().getString("TimeServer.format", DateTimeFormat::ISO8601_FORMAT)); - - // set-up a server socket - ServerSocket svs(port); - // set-up a TCPServer instance - TCPServer srv(new TimeServerConnectionFactory(format), svs); - // start the TCPServer - srv.start(); - // wait for CTRL-C or kill - waitForTerminationRequest(); - // Stop the TCPServer - srv.stop(); - } - return Application::EXIT_OK; - } - -private: - bool _helpRequested; -}; - - -int main(int argc, char** argv) -{ - TimeServer app; - return app.run(argc, argv); -} +// +// TimeServer.cpp +// +// $Id: //poco/1.2/Net/samples/TimeServer/src/TimeServer.cpp#1 $ +// +// This sample demonstrates the TCPServer and ServerSocket classes. +// +// 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/TCPServerConnection.h" +#include "Poco/Net/TCPServerConnectionFactory.h" +#include "Poco/Net/TCPServerParams.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Timestamp.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/Exception.h" +#include "Poco/Util/ServerApplication.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/HelpFormatter.h" +#include + + +using Poco::Net::ServerSocket; +using Poco::Net::StreamSocket; +using Poco::Net::TCPServerConnection; +using Poco::Net::TCPServerConnectionFactory; +using Poco::Net::TCPServer; +using Poco::Timestamp; +using Poco::DateTimeFormatter; +using Poco::DateTimeFormat; +using Poco::Util::ServerApplication; +using Poco::Util::Application; +using Poco::Util::Option; +using Poco::Util::OptionSet; +using Poco::Util::HelpFormatter; + + +class TimeServerConnection: public TCPServerConnection + /// This class handles all client connections. + /// + /// A string with the current date and time is sent back to the client. +{ +public: + TimeServerConnection(const StreamSocket& s, const std::string& format): + TCPServerConnection(s), + _format(format) + { + } + + void run() + { + Application& app = Application::instance(); + app.logger().information("Request from " + this->socket().peerAddress().toString()); + try + { + Timestamp now; + std::string dt(DateTimeFormatter::format(now, _format)); + dt.append("\r\n"); + socket().sendBytes(dt.data(), (int) dt.length()); + } + catch (Poco::Exception& exc) + { + app.logger().log(exc); + } + } + +private: + std::string _format; +}; + + +class TimeServerConnectionFactory: public TCPServerConnectionFactory + /// A factory for TimeServerConnection. +{ +public: + TimeServerConnectionFactory(const std::string& format): + _format(format) + { + } + + TCPServerConnection* createConnection(const StreamSocket& socket) + { + return new TimeServerConnection(socket, _format); + } + +private: + std::string _format; +}; + + +class TimeServer: public Poco::Util::ServerApplication + /// The main application class. + /// + /// This class handles command-line arguments and + /// configuration files. + /// Start the TimeServer executable with the help + /// option (/help on Windows, --help on Unix) for + /// the available command line options. + /// + /// To use the sample configuration file (TimeServer.properties), + /// copy the file to the directory where the TimeServer executable + /// resides. If you start the debug version of the TimeServer + /// (TimeServerd[.exe]), you must also create a copy of the configuration + /// file named TimeServerd.properties. In the configuration file, you + /// can specify the port on which the server is listening (default + /// 9911) and the format of the date/time string sent back to the client. + /// + /// To test the TimeServer you can use any telnet client (telnet localhost 9911). +{ +public: + TimeServer(): _helpRequested(false) + { + } + + ~TimeServer() + { + } + +protected: + void initialize(Application& self) + { + loadConfiguration(); // load default configuration files, if present + ServerApplication::initialize(self); + } + + void uninitialize() + { + ServerApplication::uninitialize(); + } + + void defineOptions(OptionSet& options) + { + ServerApplication::defineOptions(options); + + options.addOption( + Option("help", "h", "display help information on command line arguments") + .required(false) + .repeatable(false)); + } + + void handleOption(const std::string& name, const std::string& value) + { + ServerApplication::handleOption(name, value); + + if (name == "help") + _helpRequested = true; + } + + void displayHelp() + { + HelpFormatter helpFormatter(options()); + helpFormatter.setCommand(commandName()); + helpFormatter.setUsage("OPTIONS"); + helpFormatter.setHeader("A server application that serves the current date and time."); + helpFormatter.format(std::cout); + } + + int main(const std::vector& args) + { + if (_helpRequested) + { + displayHelp(); + } + else + { + // get parameters from configuration file + unsigned short port = (unsigned short) config().getInt("TimeServer.port", 9911); + std::string format(config().getString("TimeServer.format", DateTimeFormat::ISO8601_FORMAT)); + + // set-up a server socket + ServerSocket svs(port); + // set-up a TCPServer instance + TCPServer srv(new TimeServerConnectionFactory(format), svs); + // start the TCPServer + srv.start(); + // wait for CTRL-C or kill + waitForTerminationRequest(); + // Stop the TCPServer + srv.stop(); + } + return Application::EXIT_OK; + } + +private: + bool _helpRequested; +}; + + +int main(int argc, char** argv) +{ + TimeServer app; + return app.run(argc, argv); +} diff --git a/Net/samples/dict/Makefile b/Net/samples/dict/Makefile index fc9fe3065..b3c216461 100644 --- a/Net/samples/dict/Makefile +++ b/Net/samples/dict/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/dict/Makefile#1 $ -# -# Makefile for Poco dict -# - -include $(POCO_BASE)/build/rules/global - -objects = dict - -target = dict -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/dict/Makefile#1 $ +# +# Makefile for Poco dict +# + +include $(POCO_BASE)/build/rules/global + +objects = dict + +target = dict +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/dict/dict.vmsbuild b/Net/samples/dict/dict.vmsbuild index d7295e256..f44c66cd6 100644 --- a/Net/samples/dict/dict.vmsbuild +++ b/Net/samples/dict/dict.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Net/samples/dict/dict.vmsbuild#1 $ -# -EXE=dict -dict - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Net/samples/dict/dict.vmsbuild#1 $ +# +EXE=dict +dict + diff --git a/Net/samples/dict/dict_vs71.vcproj b/Net/samples/dict/dict_vs71.vcproj index dc44827d1..3b6c7b362 100644 --- a/Net/samples/dict/dict_vs71.vcproj +++ b/Net/samples/dict/dict_vs71.vcproj @@ -1,145 +1,145 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/dict/dict_vs80.vcproj b/Net/samples/dict/dict_vs80.vcproj index 5d798fe1b..008d00607 100644 --- a/Net/samples/dict/dict_vs80.vcproj +++ b/Net/samples/dict/dict_vs80.vcproj @@ -1,209 +1,209 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/dict/src/dict.cpp b/Net/samples/dict/src/dict.cpp index 6cf795f00..a41d2e2a0 100644 --- a/Net/samples/dict/src/dict.cpp +++ b/Net/samples/dict/src/dict.cpp @@ -1,85 +1,85 @@ -// -// dict.cpp -// -// $Id: //poco/1.2/Net/samples/dict/src/dict.cpp#1 $ -// -// This sample demonstrates the StreamSocket and SocketStream classes. -// -// 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/SocketStream.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/StreamCopier.h" -#include "Poco/Path.h" -#include "Poco/Exception.h" -#include - - -using Poco::Net::StreamSocket; -using Poco::Net::SocketStream; -using Poco::Net::SocketAddress; -using Poco::StreamCopier; -using Poco::Path; -using Poco::Exception; - - -int main(int argc, char** argv) -{ - const std::string HOST("dict.org"); - const unsigned short PORT = 2628; - - if (argc != 2) - { - Path p(argv[0]); - std::cout << "usage: " << p.getBaseName() << " " << std::endl; - std::cout << " looks up in dict.org and prints the results" << std::endl; - return 1; - } - std::string term(argv[1]); - - try - { - SocketAddress sa(HOST, PORT); - StreamSocket sock(sa); - SocketStream str(sock); - - str << "DEFINE ! " << term << "\r\n" << std::flush; - str << "QUIT\r\n" << std::flush; - - sock.shutdownSend(); - StreamCopier::copyStream(str, std::cout); - } - catch (Exception& exc) - { - std::cerr << exc.displayText() << std::endl; - return 1; - } - - return 0; -} +// +// dict.cpp +// +// $Id: //poco/1.2/Net/samples/dict/src/dict.cpp#1 $ +// +// This sample demonstrates the StreamSocket and SocketStream classes. +// +// 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/SocketStream.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/StreamCopier.h" +#include "Poco/Path.h" +#include "Poco/Exception.h" +#include + + +using Poco::Net::StreamSocket; +using Poco::Net::SocketStream; +using Poco::Net::SocketAddress; +using Poco::StreamCopier; +using Poco::Path; +using Poco::Exception; + + +int main(int argc, char** argv) +{ + const std::string HOST("dict.org"); + const unsigned short PORT = 2628; + + if (argc != 2) + { + Path p(argv[0]); + std::cout << "usage: " << p.getBaseName() << " " << std::endl; + std::cout << " looks up in dict.org and prints the results" << std::endl; + return 1; + } + std::string term(argv[1]); + + try + { + SocketAddress sa(HOST, PORT); + StreamSocket sock(sa); + SocketStream str(sock); + + str << "DEFINE ! " << term << "\r\n" << std::flush; + str << "QUIT\r\n" << std::flush; + + sock.shutdownSend(); + StreamCopier::copyStream(str, std::cout); + } + catch (Exception& exc) + { + std::cerr << exc.displayText() << std::endl; + return 1; + } + + return 0; +} diff --git a/Net/samples/download/Makefile b/Net/samples/download/Makefile index 8a97b2483..57ed7df7c 100644 --- a/Net/samples/download/Makefile +++ b/Net/samples/download/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/Main/template/sample.make#4 $ -# -# Makefile for Poco download -# - -include $(POCO_BASE)/build/rules/global - -objects = download - -target = download -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/Main/template/sample.make#4 $ +# +# Makefile for Poco download +# + +include $(POCO_BASE)/build/rules/global + +objects = download + +target = download +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/download/download.vmsbuild b/Net/samples/download/download.vmsbuild index 7bfad4474..ff5dd0fcc 100644 --- a/Net/samples/download/download.vmsbuild +++ b/Net/samples/download/download.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/Main/template/sample.vmsbuild#3 $ -# -EXE=download -download - +# +# sample.vmsbuild +# +# $Id: //poco/Main/template/sample.vmsbuild#3 $ +# +EXE=download +download + diff --git a/Net/samples/download/download_vs71.vcproj b/Net/samples/download/download_vs71.vcproj index 0f341a4fa..2b4bee74f 100644 --- a/Net/samples/download/download_vs71.vcproj +++ b/Net/samples/download/download_vs71.vcproj @@ -1,145 +1,145 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/download/download_vs80.vcproj b/Net/samples/download/download_vs80.vcproj index 6cad3bc7f..154404eb4 100644 --- a/Net/samples/download/download_vs80.vcproj +++ b/Net/samples/download/download_vs80.vcproj @@ -1,210 +1,210 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/download/src/download.cpp b/Net/samples/download/src/download.cpp index 49a3a264c..b6f7425cc 100644 --- a/Net/samples/download/src/download.cpp +++ b/Net/samples/download/src/download.cpp @@ -1,82 +1,82 @@ -// -// download.cpp -// -// $Id: //poco/1.2/Net/samples/download/src/download.cpp#1 $ -// -// This sample demonstrates the URIStreamOpener 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. -// - - -#include "Poco/URIStreamOpener.h" -#include "Poco/StreamCopier.h" -#include "Poco/Path.h" -#include "Poco/URI.h" -#include "Poco/Exception.h" -#include "Poco/Net/HTTPStreamFactory.h" -#include "Poco/Net/FTPStreamFactory.h" -#include -#include - - -using Poco::URIStreamOpener; -using Poco::StreamCopier; -using Poco::Path; -using Poco::URI; -using Poco::Exception; -using Poco::Net::HTTPStreamFactory; -using Poco::Net::FTPStreamFactory; - - -int main(int argc, char** argv) -{ - HTTPStreamFactory::registerFactory(); - FTPStreamFactory::registerFactory(); - - if (argc != 2) - { - Path p(argv[0]); - std::cerr << "usage: " << p.getBaseName() << " " << std::endl; - std::cerr << " Download to standard output." << std::endl; - std::cerr << " Works with http, ftp and file URIs." << std::endl; - return 1; - } - - try - { - URI uri(argv[1]); - std::auto_ptr pStr(URIStreamOpener::defaultOpener().open(uri)); - StreamCopier::copyStream(*pStr.get(), std::cout); - } - catch (Exception& exc) - { - std::cerr << exc.displayText() << std::endl; - return 1; - } - - return 0; -} +// +// download.cpp +// +// $Id: //poco/1.2/Net/samples/download/src/download.cpp#1 $ +// +// This sample demonstrates the URIStreamOpener 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. +// + + +#include "Poco/URIStreamOpener.h" +#include "Poco/StreamCopier.h" +#include "Poco/Path.h" +#include "Poco/URI.h" +#include "Poco/Exception.h" +#include "Poco/Net/HTTPStreamFactory.h" +#include "Poco/Net/FTPStreamFactory.h" +#include +#include + + +using Poco::URIStreamOpener; +using Poco::StreamCopier; +using Poco::Path; +using Poco::URI; +using Poco::Exception; +using Poco::Net::HTTPStreamFactory; +using Poco::Net::FTPStreamFactory; + + +int main(int argc, char** argv) +{ + HTTPStreamFactory::registerFactory(); + FTPStreamFactory::registerFactory(); + + if (argc != 2) + { + Path p(argv[0]); + std::cerr << "usage: " << p.getBaseName() << " " << std::endl; + std::cerr << " Download to standard output." << std::endl; + std::cerr << " Works with http, ftp and file URIs." << std::endl; + return 1; + } + + try + { + URI uri(argv[1]); + std::auto_ptr pStr(URIStreamOpener::defaultOpener().open(uri)); + StreamCopier::copyStream(*pStr.get(), std::cout); + } + catch (Exception& exc) + { + std::cerr << exc.displayText() << std::endl; + return 1; + } + + return 0; +} diff --git a/Net/samples/httpget/Makefile b/Net/samples/httpget/Makefile index 54071172e..e29ce5afd 100644 --- a/Net/samples/httpget/Makefile +++ b/Net/samples/httpget/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/samples/httpget/Makefile#1 $ -# -# Makefile for Poco httpget -# - -include $(POCO_BASE)/build/rules/global - -objects = httpget - -target = httpget -target_version = 1 -target_libs = PocoUtil PocoNet PocoXML PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/samples/httpget/Makefile#1 $ +# +# Makefile for Poco httpget +# + +include $(POCO_BASE)/build/rules/global + +objects = httpget + +target = httpget +target_version = 1 +target_libs = PocoUtil PocoNet PocoXML PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/samples/httpget/httpget.vmsbuild b/Net/samples/httpget/httpget.vmsbuild index 9cb331c2c..6c33a6c2b 100644 --- a/Net/samples/httpget/httpget.vmsbuild +++ b/Net/samples/httpget/httpget.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Net/samples/httpget/httpget.vmsbuild#1 $ -# -EXE=httpget -httpget - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Net/samples/httpget/httpget.vmsbuild#1 $ +# +EXE=httpget +httpget + diff --git a/Net/samples/httpget/httpget_vs71.vcproj b/Net/samples/httpget/httpget_vs71.vcproj index 45ff4f6cf..a3d39b6a9 100644 --- a/Net/samples/httpget/httpget_vs71.vcproj +++ b/Net/samples/httpget/httpget_vs71.vcproj @@ -1,145 +1,145 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/httpget/httpget_vs80.vcproj b/Net/samples/httpget/httpget_vs80.vcproj index 89123fcc5..1233b8327 100644 --- a/Net/samples/httpget/httpget_vs80.vcproj +++ b/Net/samples/httpget/httpget_vs80.vcproj @@ -1,209 +1,209 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/samples/httpget/src/httpget.cpp b/Net/samples/httpget/src/httpget.cpp index 719dbdb51..e8aace927 100644 --- a/Net/samples/httpget/src/httpget.cpp +++ b/Net/samples/httpget/src/httpget.cpp @@ -1,85 +1,85 @@ -// -// httpget.cpp -// -// $Id: //poco/1.2/Net/samples/httpget/src/httpget.cpp#1 $ -// -// This sample demonstrates the HTTPClientSession 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. -// - - -#include "Poco/Net/HTTPClientSession.h" -#include "Poco/Net/HTTPRequest.h" -#include "Poco/Net/HTTPResponse.h" -#include "Poco/StreamCopier.h" -#include "Poco/Path.h" -#include "Poco/URI.h" -#include "Poco/Exception.h" -#include - - -using Poco::Net::HTTPClientSession; -using Poco::Net::HTTPRequest; -using Poco::Net::HTTPResponse; -using Poco::Net::HTTPMessage; -using Poco::StreamCopier; -using Poco::Path; -using Poco::URI; -using Poco::Exception; - - -int main(int argc, char** argv) -{ - if (argc != 2) - { - Path p(argv[0]); - std::cout << "usage: " << p.getBaseName() << " " << std::endl; - std::cout << " fetches the resource identified by and print it to the standard output" << std::endl; - return 1; - } - - try - { - URI uri(argv[1]); - std::string path(uri.getPathAndQuery()); - if (path.empty()) path = "/"; - - HTTPClientSession session(uri.getHost(), uri.getPort()); - HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1); - session.sendRequest(req); - HTTPResponse res; - std::istream& rs = session.receiveResponse(res); - std::cout << res.getStatus() << " " << res.getReason() << std::endl; - StreamCopier::copyStream(rs, std::cout); - } - catch (Exception& exc) - { - std::cerr << exc.displayText() << std::endl; - return 1; - } - return 0; -} +// +// httpget.cpp +// +// $Id: //poco/1.2/Net/samples/httpget/src/httpget.cpp#1 $ +// +// This sample demonstrates the HTTPClientSession 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. +// + + +#include "Poco/Net/HTTPClientSession.h" +#include "Poco/Net/HTTPRequest.h" +#include "Poco/Net/HTTPResponse.h" +#include "Poco/StreamCopier.h" +#include "Poco/Path.h" +#include "Poco/URI.h" +#include "Poco/Exception.h" +#include + + +using Poco::Net::HTTPClientSession; +using Poco::Net::HTTPRequest; +using Poco::Net::HTTPResponse; +using Poco::Net::HTTPMessage; +using Poco::StreamCopier; +using Poco::Path; +using Poco::URI; +using Poco::Exception; + + +int main(int argc, char** argv) +{ + if (argc != 2) + { + Path p(argv[0]); + std::cout << "usage: " << p.getBaseName() << " " << std::endl; + std::cout << " fetches the resource identified by and print it to the standard output" << std::endl; + return 1; + } + + try + { + URI uri(argv[1]); + std::string path(uri.getPathAndQuery()); + if (path.empty()) path = "/"; + + HTTPClientSession session(uri.getHost(), uri.getPort()); + HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1); + session.sendRequest(req); + HTTPResponse res; + std::istream& rs = session.receiveResponse(res); + std::cout << res.getStatus() << " " << res.getReason() << std::endl; + StreamCopier::copyStream(rs, std::cout); + } + catch (Exception& exc) + { + std::cerr << exc.displayText() << std::endl; + return 1; + } + return 0; +} diff --git a/Net/samples/samples_vs71.sln b/Net/samples/samples_vs71.sln index 4788cfbed..642a87dbb 100644 --- a/Net/samples/samples_vs71.sln +++ b/Net/samples/samples_vs71.sln @@ -1,93 +1,93 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeServer", "TimeServer\TimeServer_vs71.vcproj", "{1DDAE25B-2263-45B2-8931-C36AD28A0362}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPTimeServer", "HTTPTimeServer\HTTPTimeServer_vs71.vcproj", "{7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dict", "dict\dict_vs71.vcproj", "{D1CACC03-A306-4ACA-82D3-005542CB119B}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "httpget", "httpget\httpget_vs71.vcproj", "{F232C4F0-4D36-454A-816F-C171E47AF61D}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "download", "download\download_vs71.vcproj", "{22F6B2E6-A532-4156-A49A-835A21BFF3F6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "EchoServer", "EchoServer\EchoServer_vs71.vcproj", "{7339ED24-9950-4B74-8519-E8DC66C0524E}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Mail", "Mail\Mail_vs71.vcproj", "{1B776CF5-3889-48D1-A58B-694D06FBD632}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPLoadTest", "HTTPLoadTest\HTTPLoadTest_vs71.vcproj", "{455C9515-4914-49B6-93FB-C37242A6C21C}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ping", "Ping\Ping_vs71.vcproj", "{73408DCF-2E65-47AF-BF38-7466DAB8D5CB}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPFormServer", "HTTPFormServer\HTTPFormServer_vs71.vcproj", "{45A054E6-44EC-4943-809A-BA8B2A25DA21}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - debug_shared = debug_shared - release_shared = release_shared - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {1DDAE25B-2263-45B2-8931-C36AD28A0362}.debug_shared.ActiveCfg = debug_shared|Win32 - {1DDAE25B-2263-45B2-8931-C36AD28A0362}.debug_shared.Build.0 = debug_shared|Win32 - {1DDAE25B-2263-45B2-8931-C36AD28A0362}.release_shared.ActiveCfg = release_shared|Win32 - {1DDAE25B-2263-45B2-8931-C36AD28A0362}.release_shared.Build.0 = release_shared|Win32 - {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.debug_shared.ActiveCfg = debug_shared|Win32 - {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.debug_shared.Build.0 = debug_shared|Win32 - {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.release_shared.ActiveCfg = release_shared|Win32 - {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.release_shared.Build.0 = release_shared|Win32 - {D1CACC03-A306-4ACA-82D3-005542CB119B}.debug_shared.ActiveCfg = debug_shared|Win32 - {D1CACC03-A306-4ACA-82D3-005542CB119B}.debug_shared.Build.0 = debug_shared|Win32 - {D1CACC03-A306-4ACA-82D3-005542CB119B}.release_shared.ActiveCfg = release_shared|Win32 - {D1CACC03-A306-4ACA-82D3-005542CB119B}.release_shared.Build.0 = release_shared|Win32 - {F232C4F0-4D36-454A-816F-C171E47AF61D}.debug_shared.ActiveCfg = debug_shared|Win32 - {F232C4F0-4D36-454A-816F-C171E47AF61D}.debug_shared.Build.0 = debug_shared|Win32 - {F232C4F0-4D36-454A-816F-C171E47AF61D}.release_shared.ActiveCfg = release_shared|Win32 - {F232C4F0-4D36-454A-816F-C171E47AF61D}.release_shared.Build.0 = release_shared|Win32 - {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.debug_shared.ActiveCfg = debug_shared|Win32 - {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.debug_shared.Build.0 = debug_shared|Win32 - {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.release_shared.ActiveCfg = release_shared|Win32 - {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.release_shared.Build.0 = release_shared|Win32 - {7339ED24-9950-4B74-8519-E8DC66C0524E}.debug_shared.ActiveCfg = debug_shared|Win32 - {7339ED24-9950-4B74-8519-E8DC66C0524E}.debug_shared.Build.0 = debug_shared|Win32 - {7339ED24-9950-4B74-8519-E8DC66C0524E}.release_shared.ActiveCfg = release_shared|Win32 - {7339ED24-9950-4B74-8519-E8DC66C0524E}.release_shared.Build.0 = release_shared|Win32 - {1B776CF5-3889-48D1-A58B-694D06FBD632}.debug_shared.ActiveCfg = debug_shared|Win32 - {1B776CF5-3889-48D1-A58B-694D06FBD632}.debug_shared.Build.0 = debug_shared|Win32 - {1B776CF5-3889-48D1-A58B-694D06FBD632}.release_shared.ActiveCfg = release_shared|Win32 - {1B776CF5-3889-48D1-A58B-694D06FBD632}.release_shared.Build.0 = release_shared|Win32 - {455C9515-4914-49B6-93FB-C37242A6C21C}.debug_shared.ActiveCfg = debug_shared|Win32 - {455C9515-4914-49B6-93FB-C37242A6C21C}.debug_shared.Build.0 = debug_shared|Win32 - {455C9515-4914-49B6-93FB-C37242A6C21C}.release_shared.ActiveCfg = release_shared|Win32 - {455C9515-4914-49B6-93FB-C37242A6C21C}.release_shared.Build.0 = release_shared|Win32 - {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.debug_shared.ActiveCfg = debug_shared|Win32 - {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.debug_shared.Build.0 = debug_shared|Win32 - {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.release_shared.ActiveCfg = release_shared|Win32 - {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.release_shared.Build.0 = release_shared|Win32 - {45A054E6-44EC-4943-809A-BA8B2A25DA21}.debug_shared.ActiveCfg = debug_shared|Win32 - {45A054E6-44EC-4943-809A-BA8B2A25DA21}.debug_shared.Build.0 = debug_shared|Win32 - {45A054E6-44EC-4943-809A-BA8B2A25DA21}.release_shared.ActiveCfg = release_shared|Win32 - {45A054E6-44EC-4943-809A-BA8B2A25DA21}.release_shared.Build.0 = release_shared|Win32 - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 8.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeServer", "TimeServer\TimeServer_vs71.vcproj", "{1DDAE25B-2263-45B2-8931-C36AD28A0362}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPTimeServer", "HTTPTimeServer\HTTPTimeServer_vs71.vcproj", "{7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dict", "dict\dict_vs71.vcproj", "{D1CACC03-A306-4ACA-82D3-005542CB119B}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "httpget", "httpget\httpget_vs71.vcproj", "{F232C4F0-4D36-454A-816F-C171E47AF61D}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "download", "download\download_vs71.vcproj", "{22F6B2E6-A532-4156-A49A-835A21BFF3F6}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "EchoServer", "EchoServer\EchoServer_vs71.vcproj", "{7339ED24-9950-4B74-8519-E8DC66C0524E}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Mail", "Mail\Mail_vs71.vcproj", "{1B776CF5-3889-48D1-A58B-694D06FBD632}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPLoadTest", "HTTPLoadTest\HTTPLoadTest_vs71.vcproj", "{455C9515-4914-49B6-93FB-C37242A6C21C}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ping", "Ping\Ping_vs71.vcproj", "{73408DCF-2E65-47AF-BF38-7466DAB8D5CB}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPFormServer", "HTTPFormServer\HTTPFormServer_vs71.vcproj", "{45A054E6-44EC-4943-809A-BA8B2A25DA21}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + debug_shared = debug_shared + release_shared = release_shared + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {1DDAE25B-2263-45B2-8931-C36AD28A0362}.debug_shared.ActiveCfg = debug_shared|Win32 + {1DDAE25B-2263-45B2-8931-C36AD28A0362}.debug_shared.Build.0 = debug_shared|Win32 + {1DDAE25B-2263-45B2-8931-C36AD28A0362}.release_shared.ActiveCfg = release_shared|Win32 + {1DDAE25B-2263-45B2-8931-C36AD28A0362}.release_shared.Build.0 = release_shared|Win32 + {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.debug_shared.ActiveCfg = debug_shared|Win32 + {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.debug_shared.Build.0 = debug_shared|Win32 + {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.release_shared.ActiveCfg = release_shared|Win32 + {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.release_shared.Build.0 = release_shared|Win32 + {D1CACC03-A306-4ACA-82D3-005542CB119B}.debug_shared.ActiveCfg = debug_shared|Win32 + {D1CACC03-A306-4ACA-82D3-005542CB119B}.debug_shared.Build.0 = debug_shared|Win32 + {D1CACC03-A306-4ACA-82D3-005542CB119B}.release_shared.ActiveCfg = release_shared|Win32 + {D1CACC03-A306-4ACA-82D3-005542CB119B}.release_shared.Build.0 = release_shared|Win32 + {F232C4F0-4D36-454A-816F-C171E47AF61D}.debug_shared.ActiveCfg = debug_shared|Win32 + {F232C4F0-4D36-454A-816F-C171E47AF61D}.debug_shared.Build.0 = debug_shared|Win32 + {F232C4F0-4D36-454A-816F-C171E47AF61D}.release_shared.ActiveCfg = release_shared|Win32 + {F232C4F0-4D36-454A-816F-C171E47AF61D}.release_shared.Build.0 = release_shared|Win32 + {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.debug_shared.ActiveCfg = debug_shared|Win32 + {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.debug_shared.Build.0 = debug_shared|Win32 + {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.release_shared.ActiveCfg = release_shared|Win32 + {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.release_shared.Build.0 = release_shared|Win32 + {7339ED24-9950-4B74-8519-E8DC66C0524E}.debug_shared.ActiveCfg = debug_shared|Win32 + {7339ED24-9950-4B74-8519-E8DC66C0524E}.debug_shared.Build.0 = debug_shared|Win32 + {7339ED24-9950-4B74-8519-E8DC66C0524E}.release_shared.ActiveCfg = release_shared|Win32 + {7339ED24-9950-4B74-8519-E8DC66C0524E}.release_shared.Build.0 = release_shared|Win32 + {1B776CF5-3889-48D1-A58B-694D06FBD632}.debug_shared.ActiveCfg = debug_shared|Win32 + {1B776CF5-3889-48D1-A58B-694D06FBD632}.debug_shared.Build.0 = debug_shared|Win32 + {1B776CF5-3889-48D1-A58B-694D06FBD632}.release_shared.ActiveCfg = release_shared|Win32 + {1B776CF5-3889-48D1-A58B-694D06FBD632}.release_shared.Build.0 = release_shared|Win32 + {455C9515-4914-49B6-93FB-C37242A6C21C}.debug_shared.ActiveCfg = debug_shared|Win32 + {455C9515-4914-49B6-93FB-C37242A6C21C}.debug_shared.Build.0 = debug_shared|Win32 + {455C9515-4914-49B6-93FB-C37242A6C21C}.release_shared.ActiveCfg = release_shared|Win32 + {455C9515-4914-49B6-93FB-C37242A6C21C}.release_shared.Build.0 = release_shared|Win32 + {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.debug_shared.ActiveCfg = debug_shared|Win32 + {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.debug_shared.Build.0 = debug_shared|Win32 + {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.release_shared.ActiveCfg = release_shared|Win32 + {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.release_shared.Build.0 = release_shared|Win32 + {45A054E6-44EC-4943-809A-BA8B2A25DA21}.debug_shared.ActiveCfg = debug_shared|Win32 + {45A054E6-44EC-4943-809A-BA8B2A25DA21}.debug_shared.Build.0 = debug_shared|Win32 + {45A054E6-44EC-4943-809A-BA8B2A25DA21}.release_shared.ActiveCfg = release_shared|Win32 + {45A054E6-44EC-4943-809A-BA8B2A25DA21}.release_shared.Build.0 = release_shared|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/Net/samples/samples_vs80.sln b/Net/samples/samples_vs80.sln index df394b362..83290618c 100644 --- a/Net/samples/samples_vs80.sln +++ b/Net/samples/samples_vs80.sln @@ -1,73 +1,73 @@ -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeServer", "TimeServer\TimeServer_vs80.vcproj", "{1DDAE25B-2263-45B2-8931-C36AD28A0362}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPTimeServer", "HTTPTimeServer\HTTPTimeServer_vs80.vcproj", "{7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dict", "dict\dict_vs80.vcproj", "{D1CACC03-A306-4ACA-82D3-005542CB119B}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "httpget", "httpget\httpget_vs80.vcproj", "{F232C4F0-4D36-454A-816F-C171E47AF61D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "download", "download\download_vs80.vcproj", "{22F6B2E6-A532-4156-A49A-835A21BFF3F6}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "EchoServer", "EchoServer\EchoServer_vs80.vcproj", "{7339ED24-9950-4B74-8519-E8DC66C0524E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Mail", "Mail\Mail_vs80.vcproj", "{D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPLoadTest", "HTTPLoadTest\HTTPLoadTest_vs80.vcproj", "{DC23240B-5266-4486-A141-B8D6F25F7676}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ping", "Ping\Ping_vs80.vcproj", "{73408DCF-2E65-47AF-BF38-7466DAB8D5CB}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPFormServer", "HTTPFormServer\HTTPFormServer_vs80.vcproj", "{5363487F-1F23-4F9E-B6A7-5471B0F2373F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - debug_shared|Win32 = debug_shared|Win32 - release_shared|Win32 = release_shared|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {1DDAE25B-2263-45B2-8931-C36AD28A0362}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {1DDAE25B-2263-45B2-8931-C36AD28A0362}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {1DDAE25B-2263-45B2-8931-C36AD28A0362}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {1DDAE25B-2263-45B2-8931-C36AD28A0362}.release_shared|Win32.Build.0 = release_shared|Win32 - {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.release_shared|Win32.Build.0 = release_shared|Win32 - {D1CACC03-A306-4ACA-82D3-005542CB119B}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {D1CACC03-A306-4ACA-82D3-005542CB119B}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {D1CACC03-A306-4ACA-82D3-005542CB119B}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {D1CACC03-A306-4ACA-82D3-005542CB119B}.release_shared|Win32.Build.0 = release_shared|Win32 - {F232C4F0-4D36-454A-816F-C171E47AF61D}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {F232C4F0-4D36-454A-816F-C171E47AF61D}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {F232C4F0-4D36-454A-816F-C171E47AF61D}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {F232C4F0-4D36-454A-816F-C171E47AF61D}.release_shared|Win32.Build.0 = release_shared|Win32 - {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.release_shared|Win32.Build.0 = release_shared|Win32 - {7339ED24-9950-4B74-8519-E8DC66C0524E}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {7339ED24-9950-4B74-8519-E8DC66C0524E}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {7339ED24-9950-4B74-8519-E8DC66C0524E}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {7339ED24-9950-4B74-8519-E8DC66C0524E}.release_shared|Win32.Build.0 = release_shared|Win32 - {D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}.release_shared|Win32.Build.0 = release_shared|Win32 - {DC23240B-5266-4486-A141-B8D6F25F7676}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {DC23240B-5266-4486-A141-B8D6F25F7676}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {DC23240B-5266-4486-A141-B8D6F25F7676}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {DC23240B-5266-4486-A141-B8D6F25F7676}.release_shared|Win32.Build.0 = release_shared|Win32 - {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.release_shared|Win32.Build.0 = release_shared|Win32 - {5363487F-1F23-4F9E-B6A7-5471B0F2373F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {5363487F-1F23-4F9E-B6A7-5471B0F2373F}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {5363487F-1F23-4F9E-B6A7-5471B0F2373F}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {5363487F-1F23-4F9E-B6A7-5471B0F2373F}.release_shared|Win32.Build.0 = release_shared|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeServer", "TimeServer\TimeServer_vs80.vcproj", "{1DDAE25B-2263-45B2-8931-C36AD28A0362}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPTimeServer", "HTTPTimeServer\HTTPTimeServer_vs80.vcproj", "{7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dict", "dict\dict_vs80.vcproj", "{D1CACC03-A306-4ACA-82D3-005542CB119B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "httpget", "httpget\httpget_vs80.vcproj", "{F232C4F0-4D36-454A-816F-C171E47AF61D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "download", "download\download_vs80.vcproj", "{22F6B2E6-A532-4156-A49A-835A21BFF3F6}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "EchoServer", "EchoServer\EchoServer_vs80.vcproj", "{7339ED24-9950-4B74-8519-E8DC66C0524E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Mail", "Mail\Mail_vs80.vcproj", "{D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPLoadTest", "HTTPLoadTest\HTTPLoadTest_vs80.vcproj", "{DC23240B-5266-4486-A141-B8D6F25F7676}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ping", "Ping\Ping_vs80.vcproj", "{73408DCF-2E65-47AF-BF38-7466DAB8D5CB}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HTTPFormServer", "HTTPFormServer\HTTPFormServer_vs80.vcproj", "{5363487F-1F23-4F9E-B6A7-5471B0F2373F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + debug_shared|Win32 = debug_shared|Win32 + release_shared|Win32 = release_shared|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1DDAE25B-2263-45B2-8931-C36AD28A0362}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {1DDAE25B-2263-45B2-8931-C36AD28A0362}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {1DDAE25B-2263-45B2-8931-C36AD28A0362}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {1DDAE25B-2263-45B2-8931-C36AD28A0362}.release_shared|Win32.Build.0 = release_shared|Win32 + {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {7C4285ED-F0BC-4CBA-B1F0-61FCB7FA26C4}.release_shared|Win32.Build.0 = release_shared|Win32 + {D1CACC03-A306-4ACA-82D3-005542CB119B}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {D1CACC03-A306-4ACA-82D3-005542CB119B}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {D1CACC03-A306-4ACA-82D3-005542CB119B}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {D1CACC03-A306-4ACA-82D3-005542CB119B}.release_shared|Win32.Build.0 = release_shared|Win32 + {F232C4F0-4D36-454A-816F-C171E47AF61D}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {F232C4F0-4D36-454A-816F-C171E47AF61D}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {F232C4F0-4D36-454A-816F-C171E47AF61D}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {F232C4F0-4D36-454A-816F-C171E47AF61D}.release_shared|Win32.Build.0 = release_shared|Win32 + {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {22F6B2E6-A532-4156-A49A-835A21BFF3F6}.release_shared|Win32.Build.0 = release_shared|Win32 + {7339ED24-9950-4B74-8519-E8DC66C0524E}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {7339ED24-9950-4B74-8519-E8DC66C0524E}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {7339ED24-9950-4B74-8519-E8DC66C0524E}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {7339ED24-9950-4B74-8519-E8DC66C0524E}.release_shared|Win32.Build.0 = release_shared|Win32 + {D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {D6C4B3D4-2026-4A33-B4DA-ABE8FF2EE0B8}.release_shared|Win32.Build.0 = release_shared|Win32 + {DC23240B-5266-4486-A141-B8D6F25F7676}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {DC23240B-5266-4486-A141-B8D6F25F7676}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {DC23240B-5266-4486-A141-B8D6F25F7676}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {DC23240B-5266-4486-A141-B8D6F25F7676}.release_shared|Win32.Build.0 = release_shared|Win32 + {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {73408DCF-2E65-47AF-BF38-7466DAB8D5CB}.release_shared|Win32.Build.0 = release_shared|Win32 + {5363487F-1F23-4F9E-B6A7-5471B0F2373F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {5363487F-1F23-4F9E-B6A7-5471B0F2373F}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {5363487F-1F23-4F9E-B6A7-5471B0F2373F}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {5363487F-1F23-4F9E-B6A7-5471B0F2373F}.release_shared|Win32.Build.0 = release_shared|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Net/src/DNS.cpp b/Net/src/DNS.cpp index f550d45af..900680ffe 100644 --- a/Net/src/DNS.cpp +++ b/Net/src/DNS.cpp @@ -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 res = _cache.insert(std::pair(hostname, HostEntry(pAI))); - freeaddrinfo(pAI); - return res.first->second; - } -#else - struct hostent* he = gethostbyname(hostname.c_str()); - if (he) - { - std::pair res = _cache.insert(std::pair(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 res = _cache.insert(std::pair(std::string(fqname), HostEntry(pAI))); - freeaddrinfo(pAI); - return res.first->second; - } - } - } -#else - struct hostent* he = gethostbyaddr(reinterpret_cast(address.addr()), address.length(), address.af()); - if (he) - { - std::pair res = _cache.insert(std::pair(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 res = _cache.insert(std::pair(hostname, HostEntry(pAI))); + freeaddrinfo(pAI); + return res.first->second; + } +#else + struct hostent* he = gethostbyname(hostname.c_str()); + if (he) + { + std::pair res = _cache.insert(std::pair(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 res = _cache.insert(std::pair(std::string(fqname), HostEntry(pAI))); + freeaddrinfo(pAI); + return res.first->second; + } + } + } +#else + struct hostent* he = gethostbyaddr(reinterpret_cast(address.addr()), address.length(), address.af()); + if (he) + { + std::pair res = _cache.insert(std::pair(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 diff --git a/Net/src/DatagramSocket.cpp b/Net/src/DatagramSocket.cpp index 0566ebc73..e4f277631 100644 --- a/Net/src/DatagramSocket.cpp +++ b/Net/src/DatagramSocket.cpp @@ -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(impl())) - throw InvalidArgumentException("Cannot assign incompatible socket"); -} - - -DatagramSocket::DatagramSocket(SocketImpl* pImpl): Socket(pImpl) -{ - if (!dynamic_cast(impl())) - throw InvalidArgumentException("Cannot assign incompatible socket"); -} - - -DatagramSocket::~DatagramSocket() -{ -} - - -DatagramSocket& DatagramSocket::operator = (const Socket& socket) -{ - if (dynamic_cast(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(impl())) + throw InvalidArgumentException("Cannot assign incompatible socket"); +} + + +DatagramSocket::DatagramSocket(SocketImpl* pImpl): Socket(pImpl) +{ + if (!dynamic_cast(impl())) + throw InvalidArgumentException("Cannot assign incompatible socket"); +} + + +DatagramSocket::~DatagramSocket() +{ +} + + +DatagramSocket& DatagramSocket::operator = (const Socket& socket) +{ + if (dynamic_cast(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 diff --git a/Net/src/DatagramSocketImpl.cpp b/Net/src/DatagramSocketImpl.cpp index 52f8ecc2b..a78e34b7a 100644 --- a/Net/src/DatagramSocketImpl.cpp +++ b/Net/src/DatagramSocketImpl.cpp @@ -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 diff --git a/Net/src/DialogSocket.cpp b/Net/src/DialogSocket.cpp index 35e726350..24544a847 100644 --- a/Net/src/DialogSocket.cpp +++ b/Net/src/DialogSocket.cpp @@ -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 -#include - - -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 +#include + + +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 diff --git a/Net/src/FTPClientSession.cpp b/Net/src/FTPClientSession.cpp index 932643088..86c35d515 100644 --- a/Net/src/FTPClientSession.cpp +++ b/Net/src/FTPClientSession.cpp @@ -1,508 +1,508 @@ -// -// FTPClientSession.cpp -// -// $Id: //poco/1.2/Net/src/FTPClientSession.cpp#1 $ -// -// Library: Net -// Package: FTP -// Module: FTPClientSession -// -// 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/FTPClientSession.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/SocketStream.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Net/NetException.h" -#include "Poco/NumberFormatter.h" -#include - - -using Poco::NumberFormatter; - - -namespace Poco { -namespace Net { - - -FTPClientSession::FTPClientSession(const StreamSocket& socket): - _controlSocket(socket), - _pDataStream(0), - _passiveMode(true), - _fileType(TYPE_BINARY), - _supports1738(true), - _isOpen(true), - _timeout(DEFAULT_TIMEOUT) -{ - _controlSocket.setReceiveTimeout(_timeout); -} - - -FTPClientSession::FTPClientSession(const std::string& host, Poco::UInt16 port): - _controlSocket(SocketAddress(host, port)), - _pDataStream(0), - _passiveMode(true), - _fileType(TYPE_BINARY), - _supports1738(true), - _isOpen(true), - _timeout(DEFAULT_TIMEOUT) -{ - _controlSocket.setReceiveTimeout(_timeout); -} - - -FTPClientSession::~FTPClientSession() -{ - try - { - close(); - } - catch (...) - { - } -} - - -void FTPClientSession::setTimeout(const Poco::Timespan& timeout) -{ - _timeout = timeout; - _controlSocket.setReceiveTimeout(timeout); -} - - -Poco::Timespan FTPClientSession::getTimeout() const -{ - return _timeout; -} - - -void FTPClientSession::setPassive(bool flag) -{ - _passiveMode = flag; -} - - -bool FTPClientSession::getPassive() const -{ - return _passiveMode; -} - - -void FTPClientSession::login(const std::string& username, const std::string& password) -{ - std::string response; - int status = _controlSocket.receiveStatusMessage(response); - if (!isPositiveCompletion(status)) throw FTPException("Cannot login to server", response); - status = sendCommand("USER", username, response); - if (isPositiveIntermediate(status)) - status = sendCommand("PASS", password, response); - if (!isPositiveCompletion(status)) throw FTPException("Login denied", response); - setFileType(_fileType); -} - - -void FTPClientSession::close() -{ - if (_isOpen) - { - try - { - endTransfer(); - } - catch (...) - { - } - std::string response; - sendCommand("QUIT", response); - _controlSocket.close(); - _isOpen = false; - } -} - - -void FTPClientSession::setFileType(FTPClientSession::FileType type) -{ - std::string response; - int status = sendCommand("TYPE", (type == TYPE_TEXT ? "A" : "I"), response); - if (!isPositiveCompletion(status)) throw FTPException("Cannot set file type", response); - _fileType = type; -} - - -FTPClientSession::FileType FTPClientSession::getFileType() const -{ - return _fileType; -} - - -std::string FTPClientSession::systemType() -{ - std::string response; - int status = sendCommand("SYST", response); - if (isPositiveCompletion(status)) - return response.substr(4); - else - throw FTPException("Cannot get remote system type", response); -} - - -void FTPClientSession::setWorkingDirectory(const std::string& path) -{ - std::string response; - int status = sendCommand("CWD", path, response); - if (!isPositiveCompletion(status)) throw FTPException("Cannot change directory", response); -} - - -std::string FTPClientSession::getWorkingDirectory() -{ - std::string response; - int status = sendCommand("PWD", response); - if (isPositiveCompletion(status)) - return extractPath(response); - else - throw FTPException("Cannot get current working directory", response); -} - - -void FTPClientSession::cdup() -{ - std::string response; - int status = sendCommand("CDUP", response); - if (!isPositiveCompletion(status)) throw FTPException("Cannot change directory", response); -} - - -void FTPClientSession::rename(const std::string& oldName, const std::string& newName) -{ - std::string response; - int status = sendCommand("RNFR", oldName, response); - if (!isPositiveIntermediate(status)) throw FTPException(std::string("Cannot rename ") + oldName, response); - status = sendCommand("RNTO", newName, response); - if (!isPositiveCompletion(status)) throw FTPException(std::string("Cannot rename to ") + newName, response); -} - - -void FTPClientSession::remove(const std::string& path) -{ - std::string response; - int status = sendCommand("DELE", path, response); - if (!isPositiveCompletion(status)) throw FTPException(std::string("Cannot remove " + path), response); -} - - -void FTPClientSession::createDirectory(const std::string& path) -{ - std::string response; - int status = sendCommand("MKD", path, response); - if (!isPositiveCompletion(status)) throw FTPException(std::string("Cannot create directory ") + path, response); -} - - -void FTPClientSession::removeDirectory(const std::string& path) -{ - std::string response; - int status = sendCommand("RMD", path, response); - if (!isPositiveCompletion(status)) throw FTPException(std::string("Cannot remove directory ") + path, response); -} - - -std::istream& FTPClientSession::beginDownload(const std::string& path) -{ - delete _pDataStream; - _pDataStream = 0; - _pDataStream = new SocketStream(establishDataConnection("RETR", path)); - return *_pDataStream; -} - - -void FTPClientSession::endDownload() -{ - endTransfer(); -} - - -std::ostream& FTPClientSession::beginUpload(const std::string& path) -{ - delete _pDataStream; - _pDataStream = 0; - _pDataStream = new SocketStream(establishDataConnection("STOR", path)); - return *_pDataStream; -} - - -void FTPClientSession::endUpload() -{ - endTransfer(); -} - - -std::istream& FTPClientSession::beginList(const std::string& path, bool extended) -{ - delete _pDataStream; - _pDataStream = 0; - _pDataStream = new SocketStream(establishDataConnection(extended ? "LIST" : "NLST", path)); - return *_pDataStream; -} - - -void FTPClientSession::endList() -{ - endTransfer(); -} - - -void FTPClientSession::abort() -{ - _controlSocket.sendByte(DialogSocket::TELNET_IP); - _controlSocket.synch(); - std::string response; - int status = sendCommand("ABOR", response); - if (status == 426) - status = _controlSocket.receiveStatusMessage(response); - if (status != 226) throw FTPException("Cannot abort transfer", response); -} - - -int FTPClientSession::sendCommand(const std::string& command, std::string& response) -{ - _controlSocket.sendMessage(command); - return _controlSocket.receiveStatusMessage(response); -} - - -int FTPClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response) -{ - _controlSocket.sendMessage(command, arg); - return _controlSocket.receiveStatusMessage(response); -} - - -std::string FTPClientSession::extractPath(const std::string& response) -{ - std::string path; - std::string::const_iterator it = response.begin(); - std::string::const_iterator end = response.end(); - while (it != end && *it != '"') ++it; - if (it != end) - { - ++it; - while (it != end) - { - if (*it == '"') - { - ++it; - if (it != end && *it != '"') break; - } - path += *it++; - } - } - return path; -} - - -StreamSocket FTPClientSession::establishDataConnection(const std::string& command, const std::string& arg) -{ - if (_passiveMode) - return passiveDataConnection(command, arg); - else - return activeDataConnection(command, arg); -} - - -StreamSocket FTPClientSession::activeDataConnection(const std::string& command, const std::string& arg) -{ - ServerSocket server(SocketAddress(_controlSocket.address().host(), 0)); - sendPortCommand(server.address()); - std::string response; - int status = sendCommand(command, arg, response); - if (!isPositivePreliminary(status)) throw FTPException(command + " command failed", response); - if (server.poll(_timeout, Socket::SELECT_READ)) - return server.acceptConnection(); - else - throw FTPException("The server has not initiated a data connection"); -} - - -StreamSocket FTPClientSession::passiveDataConnection(const std::string& command, const std::string& arg) -{ - SocketAddress sa(sendPassiveCommand()); - StreamSocket sock(sa); - std::string response; - int status = sendCommand(command, arg, response); - if (!isPositivePreliminary(status)) throw FTPException(command + " command failed", response); - return sock; -} - - -void FTPClientSession::sendPortCommand(const SocketAddress& addr) -{ - if (_supports1738) - { - if (sendEPRT(addr)) - return; - else - _supports1738 = false; - } - sendPORT(addr); -} - - -SocketAddress FTPClientSession::sendPassiveCommand() -{ - SocketAddress addr; - if (_supports1738) - { - if (sendEPSV(addr)) - return addr; - else - _supports1738 = false; - } - sendPASV(addr); - return addr; -} - - -bool FTPClientSession::sendEPRT(const SocketAddress& addr) -{ - std::string arg("|"); - arg += addr.af() == AF_INET ? '1' : '2'; - arg += '|'; - arg += addr.host().toString(); - arg += '|'; - arg += NumberFormatter::format(addr.port()); - arg += '|'; - std::string response; - int status = sendCommand("EPRT", arg, response); - if (isPositiveCompletion(status)) - return true; - else if (isPermanentNegative(status)) - return false; - else - throw FTPException("EPRT command failed", response); -} - - -void FTPClientSession::sendPORT(const SocketAddress& addr) -{ - std::string arg(addr.host().toString()); - for (std::string::iterator it = arg.begin(); it != arg.end(); ++it) - { - if (*it == '.') *it = ','; - } - arg += ','; - Poco::UInt16 port = addr.port(); - arg += NumberFormatter::format(port/256); - arg += ','; - arg += NumberFormatter::format(port % 256); - std::string response; - int status = sendCommand("PORT", arg, response); - if (!isPositiveCompletion(status)) throw FTPException("PORT command failed", response); -} - - -bool FTPClientSession::sendEPSV(SocketAddress& addr) -{ - std::string response; - int status = sendCommand("EPSV", response); - if (isPositiveCompletion(status)) - { - parseExtAddress(response, addr); - return true; - } - else if (isPermanentNegative(status)) - { - return false; - } - else throw FTPException("EPSV command failed", response); -} - - -void FTPClientSession::sendPASV(SocketAddress& addr) -{ - std::string response; - int status = sendCommand("PASV", response); - if (!isPositiveCompletion(status)) throw FTPException("PASV command failed", response); - parseAddress(response, addr); -} - - -void FTPClientSession::parseAddress(const std::string& str, SocketAddress& addr) -{ - std::string::const_iterator it = str.begin(); - std::string::const_iterator end = str.end(); - while (it != end && *it != '(') ++it; - if (it != end) ++it; - std::string host; - while (it != end && isdigit(*it)) host += *it++; - if (it != end && *it == ',') { host += '.'; ++it; } - while (it != end && isdigit(*it)) host += *it++; - if (it != end && *it == ',') { host += '.'; ++it; } - while (it != end && isdigit(*it)) host += *it++; - if (it != end && *it == ',') { host += '.'; ++it; } - while (it != end && isdigit(*it)) host += *it++; - if (it != end && *it == ',') ++it; - Poco::UInt16 portHi = 0; - while (it != end && isdigit(*it)) { portHi *= 10; portHi += *it++ - '0'; } - if (it != end && *it == ',') ++it; - Poco::UInt16 portLo = 0; - while (it != end && isdigit(*it)) { portLo *= 10; portLo += *it++ - '0'; } - addr = SocketAddress(host, portHi*256 + portLo); -} - - -void FTPClientSession::parseExtAddress(const std::string& str, SocketAddress& addr) -{ - std::string::const_iterator it = str.begin(); - std::string::const_iterator end = str.end(); - while (it != end && *it != '(') ++it; - if (it != end) ++it; - char delim = '|'; - if (it != end) delim = *it++; - if (it != end && *it == delim) ++it; - if (it != end && *it == delim) ++it; - Poco::UInt16 port = 0; - while (it != end && isdigit(*it)) { port *= 10; port += *it++ - '0'; } - addr = SocketAddress(_controlSocket.peerAddress().host(), port); -} - - -void FTPClientSession::endTransfer() -{ - if (_pDataStream) - { - delete _pDataStream; - _pDataStream = 0; - std::string response; - int status = _controlSocket.receiveStatusMessage(response); - if (!isPositiveCompletion(status)) throw FTPException("Data transfer failed", response); - } -} - - -} } // namespace Poco::Net +// +// FTPClientSession.cpp +// +// $Id: //poco/1.2/Net/src/FTPClientSession.cpp#1 $ +// +// Library: Net +// Package: FTP +// Module: FTPClientSession +// +// 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/FTPClientSession.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/SocketStream.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Net/NetException.h" +#include "Poco/NumberFormatter.h" +#include + + +using Poco::NumberFormatter; + + +namespace Poco { +namespace Net { + + +FTPClientSession::FTPClientSession(const StreamSocket& socket): + _controlSocket(socket), + _pDataStream(0), + _passiveMode(true), + _fileType(TYPE_BINARY), + _supports1738(true), + _isOpen(true), + _timeout(DEFAULT_TIMEOUT) +{ + _controlSocket.setReceiveTimeout(_timeout); +} + + +FTPClientSession::FTPClientSession(const std::string& host, Poco::UInt16 port): + _controlSocket(SocketAddress(host, port)), + _pDataStream(0), + _passiveMode(true), + _fileType(TYPE_BINARY), + _supports1738(true), + _isOpen(true), + _timeout(DEFAULT_TIMEOUT) +{ + _controlSocket.setReceiveTimeout(_timeout); +} + + +FTPClientSession::~FTPClientSession() +{ + try + { + close(); + } + catch (...) + { + } +} + + +void FTPClientSession::setTimeout(const Poco::Timespan& timeout) +{ + _timeout = timeout; + _controlSocket.setReceiveTimeout(timeout); +} + + +Poco::Timespan FTPClientSession::getTimeout() const +{ + return _timeout; +} + + +void FTPClientSession::setPassive(bool flag) +{ + _passiveMode = flag; +} + + +bool FTPClientSession::getPassive() const +{ + return _passiveMode; +} + + +void FTPClientSession::login(const std::string& username, const std::string& password) +{ + std::string response; + int status = _controlSocket.receiveStatusMessage(response); + if (!isPositiveCompletion(status)) throw FTPException("Cannot login to server", response); + status = sendCommand("USER", username, response); + if (isPositiveIntermediate(status)) + status = sendCommand("PASS", password, response); + if (!isPositiveCompletion(status)) throw FTPException("Login denied", response); + setFileType(_fileType); +} + + +void FTPClientSession::close() +{ + if (_isOpen) + { + try + { + endTransfer(); + } + catch (...) + { + } + std::string response; + sendCommand("QUIT", response); + _controlSocket.close(); + _isOpen = false; + } +} + + +void FTPClientSession::setFileType(FTPClientSession::FileType type) +{ + std::string response; + int status = sendCommand("TYPE", (type == TYPE_TEXT ? "A" : "I"), response); + if (!isPositiveCompletion(status)) throw FTPException("Cannot set file type", response); + _fileType = type; +} + + +FTPClientSession::FileType FTPClientSession::getFileType() const +{ + return _fileType; +} + + +std::string FTPClientSession::systemType() +{ + std::string response; + int status = sendCommand("SYST", response); + if (isPositiveCompletion(status)) + return response.substr(4); + else + throw FTPException("Cannot get remote system type", response); +} + + +void FTPClientSession::setWorkingDirectory(const std::string& path) +{ + std::string response; + int status = sendCommand("CWD", path, response); + if (!isPositiveCompletion(status)) throw FTPException("Cannot change directory", response); +} + + +std::string FTPClientSession::getWorkingDirectory() +{ + std::string response; + int status = sendCommand("PWD", response); + if (isPositiveCompletion(status)) + return extractPath(response); + else + throw FTPException("Cannot get current working directory", response); +} + + +void FTPClientSession::cdup() +{ + std::string response; + int status = sendCommand("CDUP", response); + if (!isPositiveCompletion(status)) throw FTPException("Cannot change directory", response); +} + + +void FTPClientSession::rename(const std::string& oldName, const std::string& newName) +{ + std::string response; + int status = sendCommand("RNFR", oldName, response); + if (!isPositiveIntermediate(status)) throw FTPException(std::string("Cannot rename ") + oldName, response); + status = sendCommand("RNTO", newName, response); + if (!isPositiveCompletion(status)) throw FTPException(std::string("Cannot rename to ") + newName, response); +} + + +void FTPClientSession::remove(const std::string& path) +{ + std::string response; + int status = sendCommand("DELE", path, response); + if (!isPositiveCompletion(status)) throw FTPException(std::string("Cannot remove " + path), response); +} + + +void FTPClientSession::createDirectory(const std::string& path) +{ + std::string response; + int status = sendCommand("MKD", path, response); + if (!isPositiveCompletion(status)) throw FTPException(std::string("Cannot create directory ") + path, response); +} + + +void FTPClientSession::removeDirectory(const std::string& path) +{ + std::string response; + int status = sendCommand("RMD", path, response); + if (!isPositiveCompletion(status)) throw FTPException(std::string("Cannot remove directory ") + path, response); +} + + +std::istream& FTPClientSession::beginDownload(const std::string& path) +{ + delete _pDataStream; + _pDataStream = 0; + _pDataStream = new SocketStream(establishDataConnection("RETR", path)); + return *_pDataStream; +} + + +void FTPClientSession::endDownload() +{ + endTransfer(); +} + + +std::ostream& FTPClientSession::beginUpload(const std::string& path) +{ + delete _pDataStream; + _pDataStream = 0; + _pDataStream = new SocketStream(establishDataConnection("STOR", path)); + return *_pDataStream; +} + + +void FTPClientSession::endUpload() +{ + endTransfer(); +} + + +std::istream& FTPClientSession::beginList(const std::string& path, bool extended) +{ + delete _pDataStream; + _pDataStream = 0; + _pDataStream = new SocketStream(establishDataConnection(extended ? "LIST" : "NLST", path)); + return *_pDataStream; +} + + +void FTPClientSession::endList() +{ + endTransfer(); +} + + +void FTPClientSession::abort() +{ + _controlSocket.sendByte(DialogSocket::TELNET_IP); + _controlSocket.synch(); + std::string response; + int status = sendCommand("ABOR", response); + if (status == 426) + status = _controlSocket.receiveStatusMessage(response); + if (status != 226) throw FTPException("Cannot abort transfer", response); +} + + +int FTPClientSession::sendCommand(const std::string& command, std::string& response) +{ + _controlSocket.sendMessage(command); + return _controlSocket.receiveStatusMessage(response); +} + + +int FTPClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response) +{ + _controlSocket.sendMessage(command, arg); + return _controlSocket.receiveStatusMessage(response); +} + + +std::string FTPClientSession::extractPath(const std::string& response) +{ + std::string path; + std::string::const_iterator it = response.begin(); + std::string::const_iterator end = response.end(); + while (it != end && *it != '"') ++it; + if (it != end) + { + ++it; + while (it != end) + { + if (*it == '"') + { + ++it; + if (it != end && *it != '"') break; + } + path += *it++; + } + } + return path; +} + + +StreamSocket FTPClientSession::establishDataConnection(const std::string& command, const std::string& arg) +{ + if (_passiveMode) + return passiveDataConnection(command, arg); + else + return activeDataConnection(command, arg); +} + + +StreamSocket FTPClientSession::activeDataConnection(const std::string& command, const std::string& arg) +{ + ServerSocket server(SocketAddress(_controlSocket.address().host(), 0)); + sendPortCommand(server.address()); + std::string response; + int status = sendCommand(command, arg, response); + if (!isPositivePreliminary(status)) throw FTPException(command + " command failed", response); + if (server.poll(_timeout, Socket::SELECT_READ)) + return server.acceptConnection(); + else + throw FTPException("The server has not initiated a data connection"); +} + + +StreamSocket FTPClientSession::passiveDataConnection(const std::string& command, const std::string& arg) +{ + SocketAddress sa(sendPassiveCommand()); + StreamSocket sock(sa); + std::string response; + int status = sendCommand(command, arg, response); + if (!isPositivePreliminary(status)) throw FTPException(command + " command failed", response); + return sock; +} + + +void FTPClientSession::sendPortCommand(const SocketAddress& addr) +{ + if (_supports1738) + { + if (sendEPRT(addr)) + return; + else + _supports1738 = false; + } + sendPORT(addr); +} + + +SocketAddress FTPClientSession::sendPassiveCommand() +{ + SocketAddress addr; + if (_supports1738) + { + if (sendEPSV(addr)) + return addr; + else + _supports1738 = false; + } + sendPASV(addr); + return addr; +} + + +bool FTPClientSession::sendEPRT(const SocketAddress& addr) +{ + std::string arg("|"); + arg += addr.af() == AF_INET ? '1' : '2'; + arg += '|'; + arg += addr.host().toString(); + arg += '|'; + arg += NumberFormatter::format(addr.port()); + arg += '|'; + std::string response; + int status = sendCommand("EPRT", arg, response); + if (isPositiveCompletion(status)) + return true; + else if (isPermanentNegative(status)) + return false; + else + throw FTPException("EPRT command failed", response); +} + + +void FTPClientSession::sendPORT(const SocketAddress& addr) +{ + std::string arg(addr.host().toString()); + for (std::string::iterator it = arg.begin(); it != arg.end(); ++it) + { + if (*it == '.') *it = ','; + } + arg += ','; + Poco::UInt16 port = addr.port(); + arg += NumberFormatter::format(port/256); + arg += ','; + arg += NumberFormatter::format(port % 256); + std::string response; + int status = sendCommand("PORT", arg, response); + if (!isPositiveCompletion(status)) throw FTPException("PORT command failed", response); +} + + +bool FTPClientSession::sendEPSV(SocketAddress& addr) +{ + std::string response; + int status = sendCommand("EPSV", response); + if (isPositiveCompletion(status)) + { + parseExtAddress(response, addr); + return true; + } + else if (isPermanentNegative(status)) + { + return false; + } + else throw FTPException("EPSV command failed", response); +} + + +void FTPClientSession::sendPASV(SocketAddress& addr) +{ + std::string response; + int status = sendCommand("PASV", response); + if (!isPositiveCompletion(status)) throw FTPException("PASV command failed", response); + parseAddress(response, addr); +} + + +void FTPClientSession::parseAddress(const std::string& str, SocketAddress& addr) +{ + std::string::const_iterator it = str.begin(); + std::string::const_iterator end = str.end(); + while (it != end && *it != '(') ++it; + if (it != end) ++it; + std::string host; + while (it != end && isdigit(*it)) host += *it++; + if (it != end && *it == ',') { host += '.'; ++it; } + while (it != end && isdigit(*it)) host += *it++; + if (it != end && *it == ',') { host += '.'; ++it; } + while (it != end && isdigit(*it)) host += *it++; + if (it != end && *it == ',') { host += '.'; ++it; } + while (it != end && isdigit(*it)) host += *it++; + if (it != end && *it == ',') ++it; + Poco::UInt16 portHi = 0; + while (it != end && isdigit(*it)) { portHi *= 10; portHi += *it++ - '0'; } + if (it != end && *it == ',') ++it; + Poco::UInt16 portLo = 0; + while (it != end && isdigit(*it)) { portLo *= 10; portLo += *it++ - '0'; } + addr = SocketAddress(host, portHi*256 + portLo); +} + + +void FTPClientSession::parseExtAddress(const std::string& str, SocketAddress& addr) +{ + std::string::const_iterator it = str.begin(); + std::string::const_iterator end = str.end(); + while (it != end && *it != '(') ++it; + if (it != end) ++it; + char delim = '|'; + if (it != end) delim = *it++; + if (it != end && *it == delim) ++it; + if (it != end && *it == delim) ++it; + Poco::UInt16 port = 0; + while (it != end && isdigit(*it)) { port *= 10; port += *it++ - '0'; } + addr = SocketAddress(_controlSocket.peerAddress().host(), port); +} + + +void FTPClientSession::endTransfer() +{ + if (_pDataStream) + { + delete _pDataStream; + _pDataStream = 0; + std::string response; + int status = _controlSocket.receiveStatusMessage(response); + if (!isPositiveCompletion(status)) throw FTPException("Data transfer failed", response); + } +} + + +} } // namespace Poco::Net diff --git a/Net/src/FTPStreamFactory.cpp b/Net/src/FTPStreamFactory.cpp index 70f49aa5b..977d0decd 100644 --- a/Net/src/FTPStreamFactory.cpp +++ b/Net/src/FTPStreamFactory.cpp @@ -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 diff --git a/Net/src/FilePartSource.cpp b/Net/src/FilePartSource.cpp index d613af3c5..4c3add6df 100644 --- a/Net/src/FilePartSource.cpp +++ b/Net/src/FilePartSource.cpp @@ -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 diff --git a/Net/src/HTMLForm.cpp b/Net/src/HTMLForm.cpp index 71b723bcb..5a9809c21 100644 --- a/Net/src/HTMLForm.cpp +++ b/Net/src/HTMLForm.cpp @@ -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 -#include - - -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::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::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 +#include + + +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::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::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 diff --git a/Net/src/HTTPBasicCredentials.cpp b/Net/src/HTTPBasicCredentials.cpp index 75300b750..ab8d5fb95 100644 --- a/Net/src/HTTPBasicCredentials.cpp +++ b/Net/src/HTTPBasicCredentials.cpp @@ -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 - - -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::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 + + +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::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 diff --git a/Net/src/HTTPBufferAllocator.cpp b/Net/src/HTTPBufferAllocator.cpp index ebc69c2f3..6e2682e57 100644 --- a/Net/src/HTTPBufferAllocator.cpp +++ b/Net/src/HTTPBufferAllocator.cpp @@ -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(_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(_pool.get()); +} + + +void HTTPBufferAllocator::deallocate(char* ptr, std::streamsize size) +{ + poco_assert_dbg (size == BUFFER_SIZE); + + _pool.release(ptr); +} + + +} } // namespace Poco::Net diff --git a/Net/src/HTTPChunkedStream.cpp b/Net/src/HTTPChunkedStream.cpp index c1af30c04..2911c7593 100644 --- a/Net/src/HTTPChunkedStream.cpp +++ b/Net/src/HTTPChunkedStream.cpp @@ -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 - - -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::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 + + +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::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 diff --git a/Net/src/HTTPClientSession.cpp b/Net/src/HTTPClientSession.cpp index 9825de994..0dd859a4b 100644 --- a/Net/src/HTTPClientSession.cpp +++ b/Net/src/HTTPClientSession.cpp @@ -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 diff --git a/Net/src/HTTPCookie.cpp b/Net/src/HTTPCookie.cpp index 1868a0036..30f616aa1 100644 --- a/Net/src/HTTPCookie.cpp +++ b/Net/src/HTTPCookie.cpp @@ -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 diff --git a/Net/src/HTTPFixedLengthStream.cpp b/Net/src/HTTPFixedLengthStream.cpp index 6abfc4aa3..7443d975b 100644 --- a/Net/src/HTTPFixedLengthStream.cpp +++ b/Net/src/HTTPFixedLengthStream.cpp @@ -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 diff --git a/Net/src/HTTPHeaderStream.cpp b/Net/src/HTTPHeaderStream.cpp index aec8e2f7b..7eaa5f79b 100644 --- a/Net/src/HTTPHeaderStream.cpp +++ b/Net/src/HTTPHeaderStream.cpp @@ -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::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::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 diff --git a/Net/src/HTTPIOStream.cpp b/Net/src/HTTPIOStream.cpp index e9bffe14d..656d32bf2 100644 --- a/Net/src/HTTPIOStream.cpp +++ b/Net/src/HTTPIOStream.cpp @@ -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 diff --git a/Net/src/HTTPMessage.cpp b/Net/src/HTTPMessage.cpp index 700afe192..900f8f25d 100644 --- a/Net/src/HTTPMessage.cpp +++ b/Net/src/HTTPMessage.cpp @@ -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 diff --git a/Net/src/HTTPRequest.cpp b/Net/src/HTTPRequest.cpp index cc833a369..2cb01f046 100644 --- a/Net/src/HTTPRequest.cpp +++ b/Net/src/HTTPRequest.cpp @@ -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 - - -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::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 + + +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::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 diff --git a/Net/src/HTTPRequestHandler.cpp b/Net/src/HTTPRequestHandler.cpp index 7b5943a3d..8149e0014 100644 --- a/Net/src/HTTPRequestHandler.cpp +++ b/Net/src/HTTPRequestHandler.cpp @@ -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 diff --git a/Net/src/HTTPRequestHandlerFactory.cpp b/Net/src/HTTPRequestHandlerFactory.cpp index c30ed9648..ceb9646f7 100644 --- a/Net/src/HTTPRequestHandlerFactory.cpp +++ b/Net/src/HTTPRequestHandlerFactory.cpp @@ -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 diff --git a/Net/src/HTTPResponse.cpp b/Net/src/HTTPResponse.cpp index b1164c29d..8ff9ce719 100644 --- a/Net/src/HTTPResponse.cpp +++ b/Net/src/HTTPResponse.cpp @@ -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 - - -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& 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::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 + + +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& 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::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 diff --git a/Net/src/HTTPServer.cpp b/Net/src/HTTPServer.cpp index 36364a215..4abc7f82c 100644 --- a/Net/src/HTTPServer.cpp +++ b/Net/src/HTTPServer.cpp @@ -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 diff --git a/Net/src/HTTPServerConnection.cpp b/Net/src/HTTPServerConnection.cpp index e9f634c9a..f760dbe99 100644 --- a/Net/src/HTTPServerConnection.cpp +++ b/Net/src/HTTPServerConnection.cpp @@ -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 - - -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 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 + + +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 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 diff --git a/Net/src/HTTPServerConnectionFactory.cpp b/Net/src/HTTPServerConnectionFactory.cpp index f77d64a43..f2e5cae03 100644 --- a/Net/src/HTTPServerConnectionFactory.cpp +++ b/Net/src/HTTPServerConnectionFactory.cpp @@ -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 diff --git a/Net/src/HTTPServerParams.cpp b/Net/src/HTTPServerParams.cpp index da47f88c7..7a10891fe 100644 --- a/Net/src/HTTPServerParams.cpp +++ b/Net/src/HTTPServerParams.cpp @@ -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 diff --git a/Net/src/HTTPServerRequest.cpp b/Net/src/HTTPServerRequest.cpp index 982f5daf1..8decb294a 100644 --- a/Net/src/HTTPServerRequest.cpp +++ b/Net/src/HTTPServerRequest.cpp @@ -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 diff --git a/Net/src/HTTPServerResponse.cpp b/Net/src/HTTPServerResponse.cpp index a58987a4c..c9d2a3347 100644 --- a/Net/src/HTTPServerResponse.cpp +++ b/Net/src/HTTPServerResponse.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/HTTPServerSession.cpp b/Net/src/HTTPServerSession.cpp index dfeb9160e..d74d2f427 100644 --- a/Net/src/HTTPServerSession.cpp +++ b/Net/src/HTTPServerSession.cpp @@ -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 diff --git a/Net/src/HTTPSession.cpp b/Net/src/HTTPSession.cpp index fb0e14b34..da6dbd1c0 100644 --- a/Net/src/HTTPSession.cpp +++ b/Net/src/HTTPSession.cpp @@ -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 - - -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::eof(); -} - - -int HTTPSession::peek() -{ - if (_pCurrent == _pEnd) - refill(); - - if (_pCurrent < _pEnd) - return *_pCurrent; - else - return std::char_traits::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 + + +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::eof(); +} + + +int HTTPSession::peek() +{ + if (_pCurrent == _pEnd) + refill(); + + if (_pCurrent < _pEnd) + return *_pCurrent; + else + return std::char_traits::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 diff --git a/Net/src/HTTPSessionFactory.cpp b/Net/src/HTTPSessionFactory.cpp index ce7ea83c3..fed92509e 100644 --- a/Net/src/HTTPSessionFactory.cpp +++ b/Net/src/HTTPSessionFactory.cpp @@ -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 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 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 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 singleton; + return *singleton.get(); +} + + +HTTPSessionFactory::InstantiatorInfo::InstantiatorInfo(HTTPSessionInstantiator* pInst): pIn(pInst), cnt(1) +{ + poco_check_ptr (pIn); +} + + +} } // namespace Poco::Net diff --git a/Net/src/HTTPSessionInstantiator.cpp b/Net/src/HTTPSessionInstantiator.cpp index 652eb8e52..75f928e13 100644 --- a/Net/src/HTTPSessionInstantiator.cpp +++ b/Net/src/HTTPSessionInstantiator.cpp @@ -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 diff --git a/Net/src/HTTPStream.cpp b/Net/src/HTTPStream.cpp index c75ca0253..ed26f5382 100644 --- a/Net/src/HTTPStream.cpp +++ b/Net/src/HTTPStream.cpp @@ -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 diff --git a/Net/src/HTTPStreamFactory.cpp b/Net/src/HTTPStreamFactory.cpp index 1087fb970..8e5bfadf2 100644 --- a/Net/src/HTTPStreamFactory.cpp +++ b/Net/src/HTTPStreamFactory.cpp @@ -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 diff --git a/Net/src/HostEntry.cpp b/Net/src/HostEntry.cpp index 3e8e341cb..506dfe6c7 100644 --- a/Net/src/HostEntry.cpp +++ b/Net/src/HostEntry.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/ICMPClient.cpp b/Net/src/ICMPClient.cpp index 9e56c921e..38472991b 100644 --- a/Net/src/ICMPClient.cpp +++ b/Net/src/ICMPClient.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/ICMPEventArgs.cpp b/Net/src/ICMPEventArgs.cpp index 9c6f97160..e81c3e6bd 100644 --- a/Net/src/ICMPEventArgs.cpp +++ b/Net/src/ICMPEventArgs.cpp @@ -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 diff --git a/Net/src/ICMPPacket.cpp b/Net/src/ICMPPacket.cpp index 3ffd80160..b7ad302ab 100644 --- a/Net/src/ICMPPacket.cpp +++ b/Net/src/ICMPPacket.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/ICMPPacketImpl.cpp b/Net/src/ICMPPacketImpl.cpp index 796445503..3af809fdd 100644 --- a/Net/src/ICMPPacketImpl.cpp +++ b/Net/src/ICMPPacketImpl.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/ICMPSocket.cpp b/Net/src/ICMPSocket.cpp index ab08d7caa..8be8c63a1 100644 --- a/Net/src/ICMPSocket.cpp +++ b/Net/src/ICMPSocket.cpp @@ -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(impl())) - throw InvalidArgumentException("Cannot assign incompatible socket"); -} - - -ICMPSocket::ICMPSocket(SocketImpl* pImpl): - Socket(pImpl) -{ - if (!dynamic_cast(impl())) - throw InvalidArgumentException("Cannot assign incompatible socket"); -} - - -ICMPSocket::~ICMPSocket() -{ -} - - -ICMPSocket& ICMPSocket::operator = (const Socket& socket) -{ - if (dynamic_cast(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(impl())) + throw InvalidArgumentException("Cannot assign incompatible socket"); +} + + +ICMPSocket::ICMPSocket(SocketImpl* pImpl): + Socket(pImpl) +{ + if (!dynamic_cast(impl())) + throw InvalidArgumentException("Cannot assign incompatible socket"); +} + + +ICMPSocket::~ICMPSocket() +{ +} + + +ICMPSocket& ICMPSocket::operator = (const Socket& socket) +{ + if (dynamic_cast(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 diff --git a/Net/src/ICMPSocketImpl.cpp b/Net/src/ICMPSocketImpl.cpp index 27123ad09..82613c266 100644 --- a/Net/src/ICMPSocketImpl.cpp +++ b/Net/src/ICMPSocketImpl.cpp @@ -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 diff --git a/Net/src/ICMPv4PacketImpl.cpp b/Net/src/ICMPv4PacketImpl.cpp index 0fb19b7db..d5c63b695 100644 --- a/Net/src/ICMPv4PacketImpl.cpp +++ b/Net/src/ICMPv4PacketImpl.cpp @@ -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 - - -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(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(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 + + +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(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(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 diff --git a/Net/src/IPAddress.cpp b/Net/src/IPAddress.cpp index cdf76b5a2..544a9af0a 100644 --- a/Net/src/IPAddress.cpp +++ b/Net/src/IPAddress.cpp @@ -1,747 +1,747 @@ -// -// IPAddress.cpp -// -// $Id: //poco/1.2/Net/src/IPAddress.cpp#2 $ -// -// Library: Net -// Package: NetCore -// Module: IPAddress -// -// 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/IPAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/RefCountedObject.h" -#include "Poco/NumberFormatter.h" -#include "Poco/Types.h" -#include -#include - - -using Poco::RefCountedObject; -using Poco::NumberFormatter; -using Poco::UInt8; -using Poco::UInt16; -using Poco::UInt32; - - -namespace Poco { -namespace Net { - - -// -// IPAddressImpl -// - - -class IPAddressImpl: public RefCountedObject -{ -public: - virtual std::string toString() const = 0; - virtual poco_socklen_t length() const = 0; - virtual const void* addr() const = 0; - virtual IPAddress::Family family() const = 0; - virtual int af() const = 0; - virtual bool isWildcard() const = 0; - virtual bool isBroadcast() const = 0; - virtual bool isLoopback() const = 0; - virtual bool isMulticast() const = 0; - virtual bool isLinkLocal() const = 0; - virtual bool isSiteLocal() const = 0; - virtual bool isIPv4Mapped() const = 0; - virtual bool isIPv4Compatible() const = 0; - virtual bool isWellKnownMC() const = 0; - virtual bool isNodeLocalMC() const = 0; - virtual bool isLinkLocalMC() const = 0; - virtual bool isSiteLocalMC() const = 0; - virtual bool isOrgLocalMC() const = 0; - virtual bool isGlobalMC() const = 0; - -protected: - IPAddressImpl() - { - } - - virtual ~IPAddressImpl() - { - } - -private: - IPAddressImpl(const IPAddressImpl&); - IPAddressImpl& operator = (const IPAddressImpl&); -}; - - -class IPv4AddressImpl: public IPAddressImpl -{ -public: - IPv4AddressImpl() - { - memset(&_addr, 0, sizeof(_addr)); - } - - IPv4AddressImpl(const void* addr) - { - memcpy(&_addr, addr, sizeof(_addr)); - } - - std::string toString() const - { - const UInt8* bytes = reinterpret_cast(&_addr); - std::string result; - result.reserve(16); - result.append(NumberFormatter::format(bytes[0])); - result.append("."); - result.append(NumberFormatter::format(bytes[1])); - result.append("."); - result.append(NumberFormatter::format(bytes[2])); - result.append("."); - result.append(NumberFormatter::format(bytes[3])); - return result; - } - - poco_socklen_t length() const - { - return sizeof(_addr); - } - - const void* addr() const - { - return &_addr; - } - - IPAddress::Family family() const - { - return IPAddress::IPv4; - } - - int af() const - { - return AF_INET; - } - - bool isWildcard() const - { - return _addr.s_addr == INADDR_ANY; - } - - bool isBroadcast() const - { - return _addr.s_addr == INADDR_NONE; - } - - bool isLoopback() const - { - return ntohl(_addr.s_addr) == 0x7F000001; // 127.0.0.1 - } - - bool isMulticast() const - { - return (ntohl(_addr.s_addr) & 0xF0000000) == 0xE0000000; // 224.0.0.0/24 to 239.0.0.0/24 - } - - bool isLinkLocal() const - { - return (ntohl(_addr.s_addr) & 0xFFFF0000) == 0xA9FE0000; // 169.254.0.0/16 - } - - bool isSiteLocal() const - { - UInt32 addr = ntohl(_addr.s_addr); - return (addr & 0xFF000000) == 0x0A000000 || // 10.0.0.0/24 - (addr & 0xFFFF0000) == 0xC0A80000 || // 192.68.0.0/16 - addr >= 0xAC100000 && addr <= 0xAC1FFFFF; // 172.16.0.0 to 172.31.255.255 - } - - bool isIPv4Compatible() const - { - return true; - } - - bool isIPv4Mapped() const - { - return true; - } - - bool isWellKnownMC() const - { - return (ntohl(_addr.s_addr) & 0xFFFFFF00) == 0xE0000000; // 224.0.0.0/8 - } - - bool isNodeLocalMC() const - { - return false; - } - - bool isLinkLocalMC() const - { - return (ntohl(_addr.s_addr) & 0xFF000000) == 0xE0000000; // 244.0.0.0/24 - } - - bool isSiteLocalMC() const - { - return (ntohl(_addr.s_addr) & 0xFFFF0000) == 0xEFFF0000; // 239.255.0.0/16 - } - - bool isOrgLocalMC() const - { - return (ntohl(_addr.s_addr) & 0xFFFF0000) == 0xEFC00000; // 239.192.0.0/16 - } - - bool isGlobalMC() const - { - UInt32 addr = ntohl(_addr.s_addr); - return addr >= 0xE0000100 && addr <= 0xEE000000; // 224.0.1.0 to 238.255.255.255 - } - - static IPv4AddressImpl* parse(const std::string& addr) - { - if (addr.empty()) return 0; -#if defined(_WIN32) - struct in_addr ia; - ia.s_addr = inet_addr(addr.c_str()); - if (ia.s_addr == INADDR_NONE && addr != "255.255.255.255") - return 0; - else - return new IPv4AddressImpl(&ia); -#else - struct in_addr ia; - if (inet_aton(addr.c_str(), &ia)) - return new IPv4AddressImpl(&ia); - else - return 0; -#endif - } - -private: - struct in_addr _addr; -}; - - -#if defined(POCO_HAVE_IPv6) - - -class IPv6AddressImpl: public IPAddressImpl -{ -public: - IPv6AddressImpl() - { - memset(&_addr, 0, sizeof(_addr)); - } - - IPv6AddressImpl(const void* addr) - { - memcpy(&_addr, addr, sizeof(_addr)); - } - - std::string toString() const - { - const UInt16* words = reinterpret_cast(&_addr); - if (isIPv4Compatible() || isIPv4Mapped()) - { - std::string result; - result.reserve(24); - if (words[5] == 0) - result.append("::"); - else - result.append("::FFFF:"); - const UInt8* bytes = reinterpret_cast(&_addr); - result.append(NumberFormatter::format(bytes[12])); - result.append("."); - result.append(NumberFormatter::format(bytes[13])); - result.append("."); - result.append(NumberFormatter::format(bytes[14])); - result.append("."); - result.append(NumberFormatter::format(bytes[15])); - return result; - } - else - { - std::string result; - result.reserve(46); - bool zeroSequence = false; - int i = 0; - while (i < 8) - { - if (!zeroSequence && words[i] == 0) - { - int zi = i; - while (zi < 8 && words[zi] == 0) ++zi; - if (zi > i + 1) - { - i = zi; - result.append(":"); - zeroSequence = true; - } - } - if (i > 0) result.append(":"); - if (i < 8) result.append(NumberFormatter::formatHex(words[i++])); - } - return result; - } - } - - poco_socklen_t length() const - { - return sizeof(_addr); - } - - const void* addr() const - { - return &_addr; - } - - IPAddress::Family family() const - { - return IPAddress::IPv6; - } - - int af() const - { - return AF_INET6; - } - - bool isWildcard() const - { - const UInt16* words = reinterpret_cast(&_addr); - return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && - words[4] == 0 && words[5] == 0 && words[6] == 0 && words[7] == 0; - } - - bool isBroadcast() const - { - return false; - } - - bool isLoopback() const - { - const UInt16* words = reinterpret_cast(&_addr); - return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && - words[4] == 0 && words[5] == 0 && words[6] == 0 && words[7] == 1; - } - - bool isMulticast() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFE0) == 0xFF00; - } - - bool isLinkLocal() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFE0) == 0xFE80; - } - - bool isSiteLocal() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFE0) == 0xFEC0; - } - - bool isIPv4Compatible() const - { - const UInt16* words = reinterpret_cast(&_addr); - return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && words[5] == 0; - } - - bool isIPv4Mapped() const - { - const UInt16* words = reinterpret_cast(&_addr); - return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && words[5] == 0xFFFF; - } - - bool isWellKnownMC() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFF0) == 0xFF00; - } - - bool isNodeLocalMC() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFEF) == 0xFF01; - } - - bool isLinkLocalMC() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFEF) == 0xFF02; - } - - bool isSiteLocalMC() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFEF) == 0xFF05; - } - - bool isOrgLocalMC() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFEF) == 0xFF08; - } - - bool isGlobalMC() const - { - const UInt16* words = reinterpret_cast(&_addr); - return (words[0] & 0xFFEF) == 0xFF0F; - } - - static IPv6AddressImpl* parse(const std::string& addr) - { - if (addr.empty()) return 0; -#if defined(_WIN32) - struct addrinfo* pAI; - struct addrinfo hints; - memset(&hints, 0, sizeof(hints)); - hints.ai_flags = AI_NUMERICHOST; - int rc = getaddrinfo(addr.c_str(), NULL, &hints, &pAI); - if (rc == 0) - { - IPv6AddressImpl* pResult = new IPv6AddressImpl(&reinterpret_cast(pAI->ai_addr)->sin6_addr); - freeaddrinfo(pAI); - return pResult; - } - else return 0; -#else - struct in6_addr ia; - if (inet_pton(AF_INET6, addr.c_str(), &ia) == 1) - return new IPv6AddressImpl(&ia); - else - return 0; -#endif - } - -private: - struct in6_addr _addr; -}; - - -#endif // POCO_HAVE_IPv6 - - -// -// IPAddress -// - - -IPAddress::IPAddress(): _pImpl(new IPv4AddressImpl) -{ -} - - -IPAddress::IPAddress(const IPAddress& addr): _pImpl(addr._pImpl) -{ - _pImpl->duplicate(); -} - - -IPAddress::IPAddress(Family family): _pImpl(0) -{ - if (family == IPv4) - _pImpl = new IPv4AddressImpl(); -#if defined(POCO_HAVE_IPv6) - else if (family == IPv6) - _pImpl = new IPv6AddressImpl(); -#endif - else Poco::InvalidArgumentException("Invalid or unsupported address family passed to IPAddress()"); -} - - -IPAddress::IPAddress(const std::string& addr) -{ - _pImpl = IPv4AddressImpl::parse(addr); -#if defined(POCO_HAVE_IPv6) - if (!_pImpl) - _pImpl = IPv6AddressImpl::parse(addr); -#endif - if (!_pImpl) throw InvalidAddressException(addr); -} - - -IPAddress::IPAddress(const std::string& addr, Family family): _pImpl(0) -{ - if (family == IPv4) - _pImpl = IPv4AddressImpl::parse(addr); -#if defined(POCO_HAVE_IPv6) - else if (family == IPv6) - _pImpl = IPv6AddressImpl::parse(addr); -#endif - else throw Poco::InvalidArgumentException("Invalid or unsupported address family passed to IPAddress()"); -} - - -IPAddress::IPAddress(const void* addr, poco_socklen_t length) -{ - if (length == sizeof(struct in_addr)) - _pImpl = new IPv4AddressImpl(addr); -#if defined(POCO_HAVE_IPv6) - else if (length == sizeof(struct in6_addr)) - _pImpl = new IPv6AddressImpl(addr); -#endif - else throw Poco::InvalidArgumentException("Invalid address length passed to IPAddress()"); -} - - -IPAddress::~IPAddress() -{ - _pImpl->release(); -} - - -IPAddress& IPAddress::operator = (const IPAddress& addr) -{ - if (&addr != this) - { - _pImpl->release(); - _pImpl = addr._pImpl; - _pImpl->duplicate(); - } - return *this; -} - - -void IPAddress::swap(IPAddress& address) -{ - std::swap(_pImpl, address._pImpl); -} - - -IPAddress::Family IPAddress::family() const -{ - return _pImpl->family(); -} - - -std::string IPAddress::toString() const -{ - return _pImpl->toString(); -} - - -bool IPAddress::isWildcard() const -{ - return _pImpl->isWildcard(); -} - -bool IPAddress::isBroadcast() const -{ - return _pImpl->isBroadcast(); -} - - -bool IPAddress::isLoopback() const -{ - return _pImpl->isLoopback(); -} - - -bool IPAddress::isMulticast() const -{ - return _pImpl->isMulticast(); -} - - -bool IPAddress::isUnicast() const -{ - return !isWildcard() && !isBroadcast() && !isMulticast(); -} - - -bool IPAddress::isLinkLocal() const -{ - return _pImpl->isLinkLocal(); -} - - -bool IPAddress::isSiteLocal() const -{ - return _pImpl->isSiteLocal(); -} - - -bool IPAddress::isIPv4Compatible() const -{ - return _pImpl->isIPv4Compatible(); -} - - -bool IPAddress::isIPv4Mapped() const -{ - return _pImpl->isIPv4Mapped(); -} - - -bool IPAddress::isWellKnownMC() const -{ - return _pImpl->isWellKnownMC(); -} - - -bool IPAddress::isNodeLocalMC() const -{ - return _pImpl->isNodeLocalMC(); -} - - -bool IPAddress::isLinkLocalMC() const -{ - return _pImpl->isLinkLocalMC(); -} - - -bool IPAddress::isSiteLocalMC() const -{ - return _pImpl->isSiteLocalMC(); -} - - -bool IPAddress::isOrgLocalMC() const -{ - return _pImpl->isOrgLocalMC(); -} - - -bool IPAddress::isGlobalMC() const -{ - return _pImpl->isGlobalMC(); -} - - -bool IPAddress::operator == (const IPAddress& a) const -{ - poco_socklen_t l1 = length(); - poco_socklen_t l2 = a.length(); - if (l1 == l2) - return memcmp(addr(), a.addr(), l1) == 0; - else - return false; -} - - -bool IPAddress::operator != (const IPAddress& a) const -{ - poco_socklen_t l1 = length(); - poco_socklen_t l2 = a.length(); - if (l1 == l2) - return memcmp(addr(), a.addr(), l1) != 0; - else - return true; -} - - -bool IPAddress::operator < (const IPAddress& a) const -{ - poco_socklen_t l1 = length(); - poco_socklen_t l2 = a.length(); - if (l1 == l2) - return memcmp(addr(), a.addr(), l1) < 0; - else - return l1 < l2; -} - - -bool IPAddress::operator <= (const IPAddress& a) const -{ - poco_socklen_t l1 = length(); - poco_socklen_t l2 = a.length(); - if (l1 == l2) - return memcmp(addr(), a.addr(), l1) <= 0; - else - return l1 < l2; -} - - -bool IPAddress::operator > (const IPAddress& a) const -{ - poco_socklen_t l1 = length(); - poco_socklen_t l2 = a.length(); - if (l1 == l2) - return memcmp(addr(), a.addr(), l1) > 0; - else - return l1 > l2; -} - - -bool IPAddress::operator >= (const IPAddress& a) const -{ - poco_socklen_t l1 = length(); - poco_socklen_t l2 = a.length(); - if (l1 == l2) - return memcmp(addr(), a.addr(), l1) >= 0; - else - return l1 > l2; -} - - -poco_socklen_t IPAddress::length() const -{ - return _pImpl->length(); -} - - -const void* IPAddress::addr() const -{ - return _pImpl->addr(); -} - - -int IPAddress::af() const -{ - return _pImpl->af(); -} - - -void IPAddress::init(IPAddressImpl* pImpl) -{ - _pImpl->release(); - _pImpl = pImpl; -} - - -IPAddress IPAddress::parse(const std::string& addr) -{ - return IPAddress(addr); -} - - -bool IPAddress::tryParse(const std::string& addr, IPAddress& result) -{ - IPAddressImpl* pImpl = IPv4AddressImpl::parse(addr); -#if defined(POCO_HAVE_IPv6) - if (!pImpl) pImpl = IPv6AddressImpl::parse(addr); -#endif - if (pImpl) - { - result.init(pImpl); - return true; - } - else return false; -} - - -} } // namespace Poco::Net +// +// IPAddress.cpp +// +// $Id: //poco/1.2/Net/src/IPAddress.cpp#2 $ +// +// Library: Net +// Package: NetCore +// Module: IPAddress +// +// 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/IPAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/RefCountedObject.h" +#include "Poco/NumberFormatter.h" +#include "Poco/Types.h" +#include +#include + + +using Poco::RefCountedObject; +using Poco::NumberFormatter; +using Poco::UInt8; +using Poco::UInt16; +using Poco::UInt32; + + +namespace Poco { +namespace Net { + + +// +// IPAddressImpl +// + + +class IPAddressImpl: public RefCountedObject +{ +public: + virtual std::string toString() const = 0; + virtual poco_socklen_t length() const = 0; + virtual const void* addr() const = 0; + virtual IPAddress::Family family() const = 0; + virtual int af() const = 0; + virtual bool isWildcard() const = 0; + virtual bool isBroadcast() const = 0; + virtual bool isLoopback() const = 0; + virtual bool isMulticast() const = 0; + virtual bool isLinkLocal() const = 0; + virtual bool isSiteLocal() const = 0; + virtual bool isIPv4Mapped() const = 0; + virtual bool isIPv4Compatible() const = 0; + virtual bool isWellKnownMC() const = 0; + virtual bool isNodeLocalMC() const = 0; + virtual bool isLinkLocalMC() const = 0; + virtual bool isSiteLocalMC() const = 0; + virtual bool isOrgLocalMC() const = 0; + virtual bool isGlobalMC() const = 0; + +protected: + IPAddressImpl() + { + } + + virtual ~IPAddressImpl() + { + } + +private: + IPAddressImpl(const IPAddressImpl&); + IPAddressImpl& operator = (const IPAddressImpl&); +}; + + +class IPv4AddressImpl: public IPAddressImpl +{ +public: + IPv4AddressImpl() + { + memset(&_addr, 0, sizeof(_addr)); + } + + IPv4AddressImpl(const void* addr) + { + memcpy(&_addr, addr, sizeof(_addr)); + } + + std::string toString() const + { + const UInt8* bytes = reinterpret_cast(&_addr); + std::string result; + result.reserve(16); + result.append(NumberFormatter::format(bytes[0])); + result.append("."); + result.append(NumberFormatter::format(bytes[1])); + result.append("."); + result.append(NumberFormatter::format(bytes[2])); + result.append("."); + result.append(NumberFormatter::format(bytes[3])); + return result; + } + + poco_socklen_t length() const + { + return sizeof(_addr); + } + + const void* addr() const + { + return &_addr; + } + + IPAddress::Family family() const + { + return IPAddress::IPv4; + } + + int af() const + { + return AF_INET; + } + + bool isWildcard() const + { + return _addr.s_addr == INADDR_ANY; + } + + bool isBroadcast() const + { + return _addr.s_addr == INADDR_NONE; + } + + bool isLoopback() const + { + return ntohl(_addr.s_addr) == 0x7F000001; // 127.0.0.1 + } + + bool isMulticast() const + { + return (ntohl(_addr.s_addr) & 0xF0000000) == 0xE0000000; // 224.0.0.0/24 to 239.0.0.0/24 + } + + bool isLinkLocal() const + { + return (ntohl(_addr.s_addr) & 0xFFFF0000) == 0xA9FE0000; // 169.254.0.0/16 + } + + bool isSiteLocal() const + { + UInt32 addr = ntohl(_addr.s_addr); + return (addr & 0xFF000000) == 0x0A000000 || // 10.0.0.0/24 + (addr & 0xFFFF0000) == 0xC0A80000 || // 192.68.0.0/16 + addr >= 0xAC100000 && addr <= 0xAC1FFFFF; // 172.16.0.0 to 172.31.255.255 + } + + bool isIPv4Compatible() const + { + return true; + } + + bool isIPv4Mapped() const + { + return true; + } + + bool isWellKnownMC() const + { + return (ntohl(_addr.s_addr) & 0xFFFFFF00) == 0xE0000000; // 224.0.0.0/8 + } + + bool isNodeLocalMC() const + { + return false; + } + + bool isLinkLocalMC() const + { + return (ntohl(_addr.s_addr) & 0xFF000000) == 0xE0000000; // 244.0.0.0/24 + } + + bool isSiteLocalMC() const + { + return (ntohl(_addr.s_addr) & 0xFFFF0000) == 0xEFFF0000; // 239.255.0.0/16 + } + + bool isOrgLocalMC() const + { + return (ntohl(_addr.s_addr) & 0xFFFF0000) == 0xEFC00000; // 239.192.0.0/16 + } + + bool isGlobalMC() const + { + UInt32 addr = ntohl(_addr.s_addr); + return addr >= 0xE0000100 && addr <= 0xEE000000; // 224.0.1.0 to 238.255.255.255 + } + + static IPv4AddressImpl* parse(const std::string& addr) + { + if (addr.empty()) return 0; +#if defined(_WIN32) + struct in_addr ia; + ia.s_addr = inet_addr(addr.c_str()); + if (ia.s_addr == INADDR_NONE && addr != "255.255.255.255") + return 0; + else + return new IPv4AddressImpl(&ia); +#else + struct in_addr ia; + if (inet_aton(addr.c_str(), &ia)) + return new IPv4AddressImpl(&ia); + else + return 0; +#endif + } + +private: + struct in_addr _addr; +}; + + +#if defined(POCO_HAVE_IPv6) + + +class IPv6AddressImpl: public IPAddressImpl +{ +public: + IPv6AddressImpl() + { + memset(&_addr, 0, sizeof(_addr)); + } + + IPv6AddressImpl(const void* addr) + { + memcpy(&_addr, addr, sizeof(_addr)); + } + + std::string toString() const + { + const UInt16* words = reinterpret_cast(&_addr); + if (isIPv4Compatible() || isIPv4Mapped()) + { + std::string result; + result.reserve(24); + if (words[5] == 0) + result.append("::"); + else + result.append("::FFFF:"); + const UInt8* bytes = reinterpret_cast(&_addr); + result.append(NumberFormatter::format(bytes[12])); + result.append("."); + result.append(NumberFormatter::format(bytes[13])); + result.append("."); + result.append(NumberFormatter::format(bytes[14])); + result.append("."); + result.append(NumberFormatter::format(bytes[15])); + return result; + } + else + { + std::string result; + result.reserve(46); + bool zeroSequence = false; + int i = 0; + while (i < 8) + { + if (!zeroSequence && words[i] == 0) + { + int zi = i; + while (zi < 8 && words[zi] == 0) ++zi; + if (zi > i + 1) + { + i = zi; + result.append(":"); + zeroSequence = true; + } + } + if (i > 0) result.append(":"); + if (i < 8) result.append(NumberFormatter::formatHex(words[i++])); + } + return result; + } + } + + poco_socklen_t length() const + { + return sizeof(_addr); + } + + const void* addr() const + { + return &_addr; + } + + IPAddress::Family family() const + { + return IPAddress::IPv6; + } + + int af() const + { + return AF_INET6; + } + + bool isWildcard() const + { + const UInt16* words = reinterpret_cast(&_addr); + return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && + words[4] == 0 && words[5] == 0 && words[6] == 0 && words[7] == 0; + } + + bool isBroadcast() const + { + return false; + } + + bool isLoopback() const + { + const UInt16* words = reinterpret_cast(&_addr); + return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && + words[4] == 0 && words[5] == 0 && words[6] == 0 && words[7] == 1; + } + + bool isMulticast() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFE0) == 0xFF00; + } + + bool isLinkLocal() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFE0) == 0xFE80; + } + + bool isSiteLocal() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFE0) == 0xFEC0; + } + + bool isIPv4Compatible() const + { + const UInt16* words = reinterpret_cast(&_addr); + return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && words[5] == 0; + } + + bool isIPv4Mapped() const + { + const UInt16* words = reinterpret_cast(&_addr); + return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && words[5] == 0xFFFF; + } + + bool isWellKnownMC() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFF0) == 0xFF00; + } + + bool isNodeLocalMC() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFEF) == 0xFF01; + } + + bool isLinkLocalMC() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFEF) == 0xFF02; + } + + bool isSiteLocalMC() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFEF) == 0xFF05; + } + + bool isOrgLocalMC() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFEF) == 0xFF08; + } + + bool isGlobalMC() const + { + const UInt16* words = reinterpret_cast(&_addr); + return (words[0] & 0xFFEF) == 0xFF0F; + } + + static IPv6AddressImpl* parse(const std::string& addr) + { + if (addr.empty()) return 0; +#if defined(_WIN32) + struct addrinfo* pAI; + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_flags = AI_NUMERICHOST; + int rc = getaddrinfo(addr.c_str(), NULL, &hints, &pAI); + if (rc == 0) + { + IPv6AddressImpl* pResult = new IPv6AddressImpl(&reinterpret_cast(pAI->ai_addr)->sin6_addr); + freeaddrinfo(pAI); + return pResult; + } + else return 0; +#else + struct in6_addr ia; + if (inet_pton(AF_INET6, addr.c_str(), &ia) == 1) + return new IPv6AddressImpl(&ia); + else + return 0; +#endif + } + +private: + struct in6_addr _addr; +}; + + +#endif // POCO_HAVE_IPv6 + + +// +// IPAddress +// + + +IPAddress::IPAddress(): _pImpl(new IPv4AddressImpl) +{ +} + + +IPAddress::IPAddress(const IPAddress& addr): _pImpl(addr._pImpl) +{ + _pImpl->duplicate(); +} + + +IPAddress::IPAddress(Family family): _pImpl(0) +{ + if (family == IPv4) + _pImpl = new IPv4AddressImpl(); +#if defined(POCO_HAVE_IPv6) + else if (family == IPv6) + _pImpl = new IPv6AddressImpl(); +#endif + else Poco::InvalidArgumentException("Invalid or unsupported address family passed to IPAddress()"); +} + + +IPAddress::IPAddress(const std::string& addr) +{ + _pImpl = IPv4AddressImpl::parse(addr); +#if defined(POCO_HAVE_IPv6) + if (!_pImpl) + _pImpl = IPv6AddressImpl::parse(addr); +#endif + if (!_pImpl) throw InvalidAddressException(addr); +} + + +IPAddress::IPAddress(const std::string& addr, Family family): _pImpl(0) +{ + if (family == IPv4) + _pImpl = IPv4AddressImpl::parse(addr); +#if defined(POCO_HAVE_IPv6) + else if (family == IPv6) + _pImpl = IPv6AddressImpl::parse(addr); +#endif + else throw Poco::InvalidArgumentException("Invalid or unsupported address family passed to IPAddress()"); +} + + +IPAddress::IPAddress(const void* addr, poco_socklen_t length) +{ + if (length == sizeof(struct in_addr)) + _pImpl = new IPv4AddressImpl(addr); +#if defined(POCO_HAVE_IPv6) + else if (length == sizeof(struct in6_addr)) + _pImpl = new IPv6AddressImpl(addr); +#endif + else throw Poco::InvalidArgumentException("Invalid address length passed to IPAddress()"); +} + + +IPAddress::~IPAddress() +{ + _pImpl->release(); +} + + +IPAddress& IPAddress::operator = (const IPAddress& addr) +{ + if (&addr != this) + { + _pImpl->release(); + _pImpl = addr._pImpl; + _pImpl->duplicate(); + } + return *this; +} + + +void IPAddress::swap(IPAddress& address) +{ + std::swap(_pImpl, address._pImpl); +} + + +IPAddress::Family IPAddress::family() const +{ + return _pImpl->family(); +} + + +std::string IPAddress::toString() const +{ + return _pImpl->toString(); +} + + +bool IPAddress::isWildcard() const +{ + return _pImpl->isWildcard(); +} + +bool IPAddress::isBroadcast() const +{ + return _pImpl->isBroadcast(); +} + + +bool IPAddress::isLoopback() const +{ + return _pImpl->isLoopback(); +} + + +bool IPAddress::isMulticast() const +{ + return _pImpl->isMulticast(); +} + + +bool IPAddress::isUnicast() const +{ + return !isWildcard() && !isBroadcast() && !isMulticast(); +} + + +bool IPAddress::isLinkLocal() const +{ + return _pImpl->isLinkLocal(); +} + + +bool IPAddress::isSiteLocal() const +{ + return _pImpl->isSiteLocal(); +} + + +bool IPAddress::isIPv4Compatible() const +{ + return _pImpl->isIPv4Compatible(); +} + + +bool IPAddress::isIPv4Mapped() const +{ + return _pImpl->isIPv4Mapped(); +} + + +bool IPAddress::isWellKnownMC() const +{ + return _pImpl->isWellKnownMC(); +} + + +bool IPAddress::isNodeLocalMC() const +{ + return _pImpl->isNodeLocalMC(); +} + + +bool IPAddress::isLinkLocalMC() const +{ + return _pImpl->isLinkLocalMC(); +} + + +bool IPAddress::isSiteLocalMC() const +{ + return _pImpl->isSiteLocalMC(); +} + + +bool IPAddress::isOrgLocalMC() const +{ + return _pImpl->isOrgLocalMC(); +} + + +bool IPAddress::isGlobalMC() const +{ + return _pImpl->isGlobalMC(); +} + + +bool IPAddress::operator == (const IPAddress& a) const +{ + poco_socklen_t l1 = length(); + poco_socklen_t l2 = a.length(); + if (l1 == l2) + return memcmp(addr(), a.addr(), l1) == 0; + else + return false; +} + + +bool IPAddress::operator != (const IPAddress& a) const +{ + poco_socklen_t l1 = length(); + poco_socklen_t l2 = a.length(); + if (l1 == l2) + return memcmp(addr(), a.addr(), l1) != 0; + else + return true; +} + + +bool IPAddress::operator < (const IPAddress& a) const +{ + poco_socklen_t l1 = length(); + poco_socklen_t l2 = a.length(); + if (l1 == l2) + return memcmp(addr(), a.addr(), l1) < 0; + else + return l1 < l2; +} + + +bool IPAddress::operator <= (const IPAddress& a) const +{ + poco_socklen_t l1 = length(); + poco_socklen_t l2 = a.length(); + if (l1 == l2) + return memcmp(addr(), a.addr(), l1) <= 0; + else + return l1 < l2; +} + + +bool IPAddress::operator > (const IPAddress& a) const +{ + poco_socklen_t l1 = length(); + poco_socklen_t l2 = a.length(); + if (l1 == l2) + return memcmp(addr(), a.addr(), l1) > 0; + else + return l1 > l2; +} + + +bool IPAddress::operator >= (const IPAddress& a) const +{ + poco_socklen_t l1 = length(); + poco_socklen_t l2 = a.length(); + if (l1 == l2) + return memcmp(addr(), a.addr(), l1) >= 0; + else + return l1 > l2; +} + + +poco_socklen_t IPAddress::length() const +{ + return _pImpl->length(); +} + + +const void* IPAddress::addr() const +{ + return _pImpl->addr(); +} + + +int IPAddress::af() const +{ + return _pImpl->af(); +} + + +void IPAddress::init(IPAddressImpl* pImpl) +{ + _pImpl->release(); + _pImpl = pImpl; +} + + +IPAddress IPAddress::parse(const std::string& addr) +{ + return IPAddress(addr); +} + + +bool IPAddress::tryParse(const std::string& addr, IPAddress& result) +{ + IPAddressImpl* pImpl = IPv4AddressImpl::parse(addr); +#if defined(POCO_HAVE_IPv6) + if (!pImpl) pImpl = IPv6AddressImpl::parse(addr); +#endif + if (pImpl) + { + result.init(pImpl); + return true; + } + else return false; +} + + +} } // namespace Poco::Net diff --git a/Net/src/MailMessage.cpp b/Net/src/MailMessage.cpp index 0861821b7..0798bf29d 100644 --- a/Net/src/MailMessage.cpp +++ b/Net/src/MailMessage.cpp @@ -1,504 +1,504 @@ -// -// MailMessage.cpp -// -// $Id: //poco/1.2/Net/src/MailMessage.cpp#3 $ -// -// Library: Net -// Package: Mail -// Module: MailMessage -// -// 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/MailMessage.h" -#include "Poco/Net/MediaType.h" -#include "Poco/Net/MultipartReader.h" -#include "Poco/Net/MultipartWriter.h" -#include "Poco/Net/PartSource.h" -#include "Poco/Net/PartHandler.h" -#include "Poco/Net/QuotedPrintableEncoder.h" -#include "Poco/Net/QuotedPrintableDecoder.h" -#include "Poco/Base64Encoder.h" -#include "Poco/Base64Decoder.h" -#include "Poco/StreamCopier.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTimeParser.h" -#include "Poco/String.h" -#include -#include - - -using Poco::Base64Encoder; -using Poco::Base64Decoder; -using Poco::StreamCopier; -using Poco::DateTimeFormat; -using Poco::DateTimeFormatter; -using Poco::DateTimeParser; -using Poco::icompare; - - -namespace Poco { -namespace Net { - - -namespace -{ - class StringPartHandler: public PartHandler - { - public: - StringPartHandler(std::string& content): - _str(content) - { - } - - ~StringPartHandler() - { - } - - void handlePart(const MessageHeader& header, std::istream& stream) - { - int ch = stream.get(); - while (ch >= 0) - { - _str += (char) ch; - ch = stream.get(); - } - } - - private: - std::string& _str; - }; -} - - -const std::string MailMessage::HEADER_SUBJECT("Subject"); -const std::string MailMessage::HEADER_FROM("From"); -const std::string MailMessage::HEADER_TO("To"); -const std::string MailMessage::HEADER_CC("CC"); -const std::string MailMessage::HEADER_BCC("BCC"); -const std::string MailMessage::HEADER_DATE("Date"); -const std::string MailMessage::HEADER_CONTENT_TYPE("Content-Type"); -const std::string MailMessage::HEADER_CONTENT_TRANSFER_ENCODING("Content-Transfer-Encoding"); -const std::string MailMessage::HEADER_CONTENT_DISPOSITION("Content-Disposition"); -const std::string MailMessage::HEADER_MIME_VERSION("Mime-Version"); -const std::string MailMessage::EMPTY_HEADER; -const std::string MailMessage::TEXT_PLAIN("text/plain"); -const std::string MailMessage::CTE_7BIT("7bit"); -const std::string MailMessage::CTE_8BIT("8bit"); -const std::string MailMessage::CTE_QUOTED_PRINTABLE("quoted-printable"); -const std::string MailMessage::CTE_BASE64("base64"); - - -MailMessage::MailMessage() -{ - Poco::Timestamp now; - setDate(now); - setContentType("text/plain"); -} - - -MailMessage::~MailMessage() -{ - for (PartVec::iterator it = _parts.begin(); it != _parts.end(); ++it) - { - delete it->pSource; - } -} - - -void MailMessage::addRecipient(const MailRecipient& recipient) -{ - _recipients.push_back(recipient); -} - - -void MailMessage::setSender(const std::string& sender) -{ - set(HEADER_FROM, sender); -} - - -const std::string& MailMessage::getSender() const -{ - if (has(HEADER_FROM)) - return get(HEADER_FROM); - else - return EMPTY_HEADER; -} - - -void MailMessage::setSubject(const std::string& subject) -{ - set(HEADER_SUBJECT, subject); -} - - -const std::string& MailMessage::getSubject() const -{ - if (has(HEADER_SUBJECT)) - return get(HEADER_SUBJECT); - else - return EMPTY_HEADER; -} - - -void MailMessage::setContent(const std::string& content, ContentTransferEncoding encoding) -{ - _content = content; - _encoding = encoding; - set(HEADER_CONTENT_TRANSFER_ENCODING, contentTransferEncodingToString(encoding)); -} - - -void MailMessage::setContentType(const std::string& mediaType) -{ - set(HEADER_CONTENT_TYPE, mediaType); -} - - -void MailMessage::setContentType(const MediaType& mediaType) -{ - setContentType(mediaType.toString()); -} - - -const std::string& MailMessage::getContentType() const -{ - if (has(HEADER_CONTENT_TYPE)) - return get(HEADER_CONTENT_TYPE); - else - return TEXT_PLAIN; -} - - -void MailMessage::setDate(const Poco::Timestamp& dateTime) -{ - set(HEADER_DATE, DateTimeFormatter::format(dateTime, DateTimeFormat::RFC1123_FORMAT)); -} - - -Poco::Timestamp MailMessage::getDate() const -{ - const std::string& dateTime = get(HEADER_DATE); - int tzd; - return DateTimeParser::parse(dateTime, tzd).timestamp(); -} - - -bool MailMessage::isMultipart() const -{ - MediaType mediaType = getContentType(); - return mediaType.matches("multipart"); -} - - -void MailMessage::addPart(const std::string& name, PartSource* pSource, ContentDisposition disposition, ContentTransferEncoding encoding) -{ - poco_check_ptr (pSource); - - makeMultipart(); - Part part; - part.name = name; - part.pSource = pSource; - part.disposition = disposition; - part.encoding = encoding; - _parts.push_back(part); -} - - -void MailMessage::addContent(PartSource* pSource, ContentTransferEncoding encoding) -{ - addPart("", pSource, CONTENT_INLINE, encoding); -} - - -void MailMessage::addAttachment(const std::string& name, PartSource* pSource, ContentTransferEncoding encoding) -{ - addPart(name, pSource, CONTENT_ATTACHMENT, encoding); -} - - -void MailMessage::read(std::istream& istr, PartHandler& handler) -{ - readHeader(istr); - if (isMultipart()) - { - readMultipart(istr, handler); - } - else - { - StringPartHandler handler(_content); - readPart(istr, *this, handler); - } -} - - -void MailMessage::read(std::istream& istr) -{ - readHeader(istr); - StringPartHandler handler(_content); - readPart(istr, *this, handler); -} - - -void MailMessage::write(std::ostream& ostr) const -{ - MessageHeader header(*this); - setRecipientHeaders(header); - if (isMultipart()) - { - writeMultipart(header, ostr); - } - else - { - writeHeader(header, ostr); - std::istringstream istr(_content); - writeEncoded(istr, ostr, _encoding); - } -} - - -void MailMessage::makeMultipart() -{ - if (!isMultipart()) - { - MediaType mediaType("multipart", "mixed"); - setContentType(mediaType); - } -} - - -void MailMessage::writeHeader(const MessageHeader& header, std::ostream& ostr) const -{ - header.write(ostr); - ostr << "\r\n"; -} - - -void MailMessage::writeMultipart(MessageHeader& header, std::ostream& ostr) const -{ - std::string boundary(MultipartWriter::createBoundary()); - MediaType mediaType(getContentType()); - mediaType.setParameter("boundary", boundary); - header.set(HEADER_CONTENT_TYPE, mediaType.toString()); - header.set(HEADER_MIME_VERSION, "1.0"); - writeHeader(header, ostr); - - MultipartWriter writer(ostr, boundary); - for (PartVec::const_iterator it = _parts.begin(); it != _parts.end(); ++it) - { - writePart(writer, *it); - } - writer.close(); -} - - -void MailMessage::writePart(MultipartWriter& writer, const Part& part) const -{ - MessageHeader partHeader; - MediaType mediaType(part.pSource->mediaType()); - if (!part.name.empty()) - mediaType.setParameter("name", part.name); - partHeader.set(HEADER_CONTENT_TYPE, mediaType.toString()); - partHeader.set(HEADER_CONTENT_TRANSFER_ENCODING, contentTransferEncodingToString(part.encoding)); - std::string disposition; - if (part.disposition == CONTENT_ATTACHMENT) - { - disposition = "attachment"; - const std::string& filename = part.pSource->filename(); - if (!filename.empty()) - { - disposition.append("; filename="); - quote(filename, disposition); - } - } - else disposition = "inline"; - partHeader.set(HEADER_CONTENT_DISPOSITION, disposition); - writer.nextPart(partHeader); - writeEncoded(part.pSource->stream(), writer.stream(), part.encoding); -} - - -void MailMessage::writeEncoded(std::istream& istr, std::ostream& ostr, ContentTransferEncoding encoding) const -{ - switch (encoding) - { - case ENCODING_7BIT: - case ENCODING_8BIT: - StreamCopier::copyStream(istr, ostr); - break; - case ENCODING_QUOTED_PRINTABLE: - { - QuotedPrintableEncoder encoder(ostr); - StreamCopier::copyStream(istr, encoder); - } - break; - case ENCODING_BASE64: - { - Base64Encoder encoder(ostr); - StreamCopier::copyStream(istr, encoder); - } - break; - } -} - - -void MailMessage::readHeader(std::istream& istr) -{ - clear(); - MessageHeader::read(istr); - istr.get(); // \r - istr.get(); // \n -} - - -void MailMessage::readMultipart(std::istream& istr, PartHandler& handler) -{ - MediaType contentType(getContentType()); - std::string boundary = contentType.getParameter("boundary"); - MultipartReader reader(istr, boundary); - while (reader.hasNextPart()) - { - MessageHeader partHeader; - reader.nextPart(partHeader); - readPart(reader.stream(), partHeader, handler); - } -} - - -void MailMessage::readPart(std::istream& istr, const MessageHeader& header, PartHandler& handler) -{ - std::string encoding; - if (header.has(HEADER_CONTENT_TRANSFER_ENCODING)) - { - encoding = header.get(HEADER_CONTENT_TRANSFER_ENCODING); - // get rid of a parameter if one is set - std::string::size_type pos = encoding.find(';'); - if (pos != std::string::npos) - encoding.resize(pos); - } - if (icompare(encoding, CTE_QUOTED_PRINTABLE) == 0) - { - QuotedPrintableDecoder decoder(istr); - handlePart(decoder, header, handler); - } - else if (icompare(encoding, CTE_BASE64) == 0) - { - Base64Decoder decoder(istr); - handlePart(decoder, header, handler); - } - else - { - handlePart(istr, header, handler); - } -} - - -void MailMessage::handlePart(std::istream& istr, const MessageHeader& header, PartHandler& handler) -{ - handler.handlePart(header, istr); - // Read remaining characters from stream in case - // the handler failed to read the complete stream. - while (istr.good()) istr.get(); -} - - -void MailMessage::setRecipientHeaders(MessageHeader& headers) const -{ - std::string to; - std::string cc; - std::string bcc; - - for (Recipients::const_iterator it = _recipients.begin(); it != _recipients.end(); ++it) - { - switch (it->getType()) - { - case MailRecipient::PRIMARY_RECIPIENT: - appendRecipient(*it, to); - break; - case MailRecipient::CC_RECIPIENT: - appendRecipient(*it, cc); - break; - case MailRecipient::BCC_RECIPIENT: - break; - } - } - if (!to.empty()) headers.set(HEADER_TO, to); - if (!cc.empty()) headers.set(HEADER_CC, cc); -} - - -const std::string& MailMessage::contentTransferEncodingToString(ContentTransferEncoding encoding) -{ - switch (encoding) - { - case ENCODING_7BIT: - return CTE_8BIT; - case ENCODING_8BIT: - return CTE_8BIT; - case ENCODING_QUOTED_PRINTABLE: - return CTE_QUOTED_PRINTABLE; - case ENCODING_BASE64: - return CTE_BASE64; - default: - poco_bugcheck(); - } - return CTE_7BIT; -} - - -int MailMessage::lineLength(const std::string& str) -{ - int n = 0; - std::string::const_reverse_iterator it = str.rbegin(); - std::string::const_reverse_iterator end = str.rend(); - while (it != end && *it != '\n') { ++n; ++it; } - return n; -} - - -void MailMessage::appendRecipient(const MailRecipient& recipient, std::string& str) -{ - if (!str.empty()) str.append(", "); - const std::string& realName = recipient.getRealName(); - const std::string& address = recipient.getAddress(); - std::string rec; - if (!realName.empty()) - { - quote(realName, rec, true); - rec.append(" "); - } - rec.append("<"); - rec.append(address); - rec.append(">"); - if (lineLength(str) + rec.length() > 70) str.append("\r\n\t"); - str.append(rec); -} - - -} } // namespace Poco::Net +// +// MailMessage.cpp +// +// $Id: //poco/1.2/Net/src/MailMessage.cpp#3 $ +// +// Library: Net +// Package: Mail +// Module: MailMessage +// +// 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/MailMessage.h" +#include "Poco/Net/MediaType.h" +#include "Poco/Net/MultipartReader.h" +#include "Poco/Net/MultipartWriter.h" +#include "Poco/Net/PartSource.h" +#include "Poco/Net/PartHandler.h" +#include "Poco/Net/QuotedPrintableEncoder.h" +#include "Poco/Net/QuotedPrintableDecoder.h" +#include "Poco/Base64Encoder.h" +#include "Poco/Base64Decoder.h" +#include "Poco/StreamCopier.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeParser.h" +#include "Poco/String.h" +#include +#include + + +using Poco::Base64Encoder; +using Poco::Base64Decoder; +using Poco::StreamCopier; +using Poco::DateTimeFormat; +using Poco::DateTimeFormatter; +using Poco::DateTimeParser; +using Poco::icompare; + + +namespace Poco { +namespace Net { + + +namespace +{ + class StringPartHandler: public PartHandler + { + public: + StringPartHandler(std::string& content): + _str(content) + { + } + + ~StringPartHandler() + { + } + + void handlePart(const MessageHeader& header, std::istream& stream) + { + int ch = stream.get(); + while (ch >= 0) + { + _str += (char) ch; + ch = stream.get(); + } + } + + private: + std::string& _str; + }; +} + + +const std::string MailMessage::HEADER_SUBJECT("Subject"); +const std::string MailMessage::HEADER_FROM("From"); +const std::string MailMessage::HEADER_TO("To"); +const std::string MailMessage::HEADER_CC("CC"); +const std::string MailMessage::HEADER_BCC("BCC"); +const std::string MailMessage::HEADER_DATE("Date"); +const std::string MailMessage::HEADER_CONTENT_TYPE("Content-Type"); +const std::string MailMessage::HEADER_CONTENT_TRANSFER_ENCODING("Content-Transfer-Encoding"); +const std::string MailMessage::HEADER_CONTENT_DISPOSITION("Content-Disposition"); +const std::string MailMessage::HEADER_MIME_VERSION("Mime-Version"); +const std::string MailMessage::EMPTY_HEADER; +const std::string MailMessage::TEXT_PLAIN("text/plain"); +const std::string MailMessage::CTE_7BIT("7bit"); +const std::string MailMessage::CTE_8BIT("8bit"); +const std::string MailMessage::CTE_QUOTED_PRINTABLE("quoted-printable"); +const std::string MailMessage::CTE_BASE64("base64"); + + +MailMessage::MailMessage() +{ + Poco::Timestamp now; + setDate(now); + setContentType("text/plain"); +} + + +MailMessage::~MailMessage() +{ + for (PartVec::iterator it = _parts.begin(); it != _parts.end(); ++it) + { + delete it->pSource; + } +} + + +void MailMessage::addRecipient(const MailRecipient& recipient) +{ + _recipients.push_back(recipient); +} + + +void MailMessage::setSender(const std::string& sender) +{ + set(HEADER_FROM, sender); +} + + +const std::string& MailMessage::getSender() const +{ + if (has(HEADER_FROM)) + return get(HEADER_FROM); + else + return EMPTY_HEADER; +} + + +void MailMessage::setSubject(const std::string& subject) +{ + set(HEADER_SUBJECT, subject); +} + + +const std::string& MailMessage::getSubject() const +{ + if (has(HEADER_SUBJECT)) + return get(HEADER_SUBJECT); + else + return EMPTY_HEADER; +} + + +void MailMessage::setContent(const std::string& content, ContentTransferEncoding encoding) +{ + _content = content; + _encoding = encoding; + set(HEADER_CONTENT_TRANSFER_ENCODING, contentTransferEncodingToString(encoding)); +} + + +void MailMessage::setContentType(const std::string& mediaType) +{ + set(HEADER_CONTENT_TYPE, mediaType); +} + + +void MailMessage::setContentType(const MediaType& mediaType) +{ + setContentType(mediaType.toString()); +} + + +const std::string& MailMessage::getContentType() const +{ + if (has(HEADER_CONTENT_TYPE)) + return get(HEADER_CONTENT_TYPE); + else + return TEXT_PLAIN; +} + + +void MailMessage::setDate(const Poco::Timestamp& dateTime) +{ + set(HEADER_DATE, DateTimeFormatter::format(dateTime, DateTimeFormat::RFC1123_FORMAT)); +} + + +Poco::Timestamp MailMessage::getDate() const +{ + const std::string& dateTime = get(HEADER_DATE); + int tzd; + return DateTimeParser::parse(dateTime, tzd).timestamp(); +} + + +bool MailMessage::isMultipart() const +{ + MediaType mediaType = getContentType(); + return mediaType.matches("multipart"); +} + + +void MailMessage::addPart(const std::string& name, PartSource* pSource, ContentDisposition disposition, ContentTransferEncoding encoding) +{ + poco_check_ptr (pSource); + + makeMultipart(); + Part part; + part.name = name; + part.pSource = pSource; + part.disposition = disposition; + part.encoding = encoding; + _parts.push_back(part); +} + + +void MailMessage::addContent(PartSource* pSource, ContentTransferEncoding encoding) +{ + addPart("", pSource, CONTENT_INLINE, encoding); +} + + +void MailMessage::addAttachment(const std::string& name, PartSource* pSource, ContentTransferEncoding encoding) +{ + addPart(name, pSource, CONTENT_ATTACHMENT, encoding); +} + + +void MailMessage::read(std::istream& istr, PartHandler& handler) +{ + readHeader(istr); + if (isMultipart()) + { + readMultipart(istr, handler); + } + else + { + StringPartHandler handler(_content); + readPart(istr, *this, handler); + } +} + + +void MailMessage::read(std::istream& istr) +{ + readHeader(istr); + StringPartHandler handler(_content); + readPart(istr, *this, handler); +} + + +void MailMessage::write(std::ostream& ostr) const +{ + MessageHeader header(*this); + setRecipientHeaders(header); + if (isMultipart()) + { + writeMultipart(header, ostr); + } + else + { + writeHeader(header, ostr); + std::istringstream istr(_content); + writeEncoded(istr, ostr, _encoding); + } +} + + +void MailMessage::makeMultipart() +{ + if (!isMultipart()) + { + MediaType mediaType("multipart", "mixed"); + setContentType(mediaType); + } +} + + +void MailMessage::writeHeader(const MessageHeader& header, std::ostream& ostr) const +{ + header.write(ostr); + ostr << "\r\n"; +} + + +void MailMessage::writeMultipart(MessageHeader& header, std::ostream& ostr) const +{ + std::string boundary(MultipartWriter::createBoundary()); + MediaType mediaType(getContentType()); + mediaType.setParameter("boundary", boundary); + header.set(HEADER_CONTENT_TYPE, mediaType.toString()); + header.set(HEADER_MIME_VERSION, "1.0"); + writeHeader(header, ostr); + + MultipartWriter writer(ostr, boundary); + for (PartVec::const_iterator it = _parts.begin(); it != _parts.end(); ++it) + { + writePart(writer, *it); + } + writer.close(); +} + + +void MailMessage::writePart(MultipartWriter& writer, const Part& part) const +{ + MessageHeader partHeader; + MediaType mediaType(part.pSource->mediaType()); + if (!part.name.empty()) + mediaType.setParameter("name", part.name); + partHeader.set(HEADER_CONTENT_TYPE, mediaType.toString()); + partHeader.set(HEADER_CONTENT_TRANSFER_ENCODING, contentTransferEncodingToString(part.encoding)); + std::string disposition; + if (part.disposition == CONTENT_ATTACHMENT) + { + disposition = "attachment"; + const std::string& filename = part.pSource->filename(); + if (!filename.empty()) + { + disposition.append("; filename="); + quote(filename, disposition); + } + } + else disposition = "inline"; + partHeader.set(HEADER_CONTENT_DISPOSITION, disposition); + writer.nextPart(partHeader); + writeEncoded(part.pSource->stream(), writer.stream(), part.encoding); +} + + +void MailMessage::writeEncoded(std::istream& istr, std::ostream& ostr, ContentTransferEncoding encoding) const +{ + switch (encoding) + { + case ENCODING_7BIT: + case ENCODING_8BIT: + StreamCopier::copyStream(istr, ostr); + break; + case ENCODING_QUOTED_PRINTABLE: + { + QuotedPrintableEncoder encoder(ostr); + StreamCopier::copyStream(istr, encoder); + } + break; + case ENCODING_BASE64: + { + Base64Encoder encoder(ostr); + StreamCopier::copyStream(istr, encoder); + } + break; + } +} + + +void MailMessage::readHeader(std::istream& istr) +{ + clear(); + MessageHeader::read(istr); + istr.get(); // \r + istr.get(); // \n +} + + +void MailMessage::readMultipart(std::istream& istr, PartHandler& handler) +{ + MediaType contentType(getContentType()); + std::string boundary = contentType.getParameter("boundary"); + MultipartReader reader(istr, boundary); + while (reader.hasNextPart()) + { + MessageHeader partHeader; + reader.nextPart(partHeader); + readPart(reader.stream(), partHeader, handler); + } +} + + +void MailMessage::readPart(std::istream& istr, const MessageHeader& header, PartHandler& handler) +{ + std::string encoding; + if (header.has(HEADER_CONTENT_TRANSFER_ENCODING)) + { + encoding = header.get(HEADER_CONTENT_TRANSFER_ENCODING); + // get rid of a parameter if one is set + std::string::size_type pos = encoding.find(';'); + if (pos != std::string::npos) + encoding.resize(pos); + } + if (icompare(encoding, CTE_QUOTED_PRINTABLE) == 0) + { + QuotedPrintableDecoder decoder(istr); + handlePart(decoder, header, handler); + } + else if (icompare(encoding, CTE_BASE64) == 0) + { + Base64Decoder decoder(istr); + handlePart(decoder, header, handler); + } + else + { + handlePart(istr, header, handler); + } +} + + +void MailMessage::handlePart(std::istream& istr, const MessageHeader& header, PartHandler& handler) +{ + handler.handlePart(header, istr); + // Read remaining characters from stream in case + // the handler failed to read the complete stream. + while (istr.good()) istr.get(); +} + + +void MailMessage::setRecipientHeaders(MessageHeader& headers) const +{ + std::string to; + std::string cc; + std::string bcc; + + for (Recipients::const_iterator it = _recipients.begin(); it != _recipients.end(); ++it) + { + switch (it->getType()) + { + case MailRecipient::PRIMARY_RECIPIENT: + appendRecipient(*it, to); + break; + case MailRecipient::CC_RECIPIENT: + appendRecipient(*it, cc); + break; + case MailRecipient::BCC_RECIPIENT: + break; + } + } + if (!to.empty()) headers.set(HEADER_TO, to); + if (!cc.empty()) headers.set(HEADER_CC, cc); +} + + +const std::string& MailMessage::contentTransferEncodingToString(ContentTransferEncoding encoding) +{ + switch (encoding) + { + case ENCODING_7BIT: + return CTE_8BIT; + case ENCODING_8BIT: + return CTE_8BIT; + case ENCODING_QUOTED_PRINTABLE: + return CTE_QUOTED_PRINTABLE; + case ENCODING_BASE64: + return CTE_BASE64; + default: + poco_bugcheck(); + } + return CTE_7BIT; +} + + +int MailMessage::lineLength(const std::string& str) +{ + int n = 0; + std::string::const_reverse_iterator it = str.rbegin(); + std::string::const_reverse_iterator end = str.rend(); + while (it != end && *it != '\n') { ++n; ++it; } + return n; +} + + +void MailMessage::appendRecipient(const MailRecipient& recipient, std::string& str) +{ + if (!str.empty()) str.append(", "); + const std::string& realName = recipient.getRealName(); + const std::string& address = recipient.getAddress(); + std::string rec; + if (!realName.empty()) + { + quote(realName, rec, true); + rec.append(" "); + } + rec.append("<"); + rec.append(address); + rec.append(">"); + if (lineLength(str) + rec.length() > 70) str.append("\r\n\t"); + str.append(rec); +} + + +} } // namespace Poco::Net diff --git a/Net/src/MailRecipient.cpp b/Net/src/MailRecipient.cpp index 8f9dcac21..603f67c8c 100644 --- a/Net/src/MailRecipient.cpp +++ b/Net/src/MailRecipient.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/MailStream.cpp b/Net/src/MailStream.cpp index 4fce868d5..91b22e270 100644 --- a/Net/src/MailStream.cpp +++ b/Net/src/MailStream.cpp @@ -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::eof(); - if (!_buffer.empty()) - { - c = _buffer[0]; - _buffer.erase(0, 1); - } - else - { - c = readOne(); - while (c != std::char_traits::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::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::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::eof(); + if (!_buffer.empty()) + { + c = _buffer[0]; + _buffer.erase(0, 1); + } + else + { + c = readOne(); + while (c != std::char_traits::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::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::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 diff --git a/Net/src/MediaType.cpp b/Net/src/MediaType.cpp index 10e4d6e32..316f4c17a 100644 --- a/Net/src/MediaType.cpp +++ b/Net/src/MediaType.cpp @@ -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 -#include - - -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 +#include + + +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 diff --git a/Net/src/MessageHeader.cpp b/Net/src/MessageHeader.cpp index e3a210f4c..5a79eb670 100644 --- a/Net/src/MessageHeader.cpp +++ b/Net/src/MessageHeader.cpp @@ -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 - - -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::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& 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 + + +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::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& 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 diff --git a/Net/src/MulticastSocket.cpp b/Net/src/MulticastSocket.cpp index 6dfbc84cb..30919a03c 100644 --- a/Net/src/MulticastSocket.cpp +++ b/Net/src/MulticastSocket.cpp @@ -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 - - -#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 + + +#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 diff --git a/Net/src/MultipartReader.cpp b/Net/src/MultipartReader.cpp index cf987a672..30f440fa9 100644 --- a/Net/src/MultipartReader.cpp +++ b/Net/src/MultipartReader.cpp @@ -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 - - -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::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::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::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 + + +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::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::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::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 diff --git a/Net/src/MultipartWriter.cpp b/Net/src/MultipartWriter.cpp index e73ed6393..c527aea7a 100644 --- a/Net/src/MultipartWriter.cpp +++ b/Net/src/MultipartWriter.cpp @@ -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 diff --git a/Net/src/NameValueCollection.cpp b/Net/src/NameValueCollection.cpp index 1c6826e8f..e7e296d43 100644 --- a/Net/src/NameValueCollection.cpp +++ b/Net/src/NameValueCollection.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/NetException.cpp b/Net/src/NetException.cpp index bb3a11243..00176e18d 100644 --- a/Net/src/NetException.cpp +++ b/Net/src/NetException.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/NetworkInterface.cpp b/Net/src/NetworkInterface.cpp index 074fa7b76..3ea78897a 100644 --- a/Net/src/NetworkInterface.cpp +++ b/Net/src/NetworkInterface.cpp @@ -1,504 +1,504 @@ -// -// NetworkInterface.cpp -// -// $Id: //poco/1.2/Net/src/NetworkInterface.cpp#1 $ -// -// Library: Net -// Package: Sockets -// Module: NetworkInterface -// -// 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/NetworkInterface.h" -#include "Poco/Net/DatagramSocket.h" -#include "Poco/Net/NetException.h" -#include "Poco/NumberFormatter.h" -#include - - -using Poco::NumberFormatter; -using Poco::FastMutex; - - -namespace Poco { -namespace Net { - - -FastMutex NetworkInterface::_mutex; - - -NetworkInterface::NetworkInterface(): - _index(0) -{ -} - - -NetworkInterface::NetworkInterface(const std::string& name, const IPAddress& address, int index): - _name(name), - _address(address), - _index(index) -{ -} - - -NetworkInterface::NetworkInterface(const NetworkInterface& interface): - _name(interface._name), - _address(interface._address), - _index(interface._index) -{ -} - - -NetworkInterface::~NetworkInterface() -{ -} - - -NetworkInterface& NetworkInterface::operator = (const NetworkInterface& interface) -{ - if (&interface != this) - { - _name = interface._name; - _address = interface._address; - _index = interface._index; - } - return *this; -} - - -NetworkInterface NetworkInterface::forName(const std::string& name, bool requireIPv6) -{ -#if defined(_WIN32) - NetworkInterfaceList ifs = list(); - for (NetworkInterfaceList::const_iterator it = ifs.begin(); it != ifs.end(); ++it) - { - if (it->name() == name && it->supportsIPv6() == requireIPv6) - return *it; - } - throw InterfaceNotFoundException(name); -#else - FastMutex::ScopedLock lock(_mutex); - - struct ifreq ifr; - strncpy(ifr.ifr_name, name.c_str(), IFNAMSIZ); - DatagramSocket ds(requireIPv6 ? IPAddress::IPv6 : IPAddress::IPv4); - ds.impl()->ioctl(SIOCGIFADDR, &ifr); - IPAddress addr; -#if defined(POCO_HAVE_IPv6) - if (ifr.ifr_addr.sa_family == AF_INET) - addr = IPAddress(&reinterpret_cast(&ifr.ifr_addr)->sin_addr, sizeof(struct in_addr)); - else if (ifr.ifr_addr.sa_family == AF_INET6) - addr = IPAddress(&reinterpret_cast(&ifr.ifr_addr)->sin6_addr, sizeof(struct in6_addr)); - else throw InterfaceNotFoundException(addr.toString(), "interface has no IP address"); - int index = if_nametoindex(name.c_str()); -#else - if (ifr.ifr_addr.sa_family == AF_INET) - addr = IPAddress(&reinterpret_cast(&ifr.ifr_addr)->sin_addr, sizeof(struct in_addr)); - else throw InterfaceNotFoundException(addr.toString(), "interface has no IP address"); - int index = 0; -#endif - return NetworkInterface(name, addr, index); -#endif -} - - -NetworkInterface NetworkInterface::forAddress(const IPAddress& addr) -{ - NetworkInterfaceList ifs = list(); - for (NetworkInterfaceList::const_iterator it = ifs.begin(); it != ifs.end(); ++it) - { - if (it->address() == addr) - return *it; - } - throw InterfaceNotFoundException(addr.toString()); -} - - -NetworkInterface NetworkInterface::forIndex(int i) -{ - if (i != 0) - { - NetworkInterfaceList ifs = list(); - for (NetworkInterfaceList::const_iterator it = ifs.begin(); it != ifs.end(); ++it) - { - if (it->index() == i) - return *it; - } - throw InterfaceNotFoundException("#" + NumberFormatter::format(i)); - } - else return NetworkInterface(); -} - - -} } // namespace Poco::Net - - -// -// platform-specific code below -// - - -#if defined(POCO_OS_FAMILY_WINDOWS) -// -// Windows -// -#include - - -namespace Poco { -namespace Net { - - -NetworkInterface::NetworkInterfaceList NetworkInterface::list() -{ - FastMutex::ScopedLock lock(_mutex); - NetworkInterfaceList result; - -#if defined(POCO_HAVE_IPv6) - // On Windows XP/Server 2003 and later we use GetAdaptersAddresses. - PIP_ADAPTER_ADDRESSES pAdapterAddresses; - PIP_ADAPTER_ADDRESSES pAdapter = 0; - ULONG len = sizeof(IP_ADAPTER_ADDRESSES); - pAdapterAddresses = reinterpret_cast(new char[len]); - // Make an initial call to GetAdaptersAddresses to get - // the necessary size into len - DWORD rc = GetAdaptersAddresses(AF_UNSPEC, 0, 0, pAdapterAddresses, &len); - if (rc == ERROR_BUFFER_OVERFLOW) - { - delete [] reinterpret_cast(pAdapterAddresses); - pAdapterAddresses = reinterpret_cast(new char[len]); - } - else if (rc != ERROR_SUCCESS) - { - throw NetException("cannot get network adapter list"); - } - try - { - if (GetAdaptersAddresses(AF_UNSPEC, 0, 0, pAdapterAddresses, &len) == NO_ERROR) - { - pAdapter = pAdapterAddresses; - while (pAdapter) - { - if (pAdapter->FirstUnicastAddress) - { - IPAddress addr(pAdapter->FirstUnicastAddress->Address.lpSockaddr, pAdapter->FirstUnicastAddress->Address.iSockaddrLength); - result.push_back(NetworkInterface(std::string(pAdapter->AdapterName), addr, pAdapter->Ipv6IfIndex)); - pAdapter = pAdapter->Next; - } - } - } - else throw NetException("cannot get network adapter list"); - } - catch (Poco::Exception&) - { - delete [] reinterpret_cast(pAdapterAddresses); - throw; - } - delete [] reinterpret_cast(pAdapterAddresses); -#else - // Add loopback interface (not returned by GetAdaptersInfo) - result.push_back(NetworkInterface("Loopback", IPAddress("127.0.0.1"), -1)); - // On Windows 2000 we use GetAdaptersInfo. - PIP_ADAPTER_INFO pAdapterInfo; - PIP_ADAPTER_INFO pAdapter = 0; - ULONG len = sizeof(IP_ADAPTER_INFO); - pAdapterInfo = reinterpret_cast(new char[len]); - // Make an initial call to GetAdaptersInfo to get - // the necessary size into len - DWORD rc = GetAdaptersInfo(pAdapterInfo, &len); - if (rc == ERROR_BUFFER_OVERFLOW) - { - delete [] reinterpret_cast(pAdapterInfo); - pAdapterInfo = reinterpret_cast(new char[len]); - } - else if (rc != ERROR_SUCCESS) - { - throw NetException("cannot get network adapter list"); - } - try - { - if (GetAdaptersInfo(pAdapterInfo, &len) == NO_ERROR) - { - pAdapter = pAdapterInfo; - while (pAdapter) - { - IPAddress addr(std::string(pAdapter->IpAddressList.IpAddress.String)); - result.push_back(NetworkInterface(std::string(pAdapter->AdapterName), addr)); - pAdapter = pAdapter->Next; - } - } - else throw NetException("cannot get network adapter list"); - } - catch (Poco::Exception&) - { - delete [] reinterpret_cast(pAdapterInfo); - throw; - } - delete [] reinterpret_cast(pAdapterInfo); -#endif - - return result; -} - - -} } // namespace Poco::Net - - -#elif defined(POCO_OS_FAMILY_BSD) || POCO_OS == POCO_OS_QNX -// -// BSD variants -// -#include -#include -#include -#include - - -namespace Poco { -namespace Net { - - -NetworkInterface::NetworkInterfaceList NetworkInterface::list() -{ - FastMutex::ScopedLock lock(_mutex); - NetworkInterfaceList result; - - struct ifaddrs* ifaphead; - int rc = getifaddrs(&ifaphead); - if (rc) throw NetException("cannot get network adapter list"); - - for (struct ifaddrs* ifap = ifaphead; ifap; ifap = ifap->ifa_next) - { - if (ifap->ifa_addr) - { - if (ifap->ifa_addr->sa_family == AF_INET) - { - IPAddress addr(&reinterpret_cast(ifap->ifa_addr)->sin_addr, sizeof(struct in_addr)); - result.push_back(NetworkInterface(std::string(ifap->ifa_name), addr)); - } -#if defined(POCO_HAVE_IPv6) - else if (ifap->ifa_addr->sa_family == AF_INET6) - { - IPAddress addr(&reinterpret_cast(ifap->ifa_addr)->sin6_addr, sizeof(struct in6_addr)); - result.push_back(NetworkInterface(std::string(ifap->ifa_name), addr, if_nametoindex(ifap->ifa_name))); - } -#endif - } - } - freeifaddrs(ifaphead); - return result; -} - - -} } // namespace Poco::Net - - -#elif POCO_OS == POCO_OS_LINUX -// -// Linux -// - - -namespace Poco { -namespace Net { - - -NetworkInterface::NetworkInterfaceList NetworkInterface::list() -{ - FastMutex::ScopedLock lock(_mutex); - NetworkInterfaceList result; - DatagramSocket socket; - // the following code is loosely based - // on W. Richard Stevens, UNIX Network Programming, pp 434ff. - int lastlen = 0; - int len = 100*sizeof(struct ifreq); - char* buf = 0; - try - { - struct ifconf ifc; - for (;;) - { - buf = new char[len]; - ifc.ifc_len = len; - ifc.ifc_buf = buf; - if (::ioctl(socket.impl()->sockfd(), SIOCGIFCONF, &ifc) < 0) - { - if (errno != EINVAL || lastlen != 0) - throw NetException("cannot get network adapter list"); - } - else - { - if (ifc.ifc_len == lastlen) - break; - lastlen = ifc.ifc_len; - } - len += 10*sizeof(struct ifreq); - delete [] buf; - } - for (const char* ptr = buf; ptr < buf + ifc.ifc_len;) - { - const struct ifreq* ifr = reinterpret_cast(ptr); - IPAddress addr; - bool haveAddr = false; - switch (ifr->ifr_addr.sa_family) - { -#if defined(POCO_HAVE_IPv6) - case AF_INET6: - addr = IPAddress(&reinterpret_cast(&ifr->ifr_addr)->sin6_addr, sizeof(struct in6_addr)); - haveAddr = true; - break; -#endif - case AF_INET: - addr = IPAddress(&reinterpret_cast(&ifr->ifr_addr)->sin_addr, sizeof(struct in_addr)); - haveAddr = true; - break; - default: - break; - } - if (haveAddr) - { -#if defined(POCO_HAVE_IPv6) - int index = if_nametoindex(ifr->ifr_name); -#else - int index = -1; -#endif - result.push_back(NetworkInterface(std::string(ifr->ifr_name), addr, index)); - } - ptr += sizeof(struct ifreq); - } - } - catch (...) - { - delete [] buf; - throw; - } - delete [] buf; - return result; -} - - -} } // namespace Poco::Net - - -#else -// -// Non-BSD Unix variants -// - - -namespace Poco { -namespace Net { - - -NetworkInterface::NetworkInterfaceList NetworkInterface::list() -{ - FastMutex::ScopedLock lock(_mutex); - NetworkInterfaceList result; - DatagramSocket socket; - // the following code is loosely based - // on W. Richard Stevens, UNIX Network Programming, pp 434ff. - int lastlen = 0; - int len = 100*sizeof(struct ifreq); - char* buf = 0; - try - { - struct ifconf ifc; - for (;;) - { - buf = new char[len]; - ifc.ifc_len = len; - ifc.ifc_buf = buf; - if (::ioctl(socket.impl()->sockfd(), SIOCGIFCONF, &ifc) < 0) - { - if (errno != EINVAL || lastlen != 0) - throw NetException("cannot get network adapter list"); - } - else - { - if (ifc.ifc_len == lastlen) - break; - lastlen = ifc.ifc_len; - } - len += 10*sizeof(struct ifreq); - delete [] buf; - } - for (const char* ptr = buf; ptr < buf + ifc.ifc_len;) - { - const struct ifreq* ifr = reinterpret_cast(ptr); -#if defined(POCO_HAVE_SALEN) - len = ifr->ifr_addr.sa_len; - if (sizeof(struct sockaddr) > len) len = sizeof(struct sockaddr); -#else - len = sizeof(struct sockaddr); -#endif - IPAddress addr; - bool haveAddr = false; - switch (ifr->ifr_addr.sa_family) - { -#if defined(POCO_HAVE_IPv6) - case AF_INET6: - if (len < sizeof(struct sockaddr_in6)) len = sizeof(struct sockaddr_in6); - addr = IPAddress(&reinterpret_cast(&ifr->ifr_addr)->sin6_addr, sizeof(struct in6_addr)); - haveAddr = true; - break; -#endif - case AF_INET: - if (len < sizeof(struct sockaddr_in)) len = sizeof(struct sockaddr_in); - addr = IPAddress(&reinterpret_cast(&ifr->ifr_addr)->sin_addr, sizeof(struct in_addr)); - haveAddr = true; - break; - default: - break; - } - if (haveAddr) - { -#if defined(POCO_HAVE_IPv6) - int index = if_nametoindex(ifr->ifr_name); -#else - int index = -1; -#endif - result.push_back(NetworkInterface(std::string(ifr->ifr_name), addr, index)); - } - len += sizeof(ifr->ifr_name); - ptr += len; - } - } - catch (...) - { - delete [] buf; - throw; - } - delete [] buf; - return result; -} - - -} } // namespace Poco::Net - - -#endif +// +// NetworkInterface.cpp +// +// $Id: //poco/1.2/Net/src/NetworkInterface.cpp#1 $ +// +// Library: Net +// Package: Sockets +// Module: NetworkInterface +// +// 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/NetworkInterface.h" +#include "Poco/Net/DatagramSocket.h" +#include "Poco/Net/NetException.h" +#include "Poco/NumberFormatter.h" +#include + + +using Poco::NumberFormatter; +using Poco::FastMutex; + + +namespace Poco { +namespace Net { + + +FastMutex NetworkInterface::_mutex; + + +NetworkInterface::NetworkInterface(): + _index(0) +{ +} + + +NetworkInterface::NetworkInterface(const std::string& name, const IPAddress& address, int index): + _name(name), + _address(address), + _index(index) +{ +} + + +NetworkInterface::NetworkInterface(const NetworkInterface& interface): + _name(interface._name), + _address(interface._address), + _index(interface._index) +{ +} + + +NetworkInterface::~NetworkInterface() +{ +} + + +NetworkInterface& NetworkInterface::operator = (const NetworkInterface& interface) +{ + if (&interface != this) + { + _name = interface._name; + _address = interface._address; + _index = interface._index; + } + return *this; +} + + +NetworkInterface NetworkInterface::forName(const std::string& name, bool requireIPv6) +{ +#if defined(_WIN32) + NetworkInterfaceList ifs = list(); + for (NetworkInterfaceList::const_iterator it = ifs.begin(); it != ifs.end(); ++it) + { + if (it->name() == name && it->supportsIPv6() == requireIPv6) + return *it; + } + throw InterfaceNotFoundException(name); +#else + FastMutex::ScopedLock lock(_mutex); + + struct ifreq ifr; + strncpy(ifr.ifr_name, name.c_str(), IFNAMSIZ); + DatagramSocket ds(requireIPv6 ? IPAddress::IPv6 : IPAddress::IPv4); + ds.impl()->ioctl(SIOCGIFADDR, &ifr); + IPAddress addr; +#if defined(POCO_HAVE_IPv6) + if (ifr.ifr_addr.sa_family == AF_INET) + addr = IPAddress(&reinterpret_cast(&ifr.ifr_addr)->sin_addr, sizeof(struct in_addr)); + else if (ifr.ifr_addr.sa_family == AF_INET6) + addr = IPAddress(&reinterpret_cast(&ifr.ifr_addr)->sin6_addr, sizeof(struct in6_addr)); + else throw InterfaceNotFoundException(addr.toString(), "interface has no IP address"); + int index = if_nametoindex(name.c_str()); +#else + if (ifr.ifr_addr.sa_family == AF_INET) + addr = IPAddress(&reinterpret_cast(&ifr.ifr_addr)->sin_addr, sizeof(struct in_addr)); + else throw InterfaceNotFoundException(addr.toString(), "interface has no IP address"); + int index = 0; +#endif + return NetworkInterface(name, addr, index); +#endif +} + + +NetworkInterface NetworkInterface::forAddress(const IPAddress& addr) +{ + NetworkInterfaceList ifs = list(); + for (NetworkInterfaceList::const_iterator it = ifs.begin(); it != ifs.end(); ++it) + { + if (it->address() == addr) + return *it; + } + throw InterfaceNotFoundException(addr.toString()); +} + + +NetworkInterface NetworkInterface::forIndex(int i) +{ + if (i != 0) + { + NetworkInterfaceList ifs = list(); + for (NetworkInterfaceList::const_iterator it = ifs.begin(); it != ifs.end(); ++it) + { + if (it->index() == i) + return *it; + } + throw InterfaceNotFoundException("#" + NumberFormatter::format(i)); + } + else return NetworkInterface(); +} + + +} } // namespace Poco::Net + + +// +// platform-specific code below +// + + +#if defined(POCO_OS_FAMILY_WINDOWS) +// +// Windows +// +#include + + +namespace Poco { +namespace Net { + + +NetworkInterface::NetworkInterfaceList NetworkInterface::list() +{ + FastMutex::ScopedLock lock(_mutex); + NetworkInterfaceList result; + +#if defined(POCO_HAVE_IPv6) + // On Windows XP/Server 2003 and later we use GetAdaptersAddresses. + PIP_ADAPTER_ADDRESSES pAdapterAddresses; + PIP_ADAPTER_ADDRESSES pAdapter = 0; + ULONG len = sizeof(IP_ADAPTER_ADDRESSES); + pAdapterAddresses = reinterpret_cast(new char[len]); + // Make an initial call to GetAdaptersAddresses to get + // the necessary size into len + DWORD rc = GetAdaptersAddresses(AF_UNSPEC, 0, 0, pAdapterAddresses, &len); + if (rc == ERROR_BUFFER_OVERFLOW) + { + delete [] reinterpret_cast(pAdapterAddresses); + pAdapterAddresses = reinterpret_cast(new char[len]); + } + else if (rc != ERROR_SUCCESS) + { + throw NetException("cannot get network adapter list"); + } + try + { + if (GetAdaptersAddresses(AF_UNSPEC, 0, 0, pAdapterAddresses, &len) == NO_ERROR) + { + pAdapter = pAdapterAddresses; + while (pAdapter) + { + if (pAdapter->FirstUnicastAddress) + { + IPAddress addr(pAdapter->FirstUnicastAddress->Address.lpSockaddr, pAdapter->FirstUnicastAddress->Address.iSockaddrLength); + result.push_back(NetworkInterface(std::string(pAdapter->AdapterName), addr, pAdapter->Ipv6IfIndex)); + pAdapter = pAdapter->Next; + } + } + } + else throw NetException("cannot get network adapter list"); + } + catch (Poco::Exception&) + { + delete [] reinterpret_cast(pAdapterAddresses); + throw; + } + delete [] reinterpret_cast(pAdapterAddresses); +#else + // Add loopback interface (not returned by GetAdaptersInfo) + result.push_back(NetworkInterface("Loopback", IPAddress("127.0.0.1"), -1)); + // On Windows 2000 we use GetAdaptersInfo. + PIP_ADAPTER_INFO pAdapterInfo; + PIP_ADAPTER_INFO pAdapter = 0; + ULONG len = sizeof(IP_ADAPTER_INFO); + pAdapterInfo = reinterpret_cast(new char[len]); + // Make an initial call to GetAdaptersInfo to get + // the necessary size into len + DWORD rc = GetAdaptersInfo(pAdapterInfo, &len); + if (rc == ERROR_BUFFER_OVERFLOW) + { + delete [] reinterpret_cast(pAdapterInfo); + pAdapterInfo = reinterpret_cast(new char[len]); + } + else if (rc != ERROR_SUCCESS) + { + throw NetException("cannot get network adapter list"); + } + try + { + if (GetAdaptersInfo(pAdapterInfo, &len) == NO_ERROR) + { + pAdapter = pAdapterInfo; + while (pAdapter) + { + IPAddress addr(std::string(pAdapter->IpAddressList.IpAddress.String)); + result.push_back(NetworkInterface(std::string(pAdapter->AdapterName), addr)); + pAdapter = pAdapter->Next; + } + } + else throw NetException("cannot get network adapter list"); + } + catch (Poco::Exception&) + { + delete [] reinterpret_cast(pAdapterInfo); + throw; + } + delete [] reinterpret_cast(pAdapterInfo); +#endif + + return result; +} + + +} } // namespace Poco::Net + + +#elif defined(POCO_OS_FAMILY_BSD) || POCO_OS == POCO_OS_QNX +// +// BSD variants +// +#include +#include +#include +#include + + +namespace Poco { +namespace Net { + + +NetworkInterface::NetworkInterfaceList NetworkInterface::list() +{ + FastMutex::ScopedLock lock(_mutex); + NetworkInterfaceList result; + + struct ifaddrs* ifaphead; + int rc = getifaddrs(&ifaphead); + if (rc) throw NetException("cannot get network adapter list"); + + for (struct ifaddrs* ifap = ifaphead; ifap; ifap = ifap->ifa_next) + { + if (ifap->ifa_addr) + { + if (ifap->ifa_addr->sa_family == AF_INET) + { + IPAddress addr(&reinterpret_cast(ifap->ifa_addr)->sin_addr, sizeof(struct in_addr)); + result.push_back(NetworkInterface(std::string(ifap->ifa_name), addr)); + } +#if defined(POCO_HAVE_IPv6) + else if (ifap->ifa_addr->sa_family == AF_INET6) + { + IPAddress addr(&reinterpret_cast(ifap->ifa_addr)->sin6_addr, sizeof(struct in6_addr)); + result.push_back(NetworkInterface(std::string(ifap->ifa_name), addr, if_nametoindex(ifap->ifa_name))); + } +#endif + } + } + freeifaddrs(ifaphead); + return result; +} + + +} } // namespace Poco::Net + + +#elif POCO_OS == POCO_OS_LINUX +// +// Linux +// + + +namespace Poco { +namespace Net { + + +NetworkInterface::NetworkInterfaceList NetworkInterface::list() +{ + FastMutex::ScopedLock lock(_mutex); + NetworkInterfaceList result; + DatagramSocket socket; + // the following code is loosely based + // on W. Richard Stevens, UNIX Network Programming, pp 434ff. + int lastlen = 0; + int len = 100*sizeof(struct ifreq); + char* buf = 0; + try + { + struct ifconf ifc; + for (;;) + { + buf = new char[len]; + ifc.ifc_len = len; + ifc.ifc_buf = buf; + if (::ioctl(socket.impl()->sockfd(), SIOCGIFCONF, &ifc) < 0) + { + if (errno != EINVAL || lastlen != 0) + throw NetException("cannot get network adapter list"); + } + else + { + if (ifc.ifc_len == lastlen) + break; + lastlen = ifc.ifc_len; + } + len += 10*sizeof(struct ifreq); + delete [] buf; + } + for (const char* ptr = buf; ptr < buf + ifc.ifc_len;) + { + const struct ifreq* ifr = reinterpret_cast(ptr); + IPAddress addr; + bool haveAddr = false; + switch (ifr->ifr_addr.sa_family) + { +#if defined(POCO_HAVE_IPv6) + case AF_INET6: + addr = IPAddress(&reinterpret_cast(&ifr->ifr_addr)->sin6_addr, sizeof(struct in6_addr)); + haveAddr = true; + break; +#endif + case AF_INET: + addr = IPAddress(&reinterpret_cast(&ifr->ifr_addr)->sin_addr, sizeof(struct in_addr)); + haveAddr = true; + break; + default: + break; + } + if (haveAddr) + { +#if defined(POCO_HAVE_IPv6) + int index = if_nametoindex(ifr->ifr_name); +#else + int index = -1; +#endif + result.push_back(NetworkInterface(std::string(ifr->ifr_name), addr, index)); + } + ptr += sizeof(struct ifreq); + } + } + catch (...) + { + delete [] buf; + throw; + } + delete [] buf; + return result; +} + + +} } // namespace Poco::Net + + +#else +// +// Non-BSD Unix variants +// + + +namespace Poco { +namespace Net { + + +NetworkInterface::NetworkInterfaceList NetworkInterface::list() +{ + FastMutex::ScopedLock lock(_mutex); + NetworkInterfaceList result; + DatagramSocket socket; + // the following code is loosely based + // on W. Richard Stevens, UNIX Network Programming, pp 434ff. + int lastlen = 0; + int len = 100*sizeof(struct ifreq); + char* buf = 0; + try + { + struct ifconf ifc; + for (;;) + { + buf = new char[len]; + ifc.ifc_len = len; + ifc.ifc_buf = buf; + if (::ioctl(socket.impl()->sockfd(), SIOCGIFCONF, &ifc) < 0) + { + if (errno != EINVAL || lastlen != 0) + throw NetException("cannot get network adapter list"); + } + else + { + if (ifc.ifc_len == lastlen) + break; + lastlen = ifc.ifc_len; + } + len += 10*sizeof(struct ifreq); + delete [] buf; + } + for (const char* ptr = buf; ptr < buf + ifc.ifc_len;) + { + const struct ifreq* ifr = reinterpret_cast(ptr); +#if defined(POCO_HAVE_SALEN) + len = ifr->ifr_addr.sa_len; + if (sizeof(struct sockaddr) > len) len = sizeof(struct sockaddr); +#else + len = sizeof(struct sockaddr); +#endif + IPAddress addr; + bool haveAddr = false; + switch (ifr->ifr_addr.sa_family) + { +#if defined(POCO_HAVE_IPv6) + case AF_INET6: + if (len < sizeof(struct sockaddr_in6)) len = sizeof(struct sockaddr_in6); + addr = IPAddress(&reinterpret_cast(&ifr->ifr_addr)->sin6_addr, sizeof(struct in6_addr)); + haveAddr = true; + break; +#endif + case AF_INET: + if (len < sizeof(struct sockaddr_in)) len = sizeof(struct sockaddr_in); + addr = IPAddress(&reinterpret_cast(&ifr->ifr_addr)->sin_addr, sizeof(struct in_addr)); + haveAddr = true; + break; + default: + break; + } + if (haveAddr) + { +#if defined(POCO_HAVE_IPv6) + int index = if_nametoindex(ifr->ifr_name); +#else + int index = -1; +#endif + result.push_back(NetworkInterface(std::string(ifr->ifr_name), addr, index)); + } + len += sizeof(ifr->ifr_name); + ptr += len; + } + } + catch (...) + { + delete [] buf; + throw; + } + delete [] buf; + return result; +} + + +} } // namespace Poco::Net + + +#endif diff --git a/Net/src/NullPartHandler.cpp b/Net/src/NullPartHandler.cpp index 4e4fd4293..813714c06 100644 --- a/Net/src/NullPartHandler.cpp +++ b/Net/src/NullPartHandler.cpp @@ -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 diff --git a/Net/src/POP3ClientSession.cpp b/Net/src/POP3ClientSession.cpp index 03574a2e0..496fa12a2 100644 --- a/Net/src/POP3ClientSession.cpp +++ b/Net/src/POP3ClientSession.cpp @@ -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 -#include - - -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 +#include + + +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 diff --git a/Net/src/PartHandler.cpp b/Net/src/PartHandler.cpp index a03043819..a147d47f5 100644 --- a/Net/src/PartHandler.cpp +++ b/Net/src/PartHandler.cpp @@ -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 diff --git a/Net/src/PartSource.cpp b/Net/src/PartSource.cpp index 239aa22d3..48e3eb059 100644 --- a/Net/src/PartSource.cpp +++ b/Net/src/PartSource.cpp @@ -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 diff --git a/Net/src/QuotedPrintableDecoder.cpp b/Net/src/QuotedPrintableDecoder.cpp index ca61629dd..bb32e8ae2 100644 --- a/Net/src/QuotedPrintableDecoder.cpp +++ b/Net/src/QuotedPrintableDecoder.cpp @@ -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 - - -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 + + +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 diff --git a/Net/src/QuotedPrintableEncoder.cpp b/Net/src/QuotedPrintableEncoder.cpp index d3160c166..b31e50a58 100644 --- a/Net/src/QuotedPrintableEncoder.cpp +++ b/Net/src/QuotedPrintableEncoder.cpp @@ -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 diff --git a/Net/src/RawSocket.cpp b/Net/src/RawSocket.cpp index 370f862bb..ad8961267 100644 --- a/Net/src/RawSocket.cpp +++ b/Net/src/RawSocket.cpp @@ -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(impl())) - throw InvalidArgumentException("Cannot assign incompatible socket"); -} - - -RawSocket::RawSocket(SocketImpl* pImpl): Socket(pImpl) -{ - if (!dynamic_cast(impl())) - throw InvalidArgumentException("Cannot assign incompatible socket"); -} - - -RawSocket::~RawSocket() -{ -} - - -RawSocket& RawSocket::operator = (const Socket& socket) -{ - if (dynamic_cast(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(impl())) + throw InvalidArgumentException("Cannot assign incompatible socket"); +} + + +RawSocket::RawSocket(SocketImpl* pImpl): Socket(pImpl) +{ + if (!dynamic_cast(impl())) + throw InvalidArgumentException("Cannot assign incompatible socket"); +} + + +RawSocket::~RawSocket() +{ +} + + +RawSocket& RawSocket::operator = (const Socket& socket) +{ + if (dynamic_cast(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 diff --git a/Net/src/RawSocketImpl.cpp b/Net/src/RawSocketImpl.cpp index 40fffed39..3cb21389b 100644 --- a/Net/src/RawSocketImpl.cpp +++ b/Net/src/RawSocketImpl.cpp @@ -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 diff --git a/Net/src/SMTPClientSession.cpp b/Net/src/SMTPClientSession.cpp index d3448946d..d83b6790f 100644 --- a/Net/src/SMTPClientSession.cpp +++ b/Net/src/SMTPClientSession.cpp @@ -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 diff --git a/Net/src/ServerSocket.cpp b/Net/src/ServerSocket.cpp index 52c978bc9..797dd2ead 100644 --- a/Net/src/ServerSocket.cpp +++ b/Net/src/ServerSocket.cpp @@ -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(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(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(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(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 diff --git a/Net/src/ServerSocketImpl.cpp b/Net/src/ServerSocketImpl.cpp index d0eebae96..1eb4a106e 100644 --- a/Net/src/ServerSocketImpl.cpp +++ b/Net/src/ServerSocketImpl.cpp @@ -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 diff --git a/Net/src/Socket.cpp b/Net/src/Socket.cpp index 324168427..dbc886a9e 100644 --- a/Net/src/Socket.cpp +++ b/Net/src/Socket.cpp @@ -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 -#include - - -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 +#include + + +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 diff --git a/Net/src/SocketAddress.cpp b/Net/src/SocketAddress.cpp index 4dca57e0e..99e2c877c 100644 --- a/Net/src/SocketAddress.cpp +++ b/Net/src/SocketAddress.cpp @@ -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 -#include - - -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(&_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(&_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(addr)); -#if defined(POCO_HAVE_IPv6) - else if (length == sizeof(struct sockaddr_in6)) - _pImpl = new IPv6SocketAddressImpl(reinterpret_cast(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 +#include + + +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(&_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(&_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(addr)); +#if defined(POCO_HAVE_IPv6) + else if (length == sizeof(struct sockaddr_in6)) + _pImpl = new IPv6SocketAddressImpl(reinterpret_cast(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 diff --git a/Net/src/SocketImpl.cpp b/Net/src/SocketImpl.cpp index a62838641..482c66dca 100644 --- a/Net/src/SocketImpl.cpp +++ b/Net/src/SocketImpl.cpp @@ -1,864 +1,864 @@ -// -// SocketImpl.cpp -// -// $Id: //poco/1.2/Net/src/SocketImpl.cpp#2 $ -// -// Library: Net -// Package: Sockets -// Module: SocketImpl -// -// 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/SocketImpl.h" -#include "Poco/Net/NetException.h" -#include "Poco/Net/StreamSocketImpl.h" -#include "Poco/NumberFormatter.h" -#include "Poco/Timestamp.h" -#include - - -using Poco::IOException; -using Poco::TimeoutException; -using Poco::InvalidArgumentException; -using Poco::NumberFormatter; -using Poco::Timespan; - - -namespace Poco { -namespace Net { - - -SocketImpl::SocketImpl(): - _sockfd(POCO_INVALID_SOCKET) -{ -} - - -SocketImpl::SocketImpl(poco_socket_t sockfd): - _sockfd(sockfd) -{ -} - - -SocketImpl::~SocketImpl() -{ - close(); -} - - -SocketImpl* SocketImpl::acceptConnection(SocketAddress& clientAddr) -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - char buffer[SocketAddress::MAX_ADDRESS_LENGTH]; - struct sockaddr* pSA = reinterpret_cast(buffer); - poco_socklen_t saLen = sizeof(buffer); - poco_socket_t sd; - do - { - sd = ::accept(_sockfd, pSA, &saLen); - } - while (sd == POCO_INVALID_SOCKET && lastError() == POCO_EINTR); - if (sd != POCO_INVALID_SOCKET) - { - clientAddr = SocketAddress(pSA, saLen); - return new StreamSocketImpl(sd); - } - error(); // will throw - return 0; -} - - -void SocketImpl::connect(const SocketAddress& address) -{ - if (_sockfd == POCO_INVALID_SOCKET) - { - init(address.af()); - } - int rc; - do - { - rc = ::connect(_sockfd, address.addr(), address.length()); - } - while (rc != 0 && lastError() == POCO_EINTR); - if (rc != 0) error(address.toString()); -} - - -void SocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout) -{ - poco_assert (_sockfd == POCO_INVALID_SOCKET); - - init(address.af()); - setBlocking(false); - try - { - int rc = ::connect(_sockfd, address.addr(), address.length()); - if (rc != 0) - { - if (lastError() != POCO_EINPROGRESS && lastError() != POCO_EWOULDBLOCK) - error(address.toString()); - if (!poll(timeout, SELECT_READ | SELECT_WRITE)) - throw Poco::TimeoutException("connect timed out", address.toString()); - int err = socketError(); - if (err != 0) error(err); - } - } - catch (Poco::Exception&) - { - setBlocking(true); - throw; - } - setBlocking(true); -} - - -void SocketImpl::connectNB(const SocketAddress& address) -{ - if (_sockfd == POCO_INVALID_SOCKET) - { - init(address.af()); - } - setBlocking(false); - int rc = ::connect(_sockfd, address.addr(), address.length()); - if (rc != 0) - { - if (lastError() != POCO_EINPROGRESS && lastError() != POCO_EWOULDBLOCK) - error(address.toString()); - } -} - - -void SocketImpl::bind(const SocketAddress& address, bool reuseAddress) -{ - if (_sockfd == POCO_INVALID_SOCKET) - { - init(address.af()); - } - if (reuseAddress) - { - setReuseAddress(true); - setReusePort(true); - } - int rc = ::bind(_sockfd, address.addr(), address.length()); - if (rc != 0) error(address.toString()); -} - - -void SocketImpl::listen(int backlog) -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - int rc = ::listen(_sockfd, backlog); - if (rc != 0) error(); -} - - -void SocketImpl::close() -{ - if (_sockfd != POCO_INVALID_SOCKET) - { - poco_closesocket(_sockfd); - _sockfd = POCO_INVALID_SOCKET; - } -} - - -void SocketImpl::shutdownReceive() -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - int rc = ::shutdown(_sockfd, 0); - if (rc != 0) error(); -} - - -void SocketImpl::shutdownSend() -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - int rc = ::shutdown(_sockfd, 1); - if (rc != 0) error(); -} - - -void SocketImpl::shutdown() -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - int rc = ::shutdown(_sockfd, 2); - if (rc != 0) error(); -} - - -int SocketImpl::sendBytes(const void* buffer, int length, int flags) -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - int rc; - do - { - rc = ::send(_sockfd, reinterpret_cast(buffer), length, flags); - } - while (rc < 0 && lastError() == POCO_EINTR); - if (rc < 0) error(); - return rc; -} - - -int SocketImpl::receiveBytes(void* buffer, int length, int flags) -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - -#if defined(POCO_BROKEN_TIMEOUTS) - if (_recvTimeout.totalMicroseconds() != 0) - { - if (!poll(_recvTimeout, SELECT_READ)) - throw TimeoutException(); - } -#endif - - int rc; - do - { - rc = ::recv(_sockfd, reinterpret_cast(buffer), length, flags); - } - while (rc < 0 && lastError() == POCO_EINTR); - if (rc < 0) - { - if (lastError() == POCO_EAGAIN || lastError() == POCO_ETIMEDOUT) - throw TimeoutException(); - else - error(); - } - return rc; -} - - -int SocketImpl::sendTo(const void* buffer, int length, const SocketAddress& address, int flags) -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - int rc; - do - { - rc = ::sendto(_sockfd, reinterpret_cast(buffer), length, flags, address.addr(), address.length()); - } - while (rc < 0 && lastError() == POCO_EINTR); - if (rc < 0) error(); - return rc; -} - - -int SocketImpl::receiveFrom(void* buffer, int length, SocketAddress& address, int flags) -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - -#if defined(POCO_BROKEN_TIMEOUTS) - if (_recvTimeout.totalMicroseconds() != 0) - { - if (!poll(_recvTimeout, SELECT_READ)) - throw TimeoutException(); - } -#endif - - char abuffer[SocketAddress::MAX_ADDRESS_LENGTH]; - struct sockaddr* pSA = reinterpret_cast(abuffer); - poco_socklen_t saLen = sizeof(abuffer); - int rc; - do - { - rc = ::recvfrom(_sockfd, reinterpret_cast(buffer), length, flags, pSA, &saLen); - } - while (rc < 0 && lastError() == POCO_EINTR); - if (rc >= 0) - { - address = SocketAddress(pSA, saLen); - } - else - { - if (lastError() == POCO_EAGAIN || lastError() == POCO_ETIMEDOUT) - throw TimeoutException(); - else - error(); - } - return rc; -} - - -void SocketImpl::sendUrgent(unsigned char data) -{ - int rc = ::send(_sockfd, reinterpret_cast(&data), sizeof(data), MSG_OOB); - if (rc < 0) error(); -} - - -int SocketImpl::available() -{ - int result; - ioctl(FIONREAD, result); - return result; -} - - -bool SocketImpl::poll(const Poco::Timespan& timeout, int mode) -{ - fd_set fdRead; - fd_set fdWrite; - fd_set fdExcept; - FD_ZERO(&fdRead); - FD_ZERO(&fdWrite); - FD_ZERO(&fdExcept); - if (mode & SELECT_READ) - { - FD_SET(_sockfd, &fdRead); - } - if (mode & SELECT_WRITE) - { - FD_SET(_sockfd, &fdWrite); - } - if (mode & SELECT_ERROR) - { - FD_SET(_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(int(_sockfd) + 1, &fdRead, &fdWrite, &fdExcept, &tv); - if (rc < 0 && lastError() == POCO_EINTR) - { - Poco::Timestamp end; - Poco::Timespan waited = end - start; - if (waited > remainingTime) - remainingTime -= waited; - else - remainingTime = 0; - } - } - while (rc < 0 && lastError() == POCO_EINTR); - if (rc < 0) error(); - return rc > 0; -} - - -void SocketImpl::setSendBufferSize(int size) -{ - setOption(SOL_SOCKET, SO_SNDBUF, size); -} - - -int SocketImpl::getSendBufferSize() -{ - int result; - getOption(SOL_SOCKET, SO_SNDBUF, result); - return result; -} - - -void SocketImpl::setReceiveBufferSize(int size) -{ - setOption(SOL_SOCKET, SO_RCVBUF, size); -} - - -int SocketImpl::getReceiveBufferSize() -{ - int result; - getOption(SOL_SOCKET, SO_RCVBUF, result); - return result; -} - - -void SocketImpl::setSendTimeout(const Poco::Timespan& timeout) -{ -#if defined(_WIN32) - int value = (int) timeout.totalMilliseconds(); - setOption(SOL_SOCKET, SO_SNDTIMEO, value); -#else - setOption(SOL_SOCKET, SO_SNDTIMEO, timeout); -#endif -} - - -Poco::Timespan SocketImpl::getSendTimeout() -{ - Timespan result; -#if defined(_WIN32) - int value; - getOption(SOL_SOCKET, SO_SNDTIMEO, value); - result = Timespan::TimeDiff(value)*1000; -#else - getOption(SOL_SOCKET, SO_SNDTIMEO, result); -#endif - return result; -} - - -void SocketImpl::setReceiveTimeout(const Poco::Timespan& timeout) -{ -#if defined(_WIN32) - int value = (int) timeout.totalMilliseconds(); - setOption(SOL_SOCKET, SO_RCVTIMEO, value); -#else - setOption(SOL_SOCKET, SO_RCVTIMEO, timeout); -#endif -#if defined(POCO_BROKEN_TIMEOUTS) - _recvTimeout = timeout; -#endif -} - - -Poco::Timespan SocketImpl::getReceiveTimeout() -{ - Timespan result; -#if defined(_WIN32) - int value; - getOption(SOL_SOCKET, SO_RCVTIMEO, value); - result = Timespan::TimeDiff(value)*1000; -#elif defined(POCO_BROKEN_TIMEOUTS) - result = _recvTimeout; -#else - getOption(SOL_SOCKET, SO_RCVTIMEO, result); -#endif - return result; -} - - -SocketAddress SocketImpl::address() -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - char buffer[SocketAddress::MAX_ADDRESS_LENGTH]; - struct sockaddr* pSA = reinterpret_cast(buffer); - poco_socklen_t saLen = sizeof(buffer); - int rc = ::getsockname(_sockfd, pSA, &saLen); - if (rc == 0) - return SocketAddress(pSA, saLen); - else - error(); - return SocketAddress(); -} - - -SocketAddress SocketImpl::peerAddress() -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - char buffer[SocketAddress::MAX_ADDRESS_LENGTH]; - struct sockaddr* pSA = reinterpret_cast(buffer); - poco_socklen_t saLen = sizeof(buffer); - int rc = ::getpeername(_sockfd, pSA, &saLen); - if (rc == 0) - return SocketAddress(pSA, saLen); - else - error(); - return SocketAddress(); -} - - -void SocketImpl::setOption(int level, int option, int value) -{ - setRawOption(level, option, &value, sizeof(value)); -} - - -void SocketImpl::setOption(int level, int option, unsigned value) -{ - setRawOption(level, option, &value, sizeof(value)); -} - - -void SocketImpl::setOption(int level, int option, unsigned char value) -{ - setRawOption(level, option, &value, sizeof(value)); -} - - -void SocketImpl::setOption(int level, int option, const IPAddress& value) -{ - setRawOption(level, option, value.addr(), value.length()); -} - - -void SocketImpl::setOption(int level, int option, const Poco::Timespan& value) -{ - struct timeval tv; - tv.tv_sec = (long) value.totalSeconds(); - tv.tv_usec = (long) value.useconds(); - - setRawOption(level, option, &tv, sizeof(tv)); -} - - -void SocketImpl::setRawOption(int level, int option, const void* value, poco_socklen_t length) -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - int rc = ::setsockopt(_sockfd, level, option, reinterpret_cast(value), length); - if (rc == -1) error(); -} - - -void SocketImpl::getOption(int level, int option, int& value) -{ - poco_socklen_t len = sizeof(value); - getRawOption(level, option, &value, len); -} - - -void SocketImpl::getOption(int level, int option, unsigned& value) -{ - poco_socklen_t len = sizeof(value); - getRawOption(level, option, &value, len); -} - - -void SocketImpl::getOption(int level, int option, unsigned char& value) -{ - poco_socklen_t len = sizeof(value); - getRawOption(level, option, &value, len); -} - - -void SocketImpl::getOption(int level, int option, Poco::Timespan& value) -{ - struct timeval tv; - poco_socklen_t len = sizeof(tv); - getRawOption(level, option, &tv, len); - value.assign(tv.tv_sec, tv.tv_usec); -} - - -void SocketImpl::getOption(int level, int option, IPAddress& value) -{ - char buffer[IPAddress::MAX_ADDRESS_LENGTH]; - poco_socklen_t len = sizeof(buffer); - getRawOption(level, option, buffer, len); - value = IPAddress(buffer, len); -} - - -void SocketImpl::getRawOption(int level, int option, void* value, poco_socklen_t& length) -{ - poco_assert (_sockfd != POCO_INVALID_SOCKET); - - int rc = ::getsockopt(_sockfd, level, option, reinterpret_cast(value), &length); - if (rc == -1) error(); -} - - -void SocketImpl::setLinger(bool on, int seconds) -{ - struct linger l; - l.l_onoff = on ? 1 : 0; - l.l_linger = seconds; - setRawOption(SOL_SOCKET, SO_LINGER, &l, sizeof(l)); -} - - -void SocketImpl::getLinger(bool& on, int& seconds) -{ - struct linger l; - poco_socklen_t len = sizeof(l); - getRawOption(SOL_SOCKET, SO_LINGER, &l, len); - on = l.l_onoff != 0; - seconds = l.l_linger; -} - - -void SocketImpl::setNoDelay(bool flag) -{ - int value = flag ? 1 : 0; - setOption(IPPROTO_TCP, TCP_NODELAY, value); -} - - -bool SocketImpl::getNoDelay() -{ - int value; - getOption(IPPROTO_TCP, TCP_NODELAY, value); - return value != 0; -} - - -void SocketImpl::setKeepAlive(bool flag) -{ - int value = flag ? 1 : 0; - setOption(SOL_SOCKET, SO_KEEPALIVE, value); -} - - -bool SocketImpl::getKeepAlive() -{ - int value; - getOption(SOL_SOCKET, SO_KEEPALIVE, value); - return value != 0; -} - - -void SocketImpl::setReuseAddress(bool flag) -{ - int value = flag ? 1 : 0; - setOption(SOL_SOCKET, SO_REUSEADDR, value); -} - - -bool SocketImpl::getReuseAddress() -{ - int value; - getOption(SOL_SOCKET, SO_REUSEADDR, value); - return value != 0; -} - - -void SocketImpl::setReusePort(bool flag) -{ -#ifdef SO_REUSEPORT - try - { - int value = flag ? 1 : 0; - setOption(SOL_SOCKET, SO_REUSEPORT, value); - } - catch (IOException&) - { - // ignore error, since not all implementations - // support SO_REUSEPORT, even if the macro - // is defined. - } -#endif -} - - -bool SocketImpl::getReusePort() -{ -#ifdef SO_REUSEPORT - int value; - getOption(SOL_SOCKET, SO_REUSEPORT, value); - return value != 0; -#else - return false; -#endif -} - - -void SocketImpl::setOOBInline(bool flag) -{ - int value = flag ? 1 : 0; - setOption(SOL_SOCKET, SO_OOBINLINE, value); -} - - -bool SocketImpl::getOOBInline() -{ - int value; - getOption(SOL_SOCKET, SO_OOBINLINE, value); - return value != 0; -} - - -void SocketImpl::setBroadcast(bool flag) -{ - int value = flag ? 1 : 0; - setOption(SOL_SOCKET, SO_BROADCAST, value); -} - - -bool SocketImpl::getBroadcast() -{ - int value; - getOption(SOL_SOCKET, SO_BROADCAST, value); - return value != 0; -} - - -void SocketImpl::setBlocking(bool flag) -{ - int arg = flag ? 0 : 1; - ioctl(FIONBIO, arg); -} - - -int SocketImpl::socketError() -{ - int result; - getOption(SOL_SOCKET, SO_ERROR, result); - return result; -} - - -void SocketImpl::init(int af) -{ - initSocket(af, SOCK_STREAM); -} - - -void SocketImpl::initSocket(int af, int type, int proto) -{ - poco_assert (_sockfd == POCO_INVALID_SOCKET); - - _sockfd = ::socket(af, type, proto); - if (_sockfd == POCO_INVALID_SOCKET) - error(); -} - - -void SocketImpl::ioctl(int request, int& arg) -{ -#if defined(_WIN32) - int rc = ioctlsocket(_sockfd, request, reinterpret_cast(&arg)); -#else - int rc = ::ioctl(_sockfd, request, &arg); -#endif - if (rc != 0) error(); -} - - -void SocketImpl::ioctl(int request, void* arg) -{ -#if defined(_WIN32) - int rc = ioctlsocket(_sockfd, request, reinterpret_cast(arg)); -#else - int rc = ::ioctl(_sockfd, request, arg); -#endif - if (rc != 0) error(); -} - - -void SocketImpl::setSockfd(poco_socket_t aSocket) -{ - poco_assert(sockfd() == POCO_INVALID_SOCKET); - _sockfd = aSocket; -} - - -void SocketImpl::error() -{ - std::string empty; - error(lastError(), empty); -} - - -void SocketImpl::error(const std::string& arg) -{ - error(lastError(), arg); -} - - -void SocketImpl::error(int code) -{ - std::string arg; - error(code, arg); -} - - -void SocketImpl::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_EINTR: - throw IOException("Interrupted"); - case POCO_EACCES: - throw IOException("Permission denied"); - case POCO_EFAULT: - throw IOException("Bad address"); - case POCO_EINVAL: - throw InvalidArgumentException(); - case POCO_EMFILE: - throw IOException("Too many open files"); - case POCO_EWOULDBLOCK: - throw IOException("Operation would block"); - case POCO_EINPROGRESS: - throw IOException("Operation now in progress"); - case POCO_EALREADY: - throw IOException("Operation already in progress"); - case POCO_ENOTSOCK: - throw IOException("Socket operation attempted on non-socket"); - case POCO_EDESTADDRREQ: - throw NetException("Destination address required"); - case POCO_EMSGSIZE: - throw NetException("Message too long"); - case POCO_EPROTOTYPE: - throw NetException("Wrong protocol type"); - case POCO_ENOPROTOOPT: - throw NetException("Protocol not available"); - case POCO_EPROTONOSUPPORT: - throw NetException("Protocol not supported"); - case POCO_ESOCKTNOSUPPORT: - throw NetException("Socket type not supported"); - case POCO_ENOTSUP: - throw NetException("Operation not supported"); - case POCO_EPFNOSUPPORT: - throw NetException("Protocol family not supported"); - case POCO_EAFNOSUPPORT: - throw NetException("Address family not supported"); - case POCO_EADDRINUSE: - throw NetException("Address already in use", arg); - case POCO_EADDRNOTAVAIL: - throw NetException("Cannot assign requested address", arg); - case POCO_ENETDOWN: - throw NetException("Network is down"); - case POCO_ENETUNREACH: - throw NetException("Network is unreachable"); - case POCO_ENETRESET: - throw NetException("Network dropped connection on reset"); - case POCO_ECONNABORTED: - throw ConnectionAbortedException(); - case POCO_ECONNRESET: - throw ConnectionResetException(); - case POCO_ENOBUFS: - throw IOException("No buffer space available"); - case POCO_EISCONN: - throw NetException("Socket is already connected"); - case POCO_ENOTCONN: - throw NetException("Socket is not connected"); - case POCO_ESHUTDOWN: - throw NetException("Cannot send after socket shutdown"); - case POCO_ETIMEDOUT: - throw TimeoutException(); - case POCO_ECONNREFUSED: - throw ConnectionRefusedException(arg); - case POCO_EHOSTDOWN: - throw NetException("Host is down"); - case POCO_EHOSTUNREACH: - throw NetException("No route to host"); - default: - throw IOException(NumberFormatter::format(code) + arg); - } -} - - -} } // namespace Poco::Net +// +// SocketImpl.cpp +// +// $Id: //poco/1.2/Net/src/SocketImpl.cpp#2 $ +// +// Library: Net +// Package: Sockets +// Module: SocketImpl +// +// 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/SocketImpl.h" +#include "Poco/Net/NetException.h" +#include "Poco/Net/StreamSocketImpl.h" +#include "Poco/NumberFormatter.h" +#include "Poco/Timestamp.h" +#include + + +using Poco::IOException; +using Poco::TimeoutException; +using Poco::InvalidArgumentException; +using Poco::NumberFormatter; +using Poco::Timespan; + + +namespace Poco { +namespace Net { + + +SocketImpl::SocketImpl(): + _sockfd(POCO_INVALID_SOCKET) +{ +} + + +SocketImpl::SocketImpl(poco_socket_t sockfd): + _sockfd(sockfd) +{ +} + + +SocketImpl::~SocketImpl() +{ + close(); +} + + +SocketImpl* SocketImpl::acceptConnection(SocketAddress& clientAddr) +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + char buffer[SocketAddress::MAX_ADDRESS_LENGTH]; + struct sockaddr* pSA = reinterpret_cast(buffer); + poco_socklen_t saLen = sizeof(buffer); + poco_socket_t sd; + do + { + sd = ::accept(_sockfd, pSA, &saLen); + } + while (sd == POCO_INVALID_SOCKET && lastError() == POCO_EINTR); + if (sd != POCO_INVALID_SOCKET) + { + clientAddr = SocketAddress(pSA, saLen); + return new StreamSocketImpl(sd); + } + error(); // will throw + return 0; +} + + +void SocketImpl::connect(const SocketAddress& address) +{ + if (_sockfd == POCO_INVALID_SOCKET) + { + init(address.af()); + } + int rc; + do + { + rc = ::connect(_sockfd, address.addr(), address.length()); + } + while (rc != 0 && lastError() == POCO_EINTR); + if (rc != 0) error(address.toString()); +} + + +void SocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout) +{ + poco_assert (_sockfd == POCO_INVALID_SOCKET); + + init(address.af()); + setBlocking(false); + try + { + int rc = ::connect(_sockfd, address.addr(), address.length()); + if (rc != 0) + { + if (lastError() != POCO_EINPROGRESS && lastError() != POCO_EWOULDBLOCK) + error(address.toString()); + if (!poll(timeout, SELECT_READ | SELECT_WRITE)) + throw Poco::TimeoutException("connect timed out", address.toString()); + int err = socketError(); + if (err != 0) error(err); + } + } + catch (Poco::Exception&) + { + setBlocking(true); + throw; + } + setBlocking(true); +} + + +void SocketImpl::connectNB(const SocketAddress& address) +{ + if (_sockfd == POCO_INVALID_SOCKET) + { + init(address.af()); + } + setBlocking(false); + int rc = ::connect(_sockfd, address.addr(), address.length()); + if (rc != 0) + { + if (lastError() != POCO_EINPROGRESS && lastError() != POCO_EWOULDBLOCK) + error(address.toString()); + } +} + + +void SocketImpl::bind(const SocketAddress& address, bool reuseAddress) +{ + if (_sockfd == POCO_INVALID_SOCKET) + { + init(address.af()); + } + if (reuseAddress) + { + setReuseAddress(true); + setReusePort(true); + } + int rc = ::bind(_sockfd, address.addr(), address.length()); + if (rc != 0) error(address.toString()); +} + + +void SocketImpl::listen(int backlog) +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + int rc = ::listen(_sockfd, backlog); + if (rc != 0) error(); +} + + +void SocketImpl::close() +{ + if (_sockfd != POCO_INVALID_SOCKET) + { + poco_closesocket(_sockfd); + _sockfd = POCO_INVALID_SOCKET; + } +} + + +void SocketImpl::shutdownReceive() +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + int rc = ::shutdown(_sockfd, 0); + if (rc != 0) error(); +} + + +void SocketImpl::shutdownSend() +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + int rc = ::shutdown(_sockfd, 1); + if (rc != 0) error(); +} + + +void SocketImpl::shutdown() +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + int rc = ::shutdown(_sockfd, 2); + if (rc != 0) error(); +} + + +int SocketImpl::sendBytes(const void* buffer, int length, int flags) +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + int rc; + do + { + rc = ::send(_sockfd, reinterpret_cast(buffer), length, flags); + } + while (rc < 0 && lastError() == POCO_EINTR); + if (rc < 0) error(); + return rc; +} + + +int SocketImpl::receiveBytes(void* buffer, int length, int flags) +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + +#if defined(POCO_BROKEN_TIMEOUTS) + if (_recvTimeout.totalMicroseconds() != 0) + { + if (!poll(_recvTimeout, SELECT_READ)) + throw TimeoutException(); + } +#endif + + int rc; + do + { + rc = ::recv(_sockfd, reinterpret_cast(buffer), length, flags); + } + while (rc < 0 && lastError() == POCO_EINTR); + if (rc < 0) + { + if (lastError() == POCO_EAGAIN || lastError() == POCO_ETIMEDOUT) + throw TimeoutException(); + else + error(); + } + return rc; +} + + +int SocketImpl::sendTo(const void* buffer, int length, const SocketAddress& address, int flags) +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + int rc; + do + { + rc = ::sendto(_sockfd, reinterpret_cast(buffer), length, flags, address.addr(), address.length()); + } + while (rc < 0 && lastError() == POCO_EINTR); + if (rc < 0) error(); + return rc; +} + + +int SocketImpl::receiveFrom(void* buffer, int length, SocketAddress& address, int flags) +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + +#if defined(POCO_BROKEN_TIMEOUTS) + if (_recvTimeout.totalMicroseconds() != 0) + { + if (!poll(_recvTimeout, SELECT_READ)) + throw TimeoutException(); + } +#endif + + char abuffer[SocketAddress::MAX_ADDRESS_LENGTH]; + struct sockaddr* pSA = reinterpret_cast(abuffer); + poco_socklen_t saLen = sizeof(abuffer); + int rc; + do + { + rc = ::recvfrom(_sockfd, reinterpret_cast(buffer), length, flags, pSA, &saLen); + } + while (rc < 0 && lastError() == POCO_EINTR); + if (rc >= 0) + { + address = SocketAddress(pSA, saLen); + } + else + { + if (lastError() == POCO_EAGAIN || lastError() == POCO_ETIMEDOUT) + throw TimeoutException(); + else + error(); + } + return rc; +} + + +void SocketImpl::sendUrgent(unsigned char data) +{ + int rc = ::send(_sockfd, reinterpret_cast(&data), sizeof(data), MSG_OOB); + if (rc < 0) error(); +} + + +int SocketImpl::available() +{ + int result; + ioctl(FIONREAD, result); + return result; +} + + +bool SocketImpl::poll(const Poco::Timespan& timeout, int mode) +{ + fd_set fdRead; + fd_set fdWrite; + fd_set fdExcept; + FD_ZERO(&fdRead); + FD_ZERO(&fdWrite); + FD_ZERO(&fdExcept); + if (mode & SELECT_READ) + { + FD_SET(_sockfd, &fdRead); + } + if (mode & SELECT_WRITE) + { + FD_SET(_sockfd, &fdWrite); + } + if (mode & SELECT_ERROR) + { + FD_SET(_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(int(_sockfd) + 1, &fdRead, &fdWrite, &fdExcept, &tv); + if (rc < 0 && lastError() == POCO_EINTR) + { + Poco::Timestamp end; + Poco::Timespan waited = end - start; + if (waited > remainingTime) + remainingTime -= waited; + else + remainingTime = 0; + } + } + while (rc < 0 && lastError() == POCO_EINTR); + if (rc < 0) error(); + return rc > 0; +} + + +void SocketImpl::setSendBufferSize(int size) +{ + setOption(SOL_SOCKET, SO_SNDBUF, size); +} + + +int SocketImpl::getSendBufferSize() +{ + int result; + getOption(SOL_SOCKET, SO_SNDBUF, result); + return result; +} + + +void SocketImpl::setReceiveBufferSize(int size) +{ + setOption(SOL_SOCKET, SO_RCVBUF, size); +} + + +int SocketImpl::getReceiveBufferSize() +{ + int result; + getOption(SOL_SOCKET, SO_RCVBUF, result); + return result; +} + + +void SocketImpl::setSendTimeout(const Poco::Timespan& timeout) +{ +#if defined(_WIN32) + int value = (int) timeout.totalMilliseconds(); + setOption(SOL_SOCKET, SO_SNDTIMEO, value); +#else + setOption(SOL_SOCKET, SO_SNDTIMEO, timeout); +#endif +} + + +Poco::Timespan SocketImpl::getSendTimeout() +{ + Timespan result; +#if defined(_WIN32) + int value; + getOption(SOL_SOCKET, SO_SNDTIMEO, value); + result = Timespan::TimeDiff(value)*1000; +#else + getOption(SOL_SOCKET, SO_SNDTIMEO, result); +#endif + return result; +} + + +void SocketImpl::setReceiveTimeout(const Poco::Timespan& timeout) +{ +#if defined(_WIN32) + int value = (int) timeout.totalMilliseconds(); + setOption(SOL_SOCKET, SO_RCVTIMEO, value); +#else + setOption(SOL_SOCKET, SO_RCVTIMEO, timeout); +#endif +#if defined(POCO_BROKEN_TIMEOUTS) + _recvTimeout = timeout; +#endif +} + + +Poco::Timespan SocketImpl::getReceiveTimeout() +{ + Timespan result; +#if defined(_WIN32) + int value; + getOption(SOL_SOCKET, SO_RCVTIMEO, value); + result = Timespan::TimeDiff(value)*1000; +#elif defined(POCO_BROKEN_TIMEOUTS) + result = _recvTimeout; +#else + getOption(SOL_SOCKET, SO_RCVTIMEO, result); +#endif + return result; +} + + +SocketAddress SocketImpl::address() +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + char buffer[SocketAddress::MAX_ADDRESS_LENGTH]; + struct sockaddr* pSA = reinterpret_cast(buffer); + poco_socklen_t saLen = sizeof(buffer); + int rc = ::getsockname(_sockfd, pSA, &saLen); + if (rc == 0) + return SocketAddress(pSA, saLen); + else + error(); + return SocketAddress(); +} + + +SocketAddress SocketImpl::peerAddress() +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + char buffer[SocketAddress::MAX_ADDRESS_LENGTH]; + struct sockaddr* pSA = reinterpret_cast(buffer); + poco_socklen_t saLen = sizeof(buffer); + int rc = ::getpeername(_sockfd, pSA, &saLen); + if (rc == 0) + return SocketAddress(pSA, saLen); + else + error(); + return SocketAddress(); +} + + +void SocketImpl::setOption(int level, int option, int value) +{ + setRawOption(level, option, &value, sizeof(value)); +} + + +void SocketImpl::setOption(int level, int option, unsigned value) +{ + setRawOption(level, option, &value, sizeof(value)); +} + + +void SocketImpl::setOption(int level, int option, unsigned char value) +{ + setRawOption(level, option, &value, sizeof(value)); +} + + +void SocketImpl::setOption(int level, int option, const IPAddress& value) +{ + setRawOption(level, option, value.addr(), value.length()); +} + + +void SocketImpl::setOption(int level, int option, const Poco::Timespan& value) +{ + struct timeval tv; + tv.tv_sec = (long) value.totalSeconds(); + tv.tv_usec = (long) value.useconds(); + + setRawOption(level, option, &tv, sizeof(tv)); +} + + +void SocketImpl::setRawOption(int level, int option, const void* value, poco_socklen_t length) +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + int rc = ::setsockopt(_sockfd, level, option, reinterpret_cast(value), length); + if (rc == -1) error(); +} + + +void SocketImpl::getOption(int level, int option, int& value) +{ + poco_socklen_t len = sizeof(value); + getRawOption(level, option, &value, len); +} + + +void SocketImpl::getOption(int level, int option, unsigned& value) +{ + poco_socklen_t len = sizeof(value); + getRawOption(level, option, &value, len); +} + + +void SocketImpl::getOption(int level, int option, unsigned char& value) +{ + poco_socklen_t len = sizeof(value); + getRawOption(level, option, &value, len); +} + + +void SocketImpl::getOption(int level, int option, Poco::Timespan& value) +{ + struct timeval tv; + poco_socklen_t len = sizeof(tv); + getRawOption(level, option, &tv, len); + value.assign(tv.tv_sec, tv.tv_usec); +} + + +void SocketImpl::getOption(int level, int option, IPAddress& value) +{ + char buffer[IPAddress::MAX_ADDRESS_LENGTH]; + poco_socklen_t len = sizeof(buffer); + getRawOption(level, option, buffer, len); + value = IPAddress(buffer, len); +} + + +void SocketImpl::getRawOption(int level, int option, void* value, poco_socklen_t& length) +{ + poco_assert (_sockfd != POCO_INVALID_SOCKET); + + int rc = ::getsockopt(_sockfd, level, option, reinterpret_cast(value), &length); + if (rc == -1) error(); +} + + +void SocketImpl::setLinger(bool on, int seconds) +{ + struct linger l; + l.l_onoff = on ? 1 : 0; + l.l_linger = seconds; + setRawOption(SOL_SOCKET, SO_LINGER, &l, sizeof(l)); +} + + +void SocketImpl::getLinger(bool& on, int& seconds) +{ + struct linger l; + poco_socklen_t len = sizeof(l); + getRawOption(SOL_SOCKET, SO_LINGER, &l, len); + on = l.l_onoff != 0; + seconds = l.l_linger; +} + + +void SocketImpl::setNoDelay(bool flag) +{ + int value = flag ? 1 : 0; + setOption(IPPROTO_TCP, TCP_NODELAY, value); +} + + +bool SocketImpl::getNoDelay() +{ + int value; + getOption(IPPROTO_TCP, TCP_NODELAY, value); + return value != 0; +} + + +void SocketImpl::setKeepAlive(bool flag) +{ + int value = flag ? 1 : 0; + setOption(SOL_SOCKET, SO_KEEPALIVE, value); +} + + +bool SocketImpl::getKeepAlive() +{ + int value; + getOption(SOL_SOCKET, SO_KEEPALIVE, value); + return value != 0; +} + + +void SocketImpl::setReuseAddress(bool flag) +{ + int value = flag ? 1 : 0; + setOption(SOL_SOCKET, SO_REUSEADDR, value); +} + + +bool SocketImpl::getReuseAddress() +{ + int value; + getOption(SOL_SOCKET, SO_REUSEADDR, value); + return value != 0; +} + + +void SocketImpl::setReusePort(bool flag) +{ +#ifdef SO_REUSEPORT + try + { + int value = flag ? 1 : 0; + setOption(SOL_SOCKET, SO_REUSEPORT, value); + } + catch (IOException&) + { + // ignore error, since not all implementations + // support SO_REUSEPORT, even if the macro + // is defined. + } +#endif +} + + +bool SocketImpl::getReusePort() +{ +#ifdef SO_REUSEPORT + int value; + getOption(SOL_SOCKET, SO_REUSEPORT, value); + return value != 0; +#else + return false; +#endif +} + + +void SocketImpl::setOOBInline(bool flag) +{ + int value = flag ? 1 : 0; + setOption(SOL_SOCKET, SO_OOBINLINE, value); +} + + +bool SocketImpl::getOOBInline() +{ + int value; + getOption(SOL_SOCKET, SO_OOBINLINE, value); + return value != 0; +} + + +void SocketImpl::setBroadcast(bool flag) +{ + int value = flag ? 1 : 0; + setOption(SOL_SOCKET, SO_BROADCAST, value); +} + + +bool SocketImpl::getBroadcast() +{ + int value; + getOption(SOL_SOCKET, SO_BROADCAST, value); + return value != 0; +} + + +void SocketImpl::setBlocking(bool flag) +{ + int arg = flag ? 0 : 1; + ioctl(FIONBIO, arg); +} + + +int SocketImpl::socketError() +{ + int result; + getOption(SOL_SOCKET, SO_ERROR, result); + return result; +} + + +void SocketImpl::init(int af) +{ + initSocket(af, SOCK_STREAM); +} + + +void SocketImpl::initSocket(int af, int type, int proto) +{ + poco_assert (_sockfd == POCO_INVALID_SOCKET); + + _sockfd = ::socket(af, type, proto); + if (_sockfd == POCO_INVALID_SOCKET) + error(); +} + + +void SocketImpl::ioctl(int request, int& arg) +{ +#if defined(_WIN32) + int rc = ioctlsocket(_sockfd, request, reinterpret_cast(&arg)); +#else + int rc = ::ioctl(_sockfd, request, &arg); +#endif + if (rc != 0) error(); +} + + +void SocketImpl::ioctl(int request, void* arg) +{ +#if defined(_WIN32) + int rc = ioctlsocket(_sockfd, request, reinterpret_cast(arg)); +#else + int rc = ::ioctl(_sockfd, request, arg); +#endif + if (rc != 0) error(); +} + + +void SocketImpl::setSockfd(poco_socket_t aSocket) +{ + poco_assert(sockfd() == POCO_INVALID_SOCKET); + _sockfd = aSocket; +} + + +void SocketImpl::error() +{ + std::string empty; + error(lastError(), empty); +} + + +void SocketImpl::error(const std::string& arg) +{ + error(lastError(), arg); +} + + +void SocketImpl::error(int code) +{ + std::string arg; + error(code, arg); +} + + +void SocketImpl::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_EINTR: + throw IOException("Interrupted"); + case POCO_EACCES: + throw IOException("Permission denied"); + case POCO_EFAULT: + throw IOException("Bad address"); + case POCO_EINVAL: + throw InvalidArgumentException(); + case POCO_EMFILE: + throw IOException("Too many open files"); + case POCO_EWOULDBLOCK: + throw IOException("Operation would block"); + case POCO_EINPROGRESS: + throw IOException("Operation now in progress"); + case POCO_EALREADY: + throw IOException("Operation already in progress"); + case POCO_ENOTSOCK: + throw IOException("Socket operation attempted on non-socket"); + case POCO_EDESTADDRREQ: + throw NetException("Destination address required"); + case POCO_EMSGSIZE: + throw NetException("Message too long"); + case POCO_EPROTOTYPE: + throw NetException("Wrong protocol type"); + case POCO_ENOPROTOOPT: + throw NetException("Protocol not available"); + case POCO_EPROTONOSUPPORT: + throw NetException("Protocol not supported"); + case POCO_ESOCKTNOSUPPORT: + throw NetException("Socket type not supported"); + case POCO_ENOTSUP: + throw NetException("Operation not supported"); + case POCO_EPFNOSUPPORT: + throw NetException("Protocol family not supported"); + case POCO_EAFNOSUPPORT: + throw NetException("Address family not supported"); + case POCO_EADDRINUSE: + throw NetException("Address already in use", arg); + case POCO_EADDRNOTAVAIL: + throw NetException("Cannot assign requested address", arg); + case POCO_ENETDOWN: + throw NetException("Network is down"); + case POCO_ENETUNREACH: + throw NetException("Network is unreachable"); + case POCO_ENETRESET: + throw NetException("Network dropped connection on reset"); + case POCO_ECONNABORTED: + throw ConnectionAbortedException(); + case POCO_ECONNRESET: + throw ConnectionResetException(); + case POCO_ENOBUFS: + throw IOException("No buffer space available"); + case POCO_EISCONN: + throw NetException("Socket is already connected"); + case POCO_ENOTCONN: + throw NetException("Socket is not connected"); + case POCO_ESHUTDOWN: + throw NetException("Cannot send after socket shutdown"); + case POCO_ETIMEDOUT: + throw TimeoutException(); + case POCO_ECONNREFUSED: + throw ConnectionRefusedException(arg); + case POCO_EHOSTDOWN: + throw NetException("Host is down"); + case POCO_EHOSTUNREACH: + throw NetException("No route to host"); + default: + throw IOException(NumberFormatter::format(code) + arg); + } +} + + +} } // namespace Poco::Net diff --git a/Net/src/SocketNotification.cpp b/Net/src/SocketNotification.cpp index b1f93ad26..4ae67df81 100644 --- a/Net/src/SocketNotification.cpp +++ b/Net/src/SocketNotification.cpp @@ -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 diff --git a/Net/src/SocketNotifier.cpp b/Net/src/SocketNotifier.cpp index ab5704045..ee4b4a009 100644 --- a/Net/src/SocketNotifier.cpp +++ b/Net/src/SocketNotifier.cpp @@ -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 diff --git a/Net/src/SocketReactor.cpp b/Net/src/SocketReactor.cpp index 45d3c6293..18fd7a702 100644 --- a/Net/src/SocketReactor.cpp +++ b/Net/src/SocketReactor.cpp @@ -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 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::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 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::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 diff --git a/Net/src/SocketStream.cpp b/Net/src/SocketStream.cpp index 5063f41ac..a099e826b 100644 --- a/Net/src/SocketStream.cpp +++ b/Net/src/SocketStream.cpp @@ -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(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(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 diff --git a/Net/src/StreamSocket.cpp b/Net/src/StreamSocket.cpp index 07114a54d..68eb2a4bc 100644 --- a/Net/src/StreamSocket.cpp +++ b/Net/src/StreamSocket.cpp @@ -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(impl())) - throw InvalidArgumentException("Cannot assign incompatible socket"); -} - - -StreamSocket::StreamSocket(SocketImpl* pImpl): Socket(pImpl) -{ - if (!dynamic_cast(impl())) - throw InvalidArgumentException("Cannot assign incompatible socket"); -} - - -StreamSocket::~StreamSocket() -{ -} - - -StreamSocket& StreamSocket::operator = (const Socket& socket) -{ - if (dynamic_cast(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(impl())) + throw InvalidArgumentException("Cannot assign incompatible socket"); +} + + +StreamSocket::StreamSocket(SocketImpl* pImpl): Socket(pImpl) +{ + if (!dynamic_cast(impl())) + throw InvalidArgumentException("Cannot assign incompatible socket"); +} + + +StreamSocket::~StreamSocket() +{ +} + + +StreamSocket& StreamSocket::operator = (const Socket& socket) +{ + if (dynamic_cast(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 diff --git a/Net/src/StreamSocketImpl.cpp b/Net/src/StreamSocketImpl.cpp index 19f1ccb3f..93c77992e 100644 --- a/Net/src/StreamSocketImpl.cpp +++ b/Net/src/StreamSocketImpl.cpp @@ -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(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(buffer); + int remaining = length; + while (remaining > 0) + { + int n = SocketImpl::sendBytes(p, length, flags); + p += n; + remaining -= n; + } + return length; +} + + +} } // namespace Poco::Net diff --git a/Net/src/StringPartSource.cpp b/Net/src/StringPartSource.cpp index f07b09259..32fc1d4d3 100644 --- a/Net/src/StringPartSource.cpp +++ b/Net/src/StringPartSource.cpp @@ -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 diff --git a/Net/src/TCPServer.cpp b/Net/src/TCPServer.cpp index bb972f03b..7f0d4de46 100644 --- a/Net/src/TCPServer.cpp +++ b/Net/src/TCPServer.cpp @@ -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 diff --git a/Net/src/TCPServerConnection.cpp b/Net/src/TCPServerConnection.cpp index 8093a6287..9546c788f 100644 --- a/Net/src/TCPServerConnection.cpp +++ b/Net/src/TCPServerConnection.cpp @@ -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 diff --git a/Net/src/TCPServerConnectionFactory.cpp b/Net/src/TCPServerConnectionFactory.cpp index 92f09a56c..02f3fd76b 100644 --- a/Net/src/TCPServerConnectionFactory.cpp +++ b/Net/src/TCPServerConnectionFactory.cpp @@ -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 diff --git a/Net/src/TCPServerDispatcher.cpp b/Net/src/TCPServerDispatcher.cpp index 70407a5de..8c3537fda 100644 --- a/Net/src/TCPServerDispatcher.cpp +++ b/Net/src/TCPServerDispatcher.cpp @@ -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 - - -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 guard(this, true); // ensure object stays alive - - int idleTime = (int) _pParams->getThreadIdleTime().totalMilliseconds(); - - for (;;) - { - AutoPtr pNf = _queue.waitDequeueNotification(idleTime); - if (pNf) - { - TCPConnectionNotification* pCNf = dynamic_cast(pNf.get()); - if (pCNf) - { - std::auto_ptr 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 + + +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 guard(this, true); // ensure object stays alive + + int idleTime = (int) _pParams->getThreadIdleTime().totalMilliseconds(); + + for (;;) + { + AutoPtr pNf = _queue.waitDequeueNotification(idleTime); + if (pNf) + { + TCPConnectionNotification* pCNf = dynamic_cast(pNf.get()); + if (pCNf) + { + std::auto_ptr 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 diff --git a/Net/src/TCPServerParams.cpp b/Net/src/TCPServerParams.cpp index 5ec8d5650..5173cac3f 100644 --- a/Net/src/TCPServerParams.cpp +++ b/Net/src/TCPServerParams.cpp @@ -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 diff --git a/Net/testsuite/Makefile b/Net/testsuite/Makefile index ec1075a65..dbe5031eb 100644 --- a/Net/testsuite/Makefile +++ b/Net/testsuite/Makefile @@ -1,33 +1,33 @@ -# -# Makefile -# -# $Id: //poco/1.2/Net/testsuite/Makefile#1 $ -# -# Makefile for Poco Net testsuite -# - -include $(POCO_BASE)/build/rules/global - -objects = \ - DNSTest HTTPServerTestSuite MulticastSocketTest SocketStreamTest \ - DatagramSocketTest HTTPStreamFactoryTest MultipartReaderTest SocketTest \ - Driver HTTPTestServer MultipartWriterTest SocketsTestSuite \ - EchoServer HTTPTestSuite NameValueCollectionTest TCPServerTest \ - HTTPClientSessionTest IPAddressTest NetCoreTestSuite TCPServerTestSuite \ - HTTPRequestTest MessageHeaderTest NetTestSuite UDPEchoServer \ - HTTPResponseTest MessagesTestSuite NetworkInterfaceTest \ - HTTPServerTest MulticastEchoServer SocketAddressTest \ - HTTPCookieTest HTTPCredentialsTest HTMLFormTest HTMLTestSuite \ - MediaTypeTest QuotedPrintableTest DialogSocketTest \ - HTTPClientTestSuite FTPClientTestSuite FTPClientSessionTest \ - FTPStreamFactoryTest DialogServer \ - SocketReactorTest ReactorTestSuite \ - MailTestSuite MailMessageTest MailStreamTest \ - SMTPClientSessionTest POP3ClientSessionTest \ - RawSocketTest ICMPClientTest ICMPSocketTest ICMPClientTestSuite - -target = testrunner -target_version = 1 -target_libs = PocoNet PocoFoundation CppUnit - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Net/testsuite/Makefile#1 $ +# +# Makefile for Poco Net testsuite +# + +include $(POCO_BASE)/build/rules/global + +objects = \ + DNSTest HTTPServerTestSuite MulticastSocketTest SocketStreamTest \ + DatagramSocketTest HTTPStreamFactoryTest MultipartReaderTest SocketTest \ + Driver HTTPTestServer MultipartWriterTest SocketsTestSuite \ + EchoServer HTTPTestSuite NameValueCollectionTest TCPServerTest \ + HTTPClientSessionTest IPAddressTest NetCoreTestSuite TCPServerTestSuite \ + HTTPRequestTest MessageHeaderTest NetTestSuite UDPEchoServer \ + HTTPResponseTest MessagesTestSuite NetworkInterfaceTest \ + HTTPServerTest MulticastEchoServer SocketAddressTest \ + HTTPCookieTest HTTPCredentialsTest HTMLFormTest HTMLTestSuite \ + MediaTypeTest QuotedPrintableTest DialogSocketTest \ + HTTPClientTestSuite FTPClientTestSuite FTPClientSessionTest \ + FTPStreamFactoryTest DialogServer \ + SocketReactorTest ReactorTestSuite \ + MailTestSuite MailMessageTest MailStreamTest \ + SMTPClientSessionTest POP3ClientSessionTest \ + RawSocketTest ICMPClientTest ICMPSocketTest ICMPClientTestSuite + +target = testrunner +target_version = 1 +target_libs = PocoNet PocoFoundation CppUnit + +include $(POCO_BASE)/build/rules/exec diff --git a/Net/testsuite/TestSuite.vmsbuild b/Net/testsuite/TestSuite.vmsbuild index 64b415679..e75753043 100644 --- a/Net/testsuite/TestSuite.vmsbuild +++ b/Net/testsuite/TestSuite.vmsbuild @@ -1,9 +1,9 @@ -# -# TestSuite.vmsbuild -# -# $Id: //poco/1.2/Net/testsuite/TestSuite.vmsbuild#1 $ -# -EXE=TestRunner -NetTestSuite -Driver - +# +# TestSuite.vmsbuild +# +# $Id: //poco/1.2/Net/testsuite/TestSuite.vmsbuild#1 $ +# +EXE=TestRunner +NetTestSuite +Driver + diff --git a/Net/testsuite/TestSuite_vs71.vcproj b/Net/testsuite/TestSuite_vs71.vcproj index 998434d80..3d9d6e78a 100644 --- a/Net/testsuite/TestSuite_vs71.vcproj +++ b/Net/testsuite/TestSuite_vs71.vcproj @@ -1,617 +1,617 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/testsuite/TestSuite_vs80.vcproj b/Net/testsuite/TestSuite_vs80.vcproj index 9133ae711..f43b8c032 100644 --- a/Net/testsuite/TestSuite_vs80.vcproj +++ b/Net/testsuite/TestSuite_vs80.vcproj @@ -1,785 +1,785 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Net/testsuite/src/DNSTest.cpp b/Net/testsuite/src/DNSTest.cpp index 0769033d4..7e01bc2ef 100644 --- a/Net/testsuite/src/DNSTest.cpp +++ b/Net/testsuite/src/DNSTest.cpp @@ -1,131 +1,131 @@ -// -// DNSTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/DNSTest.cpp#1 $ -// -// 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 "DNSTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/DNS.h" -#include "Poco/Net/HostEntry.h" -#include "Poco/Net/NetException.h" - - -using Poco::Net::DNS; -using Poco::Net::IPAddress; -using Poco::Net::HostEntry; -using Poco::Net::InvalidAddressException; -using Poco::Net::HostNotFoundException; -using Poco::Net::ServiceNotFoundException; -using Poco::Net::NoAddressFoundException; - - -DNSTest::DNSTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -DNSTest::~DNSTest() -{ -} - - -void DNSTest::testHostByName() -{ - HostEntry he1 = DNS::hostByName("www.appinf.com"); - assert (he1.name() == "appinf.com"); - assert (!he1.aliases().empty()); - assert (he1.aliases()[0] == "www.appinf.com"); - assert (he1.addresses().size() == 1); - assert (he1.addresses()[0].toString() == "213.229.60.82"); - - try - { - HostEntry he1 = DNS::hostByName("nohost.appinf.com"); - fail("host not found - must throw"); - } - catch (HostNotFoundException&) - { - } - catch (NoAddressFoundException&) - { - } -} - - -void DNSTest::testHostByAddress() -{ - IPAddress ip1("213.229.60.82"); - HostEntry he1 = DNS::hostByAddress(ip1); - assert (he1.name() == "quentin.inode.at"); - assert (he1.aliases().empty()); - assert (he1.addresses().size() == 1); - assert (he1.addresses()[0].toString() == "213.229.60.82"); - - IPAddress ip2("10.0.244.253"); - try - { - HostEntry he2 = DNS::hostByAddress(ip2); - fail("host not found - must throw"); - } - catch (HostNotFoundException&) - { - } - catch (NoAddressFoundException&) - { - } -} - - -void DNSTest::testResolve() -{ -} - - -void DNSTest::setUp() -{ -} - - -void DNSTest::tearDown() -{ -} - - -CppUnit::Test* DNSTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DNSTest"); - - CppUnit_addTest(pSuite, DNSTest, testHostByName); - CppUnit_addTest(pSuite, DNSTest, testHostByAddress); - CppUnit_addTest(pSuite, DNSTest, testResolve); - - return pSuite; -} +// +// DNSTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/DNSTest.cpp#1 $ +// +// 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 "DNSTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/DNS.h" +#include "Poco/Net/HostEntry.h" +#include "Poco/Net/NetException.h" + + +using Poco::Net::DNS; +using Poco::Net::IPAddress; +using Poco::Net::HostEntry; +using Poco::Net::InvalidAddressException; +using Poco::Net::HostNotFoundException; +using Poco::Net::ServiceNotFoundException; +using Poco::Net::NoAddressFoundException; + + +DNSTest::DNSTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DNSTest::~DNSTest() +{ +} + + +void DNSTest::testHostByName() +{ + HostEntry he1 = DNS::hostByName("www.appinf.com"); + assert (he1.name() == "appinf.com"); + assert (!he1.aliases().empty()); + assert (he1.aliases()[0] == "www.appinf.com"); + assert (he1.addresses().size() == 1); + assert (he1.addresses()[0].toString() == "213.229.60.82"); + + try + { + HostEntry he1 = DNS::hostByName("nohost.appinf.com"); + fail("host not found - must throw"); + } + catch (HostNotFoundException&) + { + } + catch (NoAddressFoundException&) + { + } +} + + +void DNSTest::testHostByAddress() +{ + IPAddress ip1("213.229.60.82"); + HostEntry he1 = DNS::hostByAddress(ip1); + assert (he1.name() == "quentin.inode.at"); + assert (he1.aliases().empty()); + assert (he1.addresses().size() == 1); + assert (he1.addresses()[0].toString() == "213.229.60.82"); + + IPAddress ip2("10.0.244.253"); + try + { + HostEntry he2 = DNS::hostByAddress(ip2); + fail("host not found - must throw"); + } + catch (HostNotFoundException&) + { + } + catch (NoAddressFoundException&) + { + } +} + + +void DNSTest::testResolve() +{ +} + + +void DNSTest::setUp() +{ +} + + +void DNSTest::tearDown() +{ +} + + +CppUnit::Test* DNSTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DNSTest"); + + CppUnit_addTest(pSuite, DNSTest, testHostByName); + CppUnit_addTest(pSuite, DNSTest, testHostByAddress); + CppUnit_addTest(pSuite, DNSTest, testResolve); + + return pSuite; +} diff --git a/Net/testsuite/src/DNSTest.h b/Net/testsuite/src/DNSTest.h index 4f14e039c..a203a4ca7 100644 --- a/Net/testsuite/src/DNSTest.h +++ b/Net/testsuite/src/DNSTest.h @@ -1,62 +1,62 @@ -// -// DNSTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/DNSTest.h#1 $ -// -// Definition of the DNSTest 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 DNSTest_INCLUDED -#define DNSTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class DNSTest: public CppUnit::TestCase -{ -public: - DNSTest(const std::string& name); - ~DNSTest(); - - void testHostByName(); - void testHostByAddress(); - void testResolve(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // DNSTest_INCLUDED +// +// DNSTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/DNSTest.h#1 $ +// +// Definition of the DNSTest 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 DNSTest_INCLUDED +#define DNSTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class DNSTest: public CppUnit::TestCase +{ +public: + DNSTest(const std::string& name); + ~DNSTest(); + + void testHostByName(); + void testHostByAddress(); + void testResolve(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // DNSTest_INCLUDED diff --git a/Net/testsuite/src/DatagramSocketTest.cpp b/Net/testsuite/src/DatagramSocketTest.cpp index 6ea8c1888..cce795941 100644 --- a/Net/testsuite/src/DatagramSocketTest.cpp +++ b/Net/testsuite/src/DatagramSocketTest.cpp @@ -1,141 +1,141 @@ -// -// DatagramSocketTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/DatagramSocketTest.cpp#1 $ -// -// 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 "DatagramSocketTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "UDPEchoServer.h" -#include "Poco/Net/DatagramSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/Timespan.h" -#include "Poco/Stopwatch.h" - - -using Poco::Net::Socket; -using Poco::Net::DatagramSocket; -using Poco::Net::SocketAddress; -using Poco::Net::IPAddress; -using Poco::Timespan; -using Poco::Stopwatch; -using Poco::TimeoutException; -using Poco::InvalidArgumentException; -using Poco::IOException; - - -DatagramSocketTest::DatagramSocketTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -DatagramSocketTest::~DatagramSocketTest() -{ -} - - -void DatagramSocketTest::testEcho() -{ - UDPEchoServer echoServer; - DatagramSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - int n = ss.sendBytes("hello", 5); - assert (n == 5); - char buffer[256]; - n = ss.receiveBytes(buffer, sizeof(buffer)); - assert (n == 5); - assert (std::string(buffer, n) == "hello"); - ss.close(); -} - - -void DatagramSocketTest::testSendToReceiveFrom() -{ - UDPEchoServer echoServer(SocketAddress("localhost", 0)); - DatagramSocket ss; - int n = ss.sendTo("hello", 5, SocketAddress("localhost", echoServer.port())); - assert (n == 5); - char buffer[256]; - SocketAddress sa; - n = ss.receiveFrom(buffer, sizeof(buffer), sa); - assert (sa.host() == echoServer.address().host()); - assert (sa.port() == echoServer.port()); - assert (n == 5); - assert (std::string(buffer, n) == "hello"); - ss.close(); -} - - -void DatagramSocketTest::testBroadcast() -{ - UDPEchoServer echoServer; - DatagramSocket ss(IPAddress::IPv4); - SocketAddress sa("255.255.255.255", echoServer.port()); - try - { - int n = ss.sendTo("hello", 5, sa); - // not all socket implementations fail if broadcast option is not set - // fail ("broadcast option not set - must throw"); - } - catch (IOException&) - { - } - ss.setBroadcast(true); - int n = ss.sendTo("hello", 5, sa); - assert (n == 5); - char buffer[256]; - n = ss.receiveBytes(buffer, sizeof(buffer)); - assert (n == 5); - assert (std::string(buffer, n) == "hello"); - ss.close(); -} - - -void DatagramSocketTest::setUp() -{ -} - - -void DatagramSocketTest::tearDown() -{ -} - - -CppUnit::Test* DatagramSocketTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DatagramSocketTest"); - - CppUnit_addTest(pSuite, DatagramSocketTest, testEcho); - CppUnit_addTest(pSuite, DatagramSocketTest, testSendToReceiveFrom); - CppUnit_addTest(pSuite, DatagramSocketTest, testBroadcast); - - return pSuite; -} +// +// DatagramSocketTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/DatagramSocketTest.cpp#1 $ +// +// 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 "DatagramSocketTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "UDPEchoServer.h" +#include "Poco/Net/DatagramSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/Timespan.h" +#include "Poco/Stopwatch.h" + + +using Poco::Net::Socket; +using Poco::Net::DatagramSocket; +using Poco::Net::SocketAddress; +using Poco::Net::IPAddress; +using Poco::Timespan; +using Poco::Stopwatch; +using Poco::TimeoutException; +using Poco::InvalidArgumentException; +using Poco::IOException; + + +DatagramSocketTest::DatagramSocketTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DatagramSocketTest::~DatagramSocketTest() +{ +} + + +void DatagramSocketTest::testEcho() +{ + UDPEchoServer echoServer; + DatagramSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + int n = ss.sendBytes("hello", 5); + assert (n == 5); + char buffer[256]; + n = ss.receiveBytes(buffer, sizeof(buffer)); + assert (n == 5); + assert (std::string(buffer, n) == "hello"); + ss.close(); +} + + +void DatagramSocketTest::testSendToReceiveFrom() +{ + UDPEchoServer echoServer(SocketAddress("localhost", 0)); + DatagramSocket ss; + int n = ss.sendTo("hello", 5, SocketAddress("localhost", echoServer.port())); + assert (n == 5); + char buffer[256]; + SocketAddress sa; + n = ss.receiveFrom(buffer, sizeof(buffer), sa); + assert (sa.host() == echoServer.address().host()); + assert (sa.port() == echoServer.port()); + assert (n == 5); + assert (std::string(buffer, n) == "hello"); + ss.close(); +} + + +void DatagramSocketTest::testBroadcast() +{ + UDPEchoServer echoServer; + DatagramSocket ss(IPAddress::IPv4); + SocketAddress sa("255.255.255.255", echoServer.port()); + try + { + int n = ss.sendTo("hello", 5, sa); + // not all socket implementations fail if broadcast option is not set + // fail ("broadcast option not set - must throw"); + } + catch (IOException&) + { + } + ss.setBroadcast(true); + int n = ss.sendTo("hello", 5, sa); + assert (n == 5); + char buffer[256]; + n = ss.receiveBytes(buffer, sizeof(buffer)); + assert (n == 5); + assert (std::string(buffer, n) == "hello"); + ss.close(); +} + + +void DatagramSocketTest::setUp() +{ +} + + +void DatagramSocketTest::tearDown() +{ +} + + +CppUnit::Test* DatagramSocketTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DatagramSocketTest"); + + CppUnit_addTest(pSuite, DatagramSocketTest, testEcho); + CppUnit_addTest(pSuite, DatagramSocketTest, testSendToReceiveFrom); + CppUnit_addTest(pSuite, DatagramSocketTest, testBroadcast); + + return pSuite; +} diff --git a/Net/testsuite/src/DatagramSocketTest.h b/Net/testsuite/src/DatagramSocketTest.h index 46f82dbd4..1a9a5c393 100644 --- a/Net/testsuite/src/DatagramSocketTest.h +++ b/Net/testsuite/src/DatagramSocketTest.h @@ -1,62 +1,62 @@ -// -// DatagramSocketTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/DatagramSocketTest.h#1 $ -// -// Definition of the DatagramSocketTest 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 DatagramSocketTest_INCLUDED -#define DatagramSocketTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class DatagramSocketTest: public CppUnit::TestCase -{ -public: - DatagramSocketTest(const std::string& name); - ~DatagramSocketTest(); - - void testEcho(); - void testSendToReceiveFrom(); - void testBroadcast(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // DatagramSocketTest_INCLUDED +// +// DatagramSocketTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/DatagramSocketTest.h#1 $ +// +// Definition of the DatagramSocketTest 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 DatagramSocketTest_INCLUDED +#define DatagramSocketTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class DatagramSocketTest: public CppUnit::TestCase +{ +public: + DatagramSocketTest(const std::string& name); + ~DatagramSocketTest(); + + void testEcho(); + void testSendToReceiveFrom(); + void testBroadcast(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // DatagramSocketTest_INCLUDED diff --git a/Net/testsuite/src/DialogServer.cpp b/Net/testsuite/src/DialogServer.cpp index 56c669cf1..9ea08c2be 100644 --- a/Net/testsuite/src/DialogServer.cpp +++ b/Net/testsuite/src/DialogServer.cpp @@ -1,190 +1,190 @@ -// -// DialogServer.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/DialogServer.cpp#1 $ -// -// 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 "DialogServer.h" -#include "Poco/Net/DialogSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Timespan.h" -#include - - -using Poco::Net::Socket; -using Poco::Net::DialogSocket; -using Poco::Net::SocketAddress; -using Poco::FastMutex; -using Poco::Thread; - - -DialogServer::DialogServer(bool acceptCommands): - _socket(SocketAddress()), - _thread("DialogServer"), - _stop(false), - _acceptCommands(acceptCommands), - _log(false) -{ - _thread.start(*this); - _ready.wait(); -} - - -DialogServer::~DialogServer() -{ - _stop = true; - _thread.join(); -} - - -Poco::UInt16 DialogServer::port() const -{ - return _socket.address().port(); -} - - -void DialogServer::run() -{ - _ready.set(); - Poco::Timespan span(250000); - while (!_stop) - { - if (_socket.poll(span, Socket::SELECT_READ)) - { - DialogSocket ds = _socket.acceptConnection(); - { - FastMutex::ScopedLock lock(_mutex); - if (!_nextResponses.empty()) - { - ds.sendMessage(_nextResponses.front()); - _nextResponses.erase(_nextResponses.begin()); - } - } - if (_acceptCommands) - { - try - { - std::string command; - while (ds.receiveMessage(command)) - { - if (_log) std::cout << ">> " << command << std::endl; - { - FastMutex::ScopedLock lock(_mutex); - _lastCommands.push_back(command); - if (!_nextResponses.empty()) - { - if (_log) std::cout << "<< " << _nextResponses.front() << std::endl; - ds.sendMessage(_nextResponses.front()); - _nextResponses.erase(_nextResponses.begin()); - } - } - } - } - catch (Poco::Exception& exc) - { - std::cerr << "DialogServer: " << exc.displayText() << std::endl; - } - } - } - } -} - - -const std::string& DialogServer::lastCommand() const -{ - FastMutex::ScopedLock lock(_mutex); - - static const std::string EMPTY; - if (_lastCommands.empty()) - return EMPTY; - else - return _lastCommands.back(); -} - - -const std::vector& DialogServer::lastCommands() const -{ - return _lastCommands; -} - - -std::string DialogServer::popCommand() -{ - FastMutex::ScopedLock lock(_mutex); - - std::string command; - if (!_lastCommands.empty()) - { - command = _lastCommands.front(); - _lastCommands.erase(_lastCommands.begin()); - } - return command; -} - - -std::string DialogServer::popCommandWait() -{ - std::string result(popCommand()); - while (result.empty()) - { - Thread::sleep(100); - result = popCommand(); - } - return result; -} - - -void DialogServer::addResponse(const std::string& response) -{ - FastMutex::ScopedLock lock(_mutex); - - _nextResponses.push_back(response); -} - - -void DialogServer::clearCommands() -{ - FastMutex::ScopedLock lock(_mutex); - - _lastCommands.clear(); -} - - -void DialogServer::clearResponses() -{ - FastMutex::ScopedLock lock(_mutex); - - _nextResponses.clear(); -} - - -void DialogServer::log(bool flag) -{ - _log = flag; -} +// +// DialogServer.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/DialogServer.cpp#1 $ +// +// 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 "DialogServer.h" +#include "Poco/Net/DialogSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Timespan.h" +#include + + +using Poco::Net::Socket; +using Poco::Net::DialogSocket; +using Poco::Net::SocketAddress; +using Poco::FastMutex; +using Poco::Thread; + + +DialogServer::DialogServer(bool acceptCommands): + _socket(SocketAddress()), + _thread("DialogServer"), + _stop(false), + _acceptCommands(acceptCommands), + _log(false) +{ + _thread.start(*this); + _ready.wait(); +} + + +DialogServer::~DialogServer() +{ + _stop = true; + _thread.join(); +} + + +Poco::UInt16 DialogServer::port() const +{ + return _socket.address().port(); +} + + +void DialogServer::run() +{ + _ready.set(); + Poco::Timespan span(250000); + while (!_stop) + { + if (_socket.poll(span, Socket::SELECT_READ)) + { + DialogSocket ds = _socket.acceptConnection(); + { + FastMutex::ScopedLock lock(_mutex); + if (!_nextResponses.empty()) + { + ds.sendMessage(_nextResponses.front()); + _nextResponses.erase(_nextResponses.begin()); + } + } + if (_acceptCommands) + { + try + { + std::string command; + while (ds.receiveMessage(command)) + { + if (_log) std::cout << ">> " << command << std::endl; + { + FastMutex::ScopedLock lock(_mutex); + _lastCommands.push_back(command); + if (!_nextResponses.empty()) + { + if (_log) std::cout << "<< " << _nextResponses.front() << std::endl; + ds.sendMessage(_nextResponses.front()); + _nextResponses.erase(_nextResponses.begin()); + } + } + } + } + catch (Poco::Exception& exc) + { + std::cerr << "DialogServer: " << exc.displayText() << std::endl; + } + } + } + } +} + + +const std::string& DialogServer::lastCommand() const +{ + FastMutex::ScopedLock lock(_mutex); + + static const std::string EMPTY; + if (_lastCommands.empty()) + return EMPTY; + else + return _lastCommands.back(); +} + + +const std::vector& DialogServer::lastCommands() const +{ + return _lastCommands; +} + + +std::string DialogServer::popCommand() +{ + FastMutex::ScopedLock lock(_mutex); + + std::string command; + if (!_lastCommands.empty()) + { + command = _lastCommands.front(); + _lastCommands.erase(_lastCommands.begin()); + } + return command; +} + + +std::string DialogServer::popCommandWait() +{ + std::string result(popCommand()); + while (result.empty()) + { + Thread::sleep(100); + result = popCommand(); + } + return result; +} + + +void DialogServer::addResponse(const std::string& response) +{ + FastMutex::ScopedLock lock(_mutex); + + _nextResponses.push_back(response); +} + + +void DialogServer::clearCommands() +{ + FastMutex::ScopedLock lock(_mutex); + + _lastCommands.clear(); +} + + +void DialogServer::clearResponses() +{ + FastMutex::ScopedLock lock(_mutex); + + _nextResponses.clear(); +} + + +void DialogServer::log(bool flag) +{ + _log = flag; +} diff --git a/Net/testsuite/src/DialogServer.h b/Net/testsuite/src/DialogServer.h index 641f86db0..e874b2bdf 100644 --- a/Net/testsuite/src/DialogServer.h +++ b/Net/testsuite/src/DialogServer.h @@ -1,103 +1,103 @@ -// -// DialogServer.h -// -// $Id: //poco/1.2/Net/testsuite/src/DialogServer.h#1 $ -// -// Definition of the DialogServer 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 DialogServer_INCLUDED -#define DialogServer_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" -#include "Poco/Mutex.h" -#include - - -class DialogServer: public Poco::Runnable - /// A server for testing FTPClientSession and friends. -{ -public: - DialogServer(bool acceptCommands = true); - /// Creates the DialogServer. - - ~DialogServer(); - /// Destroys the DialogServer. - - Poco::UInt16 port() const; - /// Returns the port the echo server is - /// listening on. - - void run(); - /// Does the work. - - const std::string& lastCommand() const; - /// Returns the last command received by the server. - - std::string popCommand(); - /// Pops the next command from the list of received commands. - - std::string popCommandWait(); - /// Pops the next command from the list of received commands. - /// Waits until a command is available. - - const std::vector& lastCommands() const; - /// Returns the last command received by the server. - - void addResponse(const std::string& response); - /// Sets the next response returned by the server. - - void clearCommands(); - /// Clears all commands. - - void clearResponses(); - /// Clears all responses. - - void log(bool flag); - /// Enables or disables logging to stdout. - -private: - Poco::Net::ServerSocket _socket; - Poco::Thread _thread; - Poco::Event _ready; - mutable Poco::FastMutex _mutex; - bool _stop; - std::vector _nextResponses; - std::vector _lastCommands; - bool _acceptCommands; - bool _log; -}; - - -#endif // DialogServer_INCLUDED +// +// DialogServer.h +// +// $Id: //poco/1.2/Net/testsuite/src/DialogServer.h#1 $ +// +// Definition of the DialogServer 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 DialogServer_INCLUDED +#define DialogServer_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" +#include "Poco/Mutex.h" +#include + + +class DialogServer: public Poco::Runnable + /// A server for testing FTPClientSession and friends. +{ +public: + DialogServer(bool acceptCommands = true); + /// Creates the DialogServer. + + ~DialogServer(); + /// Destroys the DialogServer. + + Poco::UInt16 port() const; + /// Returns the port the echo server is + /// listening on. + + void run(); + /// Does the work. + + const std::string& lastCommand() const; + /// Returns the last command received by the server. + + std::string popCommand(); + /// Pops the next command from the list of received commands. + + std::string popCommandWait(); + /// Pops the next command from the list of received commands. + /// Waits until a command is available. + + const std::vector& lastCommands() const; + /// Returns the last command received by the server. + + void addResponse(const std::string& response); + /// Sets the next response returned by the server. + + void clearCommands(); + /// Clears all commands. + + void clearResponses(); + /// Clears all responses. + + void log(bool flag); + /// Enables or disables logging to stdout. + +private: + Poco::Net::ServerSocket _socket; + Poco::Thread _thread; + Poco::Event _ready; + mutable Poco::FastMutex _mutex; + bool _stop; + std::vector _nextResponses; + std::vector _lastCommands; + bool _acceptCommands; + bool _log; +}; + + +#endif // DialogServer_INCLUDED diff --git a/Net/testsuite/src/DialogSocketTest.cpp b/Net/testsuite/src/DialogSocketTest.cpp index 6a2b5743a..649bec771 100644 --- a/Net/testsuite/src/DialogSocketTest.cpp +++ b/Net/testsuite/src/DialogSocketTest.cpp @@ -1,117 +1,117 @@ -// -// DialogSocketTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/DialogSocketTest.cpp#1 $ -// -// 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 "DialogSocketTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "EchoServer.h" -#include "Poco/Net/DialogSocket.h" -#include "Poco/Net/SocketAddress.h" - - -using Poco::Net::DialogSocket; -using Poco::Net::SocketAddress; - - -DialogSocketTest::DialogSocketTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -DialogSocketTest::~DialogSocketTest() -{ -} - - -void DialogSocketTest::testDialogSocket() -{ - EchoServer echoServer; - DialogSocket ds; - ds.connect(SocketAddress("localhost", echoServer.port())); - - ds.sendMessage("Hello, world!"); - std::string str; - ds.receiveMessage(str); - assert (str == "Hello, world!"); - - ds.sendString("Hello, World!\n"); - ds.receiveMessage(str); - assert (str == "Hello, World!"); - - ds.sendMessage("EHLO", "appinf.com"); - ds.receiveMessage(str); - assert (str == "EHLO appinf.com"); - - ds.sendMessage("PUT", "local.txt", "remote.txt"); - ds.receiveMessage(str); - assert (str == "PUT local.txt remote.txt"); - - ds.sendMessage("220 Hello, world!"); - int status = ds.receiveStatusMessage(str); - assert (status == 220); - assert (str == "220 Hello, world!"); - - ds.sendString("220-line1\r\n220 line2\r\n"); - status = ds.receiveStatusMessage(str); - assert (status == 220); - assert (str == "220-line1\n220 line2"); - - ds.sendString("220-line1\r\nline2\r\n220 line3\r\n"); - status = ds.receiveStatusMessage(str); - assert (status == 220); - assert (str == "220-line1\nline2\n220 line3"); - - ds.sendMessage("Hello, world!"); - status = ds.receiveStatusMessage(str); - assert (status == 0); - assert (str == "Hello, world!"); -} - - -void DialogSocketTest::setUp() -{ -} - - -void DialogSocketTest::tearDown() -{ -} - - -CppUnit::Test* DialogSocketTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DialogSocketTest"); - - CppUnit_addTest(pSuite, DialogSocketTest, testDialogSocket); - - return pSuite; -} +// +// DialogSocketTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/DialogSocketTest.cpp#1 $ +// +// 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 "DialogSocketTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "EchoServer.h" +#include "Poco/Net/DialogSocket.h" +#include "Poco/Net/SocketAddress.h" + + +using Poco::Net::DialogSocket; +using Poco::Net::SocketAddress; + + +DialogSocketTest::DialogSocketTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DialogSocketTest::~DialogSocketTest() +{ +} + + +void DialogSocketTest::testDialogSocket() +{ + EchoServer echoServer; + DialogSocket ds; + ds.connect(SocketAddress("localhost", echoServer.port())); + + ds.sendMessage("Hello, world!"); + std::string str; + ds.receiveMessage(str); + assert (str == "Hello, world!"); + + ds.sendString("Hello, World!\n"); + ds.receiveMessage(str); + assert (str == "Hello, World!"); + + ds.sendMessage("EHLO", "appinf.com"); + ds.receiveMessage(str); + assert (str == "EHLO appinf.com"); + + ds.sendMessage("PUT", "local.txt", "remote.txt"); + ds.receiveMessage(str); + assert (str == "PUT local.txt remote.txt"); + + ds.sendMessage("220 Hello, world!"); + int status = ds.receiveStatusMessage(str); + assert (status == 220); + assert (str == "220 Hello, world!"); + + ds.sendString("220-line1\r\n220 line2\r\n"); + status = ds.receiveStatusMessage(str); + assert (status == 220); + assert (str == "220-line1\n220 line2"); + + ds.sendString("220-line1\r\nline2\r\n220 line3\r\n"); + status = ds.receiveStatusMessage(str); + assert (status == 220); + assert (str == "220-line1\nline2\n220 line3"); + + ds.sendMessage("Hello, world!"); + status = ds.receiveStatusMessage(str); + assert (status == 0); + assert (str == "Hello, world!"); +} + + +void DialogSocketTest::setUp() +{ +} + + +void DialogSocketTest::tearDown() +{ +} + + +CppUnit::Test* DialogSocketTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DialogSocketTest"); + + CppUnit_addTest(pSuite, DialogSocketTest, testDialogSocket); + + return pSuite; +} diff --git a/Net/testsuite/src/DialogSocketTest.h b/Net/testsuite/src/DialogSocketTest.h index 16e635eae..5cb5d3c80 100644 --- a/Net/testsuite/src/DialogSocketTest.h +++ b/Net/testsuite/src/DialogSocketTest.h @@ -1,60 +1,60 @@ -// -// DialogSocketTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/DialogSocketTest.h#1 $ -// -// Definition of the DialogSocketTest 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 DialogSocketTest_INCLUDED -#define DialogSocketTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class DialogSocketTest: public CppUnit::TestCase -{ -public: - DialogSocketTest(const std::string& name); - ~DialogSocketTest(); - - void testDialogSocket(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // DialogSocketTest_INCLUDED +// +// DialogSocketTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/DialogSocketTest.h#1 $ +// +// Definition of the DialogSocketTest 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 DialogSocketTest_INCLUDED +#define DialogSocketTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class DialogSocketTest: public CppUnit::TestCase +{ +public: + DialogSocketTest(const std::string& name); + ~DialogSocketTest(); + + void testDialogSocket(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // DialogSocketTest_INCLUDED diff --git a/Net/testsuite/src/Driver.cpp b/Net/testsuite/src/Driver.cpp index f08078e91..2a99cae30 100644 --- a/Net/testsuite/src/Driver.cpp +++ b/Net/testsuite/src/Driver.cpp @@ -1,39 +1,39 @@ -// -// Driver.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/Driver.cpp#1 $ -// -// Console-based test driver for Poco Net. -// -// 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 "CppUnit/TestRunner.h" -#include "NetTestSuite.h" - - -CppUnitMain(NetTestSuite) +// +// Driver.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/Driver.cpp#1 $ +// +// Console-based test driver for Poco Net. +// +// 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 "CppUnit/TestRunner.h" +#include "NetTestSuite.h" + + +CppUnitMain(NetTestSuite) diff --git a/Net/testsuite/src/EchoServer.cpp b/Net/testsuite/src/EchoServer.cpp index 1f093fcde..7287c8697 100644 --- a/Net/testsuite/src/EchoServer.cpp +++ b/Net/testsuite/src/EchoServer.cpp @@ -1,94 +1,94 @@ -// -// EchoServer.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/EchoServer.cpp#1 $ -// -// 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 "EchoServer.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Timespan.h" -#include - - -using Poco::Net::Socket; -using Poco::Net::StreamSocket; -using Poco::Net::SocketAddress; - - -EchoServer::EchoServer(): - _socket(SocketAddress()), - _thread("EchoServer"), - _stop(false) -{ - _thread.start(*this); - _ready.wait(); -} - - -EchoServer::~EchoServer() -{ - _stop = true; - _thread.join(); -} - - -Poco::UInt16 EchoServer::port() const -{ - return _socket.address().port(); -} - - -void EchoServer::run() -{ - _ready.set(); - Poco::Timespan span(250000); - while (!_stop) - { - if (_socket.poll(span, Socket::SELECT_READ)) - { - StreamSocket ss = _socket.acceptConnection(); - try - { - char buffer[256]; - int n = ss.receiveBytes(buffer, sizeof(buffer)); - while (n > 0 && !_stop) - { - ss.sendBytes(buffer, n); - n = ss.receiveBytes(buffer, sizeof(buffer)); - } - } - catch (Poco::Exception& exc) - { - std::cerr << "EchoServer: " << exc.displayText() << std::endl; - } - } - } -} - +// +// EchoServer.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/EchoServer.cpp#1 $ +// +// 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 "EchoServer.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Timespan.h" +#include + + +using Poco::Net::Socket; +using Poco::Net::StreamSocket; +using Poco::Net::SocketAddress; + + +EchoServer::EchoServer(): + _socket(SocketAddress()), + _thread("EchoServer"), + _stop(false) +{ + _thread.start(*this); + _ready.wait(); +} + + +EchoServer::~EchoServer() +{ + _stop = true; + _thread.join(); +} + + +Poco::UInt16 EchoServer::port() const +{ + return _socket.address().port(); +} + + +void EchoServer::run() +{ + _ready.set(); + Poco::Timespan span(250000); + while (!_stop) + { + if (_socket.poll(span, Socket::SELECT_READ)) + { + StreamSocket ss = _socket.acceptConnection(); + try + { + char buffer[256]; + int n = ss.receiveBytes(buffer, sizeof(buffer)); + while (n > 0 && !_stop) + { + ss.sendBytes(buffer, n); + n = ss.receiveBytes(buffer, sizeof(buffer)); + } + } + catch (Poco::Exception& exc) + { + std::cerr << "EchoServer: " << exc.displayText() << std::endl; + } + } + } +} + diff --git a/Net/testsuite/src/EchoServer.h b/Net/testsuite/src/EchoServer.h index 53d9648b4..23ed92fff 100644 --- a/Net/testsuite/src/EchoServer.h +++ b/Net/testsuite/src/EchoServer.h @@ -1,70 +1,70 @@ -// -// EchoServer.h -// -// $Id: //poco/1.2/Net/testsuite/src/EchoServer.h#1 $ -// -// Definition of the EchoServer 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 EchoServer_INCLUDED -#define EchoServer_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" - - -class EchoServer: public Poco::Runnable - /// A simple sequential echo server. -{ -public: - EchoServer(); - /// Creates the EchoServer. - - ~EchoServer(); - /// Destroys the EchoServer. - - Poco::UInt16 port() const; - /// Returns the port the echo server is - /// listening on. - - void run(); - /// Does the work. - -private: - Poco::Net::ServerSocket _socket; - Poco::Thread _thread; - Poco::Event _ready; - bool _stop; -}; - - -#endif // EchoServer_INCLUDED +// +// EchoServer.h +// +// $Id: //poco/1.2/Net/testsuite/src/EchoServer.h#1 $ +// +// Definition of the EchoServer 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 EchoServer_INCLUDED +#define EchoServer_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" + + +class EchoServer: public Poco::Runnable + /// A simple sequential echo server. +{ +public: + EchoServer(); + /// Creates the EchoServer. + + ~EchoServer(); + /// Destroys the EchoServer. + + Poco::UInt16 port() const; + /// Returns the port the echo server is + /// listening on. + + void run(); + /// Does the work. + +private: + Poco::Net::ServerSocket _socket; + Poco::Thread _thread; + Poco::Event _ready; + bool _stop; +}; + + +#endif // EchoServer_INCLUDED diff --git a/Net/testsuite/src/FTPClientSessionTest.cpp b/Net/testsuite/src/FTPClientSessionTest.cpp index 2f9a1d902..1a6917248 100644 --- a/Net/testsuite/src/FTPClientSessionTest.cpp +++ b/Net/testsuite/src/FTPClientSessionTest.cpp @@ -1,550 +1,550 @@ -// -// FTPClientSessionTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/FTPClientSessionTest.cpp#1 $ -// -// 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 "FTPClientSessionTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "DialogServer.h" -#include "Poco/Net/FTPClientSession.h" -#include "Poco/Net/DialogSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/Thread.h" -#include "Poco/ActiveMethod.h" -#include "Poco/StreamCopier.h" -#include - - -using Poco::Net::FTPClientSession; -using Poco::Net::DialogSocket; -using Poco::Net::SocketAddress; -using Poco::Net::FTPException; -using Poco::ActiveMethod; -using Poco::ActiveResult; -using Poco::StreamCopier; -using Poco::Thread; - - -namespace -{ - class ActiveDownloader - { - public: - ActiveDownloader(FTPClientSession& session): - download(this, &ActiveDownloader::downloadImp), - _session(session) - { - } - - ActiveMethod download; - - protected: - std::string downloadImp(const std::string& path) - { - std::istream& istr = _session.beginDownload(path); - std::ostringstream ostr; - StreamCopier::copyStream(istr, ostr); - _session.endDownload(); - return ostr.str(); - } - - private: - FTPClientSession& _session; - }; -}; - - -FTPClientSessionTest::FTPClientSessionTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -FTPClientSessionTest::~FTPClientSessionTest() -{ -} - - -void FTPClientSessionTest::testLogin() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - FTPClientSession session("localhost", server.port()); - session.login("user", "password"); - std::string cmd = server.popCommand(); - assert (cmd == "USER user"); - cmd = server.popCommand(); - assert (cmd == "PASS password"); - cmd = server.popCommand(); - assert (cmd == "TYPE I"); - - assert (session.getFileType() == FTPClientSession::TYPE_BINARY); - - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testLoginFailed1() -{ - DialogServer server; - server.addResponse("421 localhost FTP not ready"); - FTPClientSession session("localhost", server.port()); - try - { - session.login("user", "password"); - fail("server not ready - must throw"); - } - catch (FTPException&) - { - } - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testLoginFailed2() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("530 Login incorrect"); - FTPClientSession session("localhost", server.port()); - try - { - session.login("user", "password"); - fail("login incorrect - must throw"); - } - catch (FTPException&) - { - } - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testCommands() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - FTPClientSession session("localhost", server.port()); - session.login("user", "password"); - std::string cmd = server.popCommand(); - assert (cmd == "USER user"); - cmd = server.popCommand(); - assert (cmd == "PASS password"); - cmd = server.popCommand(); - assert (cmd == "TYPE I"); - - // systemType - server.clearCommands(); - server.addResponse("215 UNIX Type: L8 Version: dummyFTP 1.0"); - std::string type = session.systemType(); - cmd = server.popCommand(); - assert (cmd == "SYST"); - assert (type == "UNIX Type: L8 Version: dummyFTP 1.0"); - - // getWorkingDirectory - server.addResponse("257 \"/usr/test\" is current directory"); - std::string cwd = session.getWorkingDirectory(); - cmd = server.popCommand(); - assert (cmd == "PWD"); - assert (cwd == "/usr/test"); - - // getWorkingDirectory (quotes in filename) - server.addResponse("257 \"\"\"quote\"\"\" is current directory"); - cwd = session.getWorkingDirectory(); - cmd = server.popCommand(); - assert (cmd == "PWD"); - assert (cwd == "\"quote\""); - - // setWorkingDirectory - server.addResponse("250 CWD OK"); - session.setWorkingDirectory("test"); - cmd = server.popCommand(); - assert (cmd == "CWD test"); - - server.addResponse("250 CDUP OK"); - session.cdup(); - cmd = server.popCommand(); - assert (cmd == "CDUP"); - - // rename - server.addResponse("350 File exists, send destination name"); - server.addResponse("250 Rename OK"); - session.rename("old.txt", "new.txt"); - cmd = server.popCommand(); - assert (cmd == "RNFR old.txt"); - cmd = server.popCommand(); - assert (cmd == "RNTO new.txt"); - - // rename (failing) - server.addResponse("550 not found"); - try - { - session.rename("old.txt", "new.txt"); - fail("not found - must throw"); - } - catch (FTPException&) - { - } - server.clearCommands(); - - // remove - server.addResponse("250 delete ok"); - session.remove("test.txt"); - cmd = server.popCommand(); - assert (cmd == "DELE test.txt"); - - // remove (failing) - server.addResponse("550 not found"); - try - { - session.remove("test.txt"); - fail("not found - must throw"); - } - catch (FTPException&) - { - } - server.clearCommands(); - - // createDirectory - server.addResponse("257 dir created"); - session.createDirectory("foo"); - cmd = server.popCommand(); - assert (cmd == "MKD foo"); - - // createDirectory (failing) - server.addResponse("550 exists"); - try - { - session.createDirectory("foo"); - fail("not found - must throw"); - } - catch (FTPException&) - { - } - server.clearCommands(); - - // removeDirectory - server.addResponse("250 RMD OK"); - session.removeDirectory("foo"); - cmd = server.popCommand(); - assert (cmd == "RMD foo"); - - // removeDirectory (failing) - server.addResponse("550 not found"); - try - { - session.removeDirectory("foo"); - fail("not found - must throw"); - } - catch (FTPException&) - { - } - server.clearCommands(); - - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testDownloadPORT() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - FTPClientSession session("localhost", server.port()); - session.setPassive(false); - session.login("user", "password"); - server.clearCommands(); - - server.addResponse("500 EPRT not understood"); - server.addResponse("200 PORT OK"); - server.addResponse("150 Sending data\r\n226 Transfer complete"); - - ActiveDownloader dl(session); - ActiveResult result = dl.download("test.txt"); - - std::string cmd = server.popCommandWait(); - assert (cmd.substr(0, 4) == "EPRT"); - - cmd = server.popCommandWait(); - assert (cmd.substr(0, 4) == "PORT"); - - std::string dummy; - int x, lo, hi; - for (std::string::iterator it = cmd.begin(); it != cmd.end(); ++it) - { - if (*it == ',') *it = ' '; - } - std::istringstream istr(cmd); - istr >> dummy >> x >> x >> x >> x >> hi >> lo; - int port = hi*256 + lo; - - cmd = server.popCommandWait(); - assert (cmd == "RETR test.txt"); - - SocketAddress sa("localhost", (Poco::UInt16) port); - DialogSocket dataSock; - dataSock.connect(sa); - - std::string data("This is some data"); - dataSock.sendString(data); - dataSock.close(); - - result.wait(); - std::string received = result.data(); - assert (received == data); - - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testDownloadEPRT() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - FTPClientSession session("localhost", server.port()); - session.setPassive(false); - session.login("user", "password"); - server.clearCommands(); - - server.addResponse("200 EPRT OK"); - server.addResponse("150 Sending data\r\n226 Transfer complete"); - - ActiveDownloader dl(session); - ActiveResult result = dl.download("test.txt"); - - std::string cmd = server.popCommandWait(); - assert (cmd.substr(0, 4) == "EPRT"); - - std::string dummy; - char c; - int d; - int port; - std::istringstream istr(cmd); - istr >> dummy >> c >> d >> c >> d >> c >> d >> c >> d >> c >> d >> c >> port >> c; - - cmd = server.popCommandWait(); - assert (cmd == "RETR test.txt"); - - SocketAddress sa("localhost", (Poco::UInt16) port); - DialogSocket dataSock; - dataSock.connect(sa); - - std::string data("This is some data"); - dataSock.sendString(data); - dataSock.close(); - - result.wait(); - std::string received = result.data(); - assert (received == data); - - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testDownloadPASV() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - FTPClientSession session("localhost", server.port()); - session.login("user", "password"); - server.clearCommands(); - - server.addResponse("500 EPSV not understood"); - - DialogServer dataServer(false); - dataServer.addResponse("This is some data"); - std::ostringstream pasv; - pasv << "227 Entering Passive Mode (127,0,0,1," << (dataServer.port()/256) << "," << (dataServer.port() % 256) << ")"; - server.addResponse(pasv.str()); - server.addResponse("150 sending data\r\n226 Transfer complete"); - - std::istream& istr = session.beginDownload("test.txt"); - std::ostringstream dataStr; - StreamCopier::copyStream(istr, dataStr); - session.endDownload(); - std::string s(dataStr.str()); - assert (s == "This is some data\r\n"); - - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testDownloadEPSV() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - FTPClientSession session("localhost", server.port()); - session.login("user", "password"); - server.clearCommands(); - - DialogServer dataServer(false); - dataServer.addResponse("This is some data"); - std::ostringstream epsv; - epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; - server.addResponse(epsv.str()); - server.addResponse("150 sending data\r\n226 Transfer complete"); - - std::istream& istr = session.beginDownload("test.txt"); - std::ostringstream dataStr; - StreamCopier::copyStream(istr, dataStr); - session.endDownload(); - std::string s(dataStr.str()); - assert (s == "This is some data\r\n"); - - std::string cmd = server.popCommand(); - assert (cmd.substr(0, 4) == "EPSV"); - cmd = server.popCommand(); - assert (cmd == "RETR test.txt"); - - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testUpload() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - FTPClientSession session("localhost", server.port()); - session.login("user", "password"); - server.clearCommands(); - - DialogServer dataServer; - std::ostringstream epsv; - epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; - server.addResponse(epsv.str()); - server.addResponse("150 send data\r\n226 Transfer complete"); - - std::ostream& ostr = session.beginUpload("test.txt"); - ostr << "This is some data\r\n"; - session.endUpload(); - std::string s(dataServer.popCommandWait()); - assert (s == "This is some data"); - - std::string cmd = server.popCommand(); - assert (cmd.substr(0, 4) == "EPSV"); - cmd = server.popCommand(); - assert (cmd == "STOR test.txt"); - - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::testList() -{ - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - FTPClientSession session("localhost", server.port()); - session.login("user", "password"); - server.clearCommands(); - - DialogServer dataServer(false); - dataServer.addResponse("file1\r\nfile2"); - std::ostringstream epsv; - epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; - server.addResponse(epsv.str()); - server.addResponse("150 sending data\r\n226 Transfer complete"); - - std::istream& istr = session.beginList(); - std::ostringstream dataStr; - StreamCopier::copyStream(istr, dataStr); - session.endList(); - std::string s(dataStr.str()); - assert (s == "file1\r\nfile2\r\n"); - - std::string cmd = server.popCommand(); - assert (cmd.substr(0, 4) == "EPSV"); - cmd = server.popCommand(); - assert (cmd == "NLST"); - - server.addResponse("221 Good Bye"); - session.close(); -} - - -void FTPClientSessionTest::setUp() -{ -} - - -void FTPClientSessionTest::tearDown() -{ -} - - -CppUnit::Test* FTPClientSessionTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FTPClientSessionTest"); - - CppUnit_addTest(pSuite, FTPClientSessionTest, testLogin); - CppUnit_addTest(pSuite, FTPClientSessionTest, testLoginFailed1); - CppUnit_addTest(pSuite, FTPClientSessionTest, testLoginFailed2); - CppUnit_addTest(pSuite, FTPClientSessionTest, testCommands); - CppUnit_addTest(pSuite, FTPClientSessionTest, testDownloadPORT); - CppUnit_addTest(pSuite, FTPClientSessionTest, testDownloadEPRT); - CppUnit_addTest(pSuite, FTPClientSessionTest, testDownloadPASV); - CppUnit_addTest(pSuite, FTPClientSessionTest, testDownloadEPSV); - CppUnit_addTest(pSuite, FTPClientSessionTest, testUpload); - CppUnit_addTest(pSuite, FTPClientSessionTest, testList); - - return pSuite; -} +// +// FTPClientSessionTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/FTPClientSessionTest.cpp#1 $ +// +// 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 "FTPClientSessionTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "DialogServer.h" +#include "Poco/Net/FTPClientSession.h" +#include "Poco/Net/DialogSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/Thread.h" +#include "Poco/ActiveMethod.h" +#include "Poco/StreamCopier.h" +#include + + +using Poco::Net::FTPClientSession; +using Poco::Net::DialogSocket; +using Poco::Net::SocketAddress; +using Poco::Net::FTPException; +using Poco::ActiveMethod; +using Poco::ActiveResult; +using Poco::StreamCopier; +using Poco::Thread; + + +namespace +{ + class ActiveDownloader + { + public: + ActiveDownloader(FTPClientSession& session): + download(this, &ActiveDownloader::downloadImp), + _session(session) + { + } + + ActiveMethod download; + + protected: + std::string downloadImp(const std::string& path) + { + std::istream& istr = _session.beginDownload(path); + std::ostringstream ostr; + StreamCopier::copyStream(istr, ostr); + _session.endDownload(); + return ostr.str(); + } + + private: + FTPClientSession& _session; + }; +}; + + +FTPClientSessionTest::FTPClientSessionTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +FTPClientSessionTest::~FTPClientSessionTest() +{ +} + + +void FTPClientSessionTest::testLogin() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + FTPClientSession session("localhost", server.port()); + session.login("user", "password"); + std::string cmd = server.popCommand(); + assert (cmd == "USER user"); + cmd = server.popCommand(); + assert (cmd == "PASS password"); + cmd = server.popCommand(); + assert (cmd == "TYPE I"); + + assert (session.getFileType() == FTPClientSession::TYPE_BINARY); + + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testLoginFailed1() +{ + DialogServer server; + server.addResponse("421 localhost FTP not ready"); + FTPClientSession session("localhost", server.port()); + try + { + session.login("user", "password"); + fail("server not ready - must throw"); + } + catch (FTPException&) + { + } + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testLoginFailed2() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("530 Login incorrect"); + FTPClientSession session("localhost", server.port()); + try + { + session.login("user", "password"); + fail("login incorrect - must throw"); + } + catch (FTPException&) + { + } + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testCommands() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + FTPClientSession session("localhost", server.port()); + session.login("user", "password"); + std::string cmd = server.popCommand(); + assert (cmd == "USER user"); + cmd = server.popCommand(); + assert (cmd == "PASS password"); + cmd = server.popCommand(); + assert (cmd == "TYPE I"); + + // systemType + server.clearCommands(); + server.addResponse("215 UNIX Type: L8 Version: dummyFTP 1.0"); + std::string type = session.systemType(); + cmd = server.popCommand(); + assert (cmd == "SYST"); + assert (type == "UNIX Type: L8 Version: dummyFTP 1.0"); + + // getWorkingDirectory + server.addResponse("257 \"/usr/test\" is current directory"); + std::string cwd = session.getWorkingDirectory(); + cmd = server.popCommand(); + assert (cmd == "PWD"); + assert (cwd == "/usr/test"); + + // getWorkingDirectory (quotes in filename) + server.addResponse("257 \"\"\"quote\"\"\" is current directory"); + cwd = session.getWorkingDirectory(); + cmd = server.popCommand(); + assert (cmd == "PWD"); + assert (cwd == "\"quote\""); + + // setWorkingDirectory + server.addResponse("250 CWD OK"); + session.setWorkingDirectory("test"); + cmd = server.popCommand(); + assert (cmd == "CWD test"); + + server.addResponse("250 CDUP OK"); + session.cdup(); + cmd = server.popCommand(); + assert (cmd == "CDUP"); + + // rename + server.addResponse("350 File exists, send destination name"); + server.addResponse("250 Rename OK"); + session.rename("old.txt", "new.txt"); + cmd = server.popCommand(); + assert (cmd == "RNFR old.txt"); + cmd = server.popCommand(); + assert (cmd == "RNTO new.txt"); + + // rename (failing) + server.addResponse("550 not found"); + try + { + session.rename("old.txt", "new.txt"); + fail("not found - must throw"); + } + catch (FTPException&) + { + } + server.clearCommands(); + + // remove + server.addResponse("250 delete ok"); + session.remove("test.txt"); + cmd = server.popCommand(); + assert (cmd == "DELE test.txt"); + + // remove (failing) + server.addResponse("550 not found"); + try + { + session.remove("test.txt"); + fail("not found - must throw"); + } + catch (FTPException&) + { + } + server.clearCommands(); + + // createDirectory + server.addResponse("257 dir created"); + session.createDirectory("foo"); + cmd = server.popCommand(); + assert (cmd == "MKD foo"); + + // createDirectory (failing) + server.addResponse("550 exists"); + try + { + session.createDirectory("foo"); + fail("not found - must throw"); + } + catch (FTPException&) + { + } + server.clearCommands(); + + // removeDirectory + server.addResponse("250 RMD OK"); + session.removeDirectory("foo"); + cmd = server.popCommand(); + assert (cmd == "RMD foo"); + + // removeDirectory (failing) + server.addResponse("550 not found"); + try + { + session.removeDirectory("foo"); + fail("not found - must throw"); + } + catch (FTPException&) + { + } + server.clearCommands(); + + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testDownloadPORT() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + FTPClientSession session("localhost", server.port()); + session.setPassive(false); + session.login("user", "password"); + server.clearCommands(); + + server.addResponse("500 EPRT not understood"); + server.addResponse("200 PORT OK"); + server.addResponse("150 Sending data\r\n226 Transfer complete"); + + ActiveDownloader dl(session); + ActiveResult result = dl.download("test.txt"); + + std::string cmd = server.popCommandWait(); + assert (cmd.substr(0, 4) == "EPRT"); + + cmd = server.popCommandWait(); + assert (cmd.substr(0, 4) == "PORT"); + + std::string dummy; + int x, lo, hi; + for (std::string::iterator it = cmd.begin(); it != cmd.end(); ++it) + { + if (*it == ',') *it = ' '; + } + std::istringstream istr(cmd); + istr >> dummy >> x >> x >> x >> x >> hi >> lo; + int port = hi*256 + lo; + + cmd = server.popCommandWait(); + assert (cmd == "RETR test.txt"); + + SocketAddress sa("localhost", (Poco::UInt16) port); + DialogSocket dataSock; + dataSock.connect(sa); + + std::string data("This is some data"); + dataSock.sendString(data); + dataSock.close(); + + result.wait(); + std::string received = result.data(); + assert (received == data); + + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testDownloadEPRT() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + FTPClientSession session("localhost", server.port()); + session.setPassive(false); + session.login("user", "password"); + server.clearCommands(); + + server.addResponse("200 EPRT OK"); + server.addResponse("150 Sending data\r\n226 Transfer complete"); + + ActiveDownloader dl(session); + ActiveResult result = dl.download("test.txt"); + + std::string cmd = server.popCommandWait(); + assert (cmd.substr(0, 4) == "EPRT"); + + std::string dummy; + char c; + int d; + int port; + std::istringstream istr(cmd); + istr >> dummy >> c >> d >> c >> d >> c >> d >> c >> d >> c >> d >> c >> port >> c; + + cmd = server.popCommandWait(); + assert (cmd == "RETR test.txt"); + + SocketAddress sa("localhost", (Poco::UInt16) port); + DialogSocket dataSock; + dataSock.connect(sa); + + std::string data("This is some data"); + dataSock.sendString(data); + dataSock.close(); + + result.wait(); + std::string received = result.data(); + assert (received == data); + + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testDownloadPASV() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + FTPClientSession session("localhost", server.port()); + session.login("user", "password"); + server.clearCommands(); + + server.addResponse("500 EPSV not understood"); + + DialogServer dataServer(false); + dataServer.addResponse("This is some data"); + std::ostringstream pasv; + pasv << "227 Entering Passive Mode (127,0,0,1," << (dataServer.port()/256) << "," << (dataServer.port() % 256) << ")"; + server.addResponse(pasv.str()); + server.addResponse("150 sending data\r\n226 Transfer complete"); + + std::istream& istr = session.beginDownload("test.txt"); + std::ostringstream dataStr; + StreamCopier::copyStream(istr, dataStr); + session.endDownload(); + std::string s(dataStr.str()); + assert (s == "This is some data\r\n"); + + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testDownloadEPSV() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + FTPClientSession session("localhost", server.port()); + session.login("user", "password"); + server.clearCommands(); + + DialogServer dataServer(false); + dataServer.addResponse("This is some data"); + std::ostringstream epsv; + epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; + server.addResponse(epsv.str()); + server.addResponse("150 sending data\r\n226 Transfer complete"); + + std::istream& istr = session.beginDownload("test.txt"); + std::ostringstream dataStr; + StreamCopier::copyStream(istr, dataStr); + session.endDownload(); + std::string s(dataStr.str()); + assert (s == "This is some data\r\n"); + + std::string cmd = server.popCommand(); + assert (cmd.substr(0, 4) == "EPSV"); + cmd = server.popCommand(); + assert (cmd == "RETR test.txt"); + + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testUpload() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + FTPClientSession session("localhost", server.port()); + session.login("user", "password"); + server.clearCommands(); + + DialogServer dataServer; + std::ostringstream epsv; + epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; + server.addResponse(epsv.str()); + server.addResponse("150 send data\r\n226 Transfer complete"); + + std::ostream& ostr = session.beginUpload("test.txt"); + ostr << "This is some data\r\n"; + session.endUpload(); + std::string s(dataServer.popCommandWait()); + assert (s == "This is some data"); + + std::string cmd = server.popCommand(); + assert (cmd.substr(0, 4) == "EPSV"); + cmd = server.popCommand(); + assert (cmd == "STOR test.txt"); + + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::testList() +{ + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + FTPClientSession session("localhost", server.port()); + session.login("user", "password"); + server.clearCommands(); + + DialogServer dataServer(false); + dataServer.addResponse("file1\r\nfile2"); + std::ostringstream epsv; + epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; + server.addResponse(epsv.str()); + server.addResponse("150 sending data\r\n226 Transfer complete"); + + std::istream& istr = session.beginList(); + std::ostringstream dataStr; + StreamCopier::copyStream(istr, dataStr); + session.endList(); + std::string s(dataStr.str()); + assert (s == "file1\r\nfile2\r\n"); + + std::string cmd = server.popCommand(); + assert (cmd.substr(0, 4) == "EPSV"); + cmd = server.popCommand(); + assert (cmd == "NLST"); + + server.addResponse("221 Good Bye"); + session.close(); +} + + +void FTPClientSessionTest::setUp() +{ +} + + +void FTPClientSessionTest::tearDown() +{ +} + + +CppUnit::Test* FTPClientSessionTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FTPClientSessionTest"); + + CppUnit_addTest(pSuite, FTPClientSessionTest, testLogin); + CppUnit_addTest(pSuite, FTPClientSessionTest, testLoginFailed1); + CppUnit_addTest(pSuite, FTPClientSessionTest, testLoginFailed2); + CppUnit_addTest(pSuite, FTPClientSessionTest, testCommands); + CppUnit_addTest(pSuite, FTPClientSessionTest, testDownloadPORT); + CppUnit_addTest(pSuite, FTPClientSessionTest, testDownloadEPRT); + CppUnit_addTest(pSuite, FTPClientSessionTest, testDownloadPASV); + CppUnit_addTest(pSuite, FTPClientSessionTest, testDownloadEPSV); + CppUnit_addTest(pSuite, FTPClientSessionTest, testUpload); + CppUnit_addTest(pSuite, FTPClientSessionTest, testList); + + return pSuite; +} diff --git a/Net/testsuite/src/FTPClientSessionTest.h b/Net/testsuite/src/FTPClientSessionTest.h index 4af13c2fe..4d4c5edd4 100644 --- a/Net/testsuite/src/FTPClientSessionTest.h +++ b/Net/testsuite/src/FTPClientSessionTest.h @@ -1,69 +1,69 @@ -// -// FTPClientSessionTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/FTPClientSessionTest.h#1 $ -// -// Definition of the FTPClientSessionTest 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 FTPClientSessionTest_INCLUDED -#define FTPClientSessionTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class FTPClientSessionTest: public CppUnit::TestCase -{ -public: - FTPClientSessionTest(const std::string& name); - ~FTPClientSessionTest(); - - void testLogin(); - void testLoginFailed1(); - void testLoginFailed2(); - void testCommands(); - void testDownloadPORT(); - void testDownloadEPRT(); - void testDownloadPASV(); - void testDownloadEPSV(); - void testUpload(); - void testList(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // FTPClientSessionTest_INCLUDED +// +// FTPClientSessionTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/FTPClientSessionTest.h#1 $ +// +// Definition of the FTPClientSessionTest 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 FTPClientSessionTest_INCLUDED +#define FTPClientSessionTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class FTPClientSessionTest: public CppUnit::TestCase +{ +public: + FTPClientSessionTest(const std::string& name); + ~FTPClientSessionTest(); + + void testLogin(); + void testLoginFailed1(); + void testLoginFailed2(); + void testCommands(); + void testDownloadPORT(); + void testDownloadEPRT(); + void testDownloadPASV(); + void testDownloadEPSV(); + void testUpload(); + void testList(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // FTPClientSessionTest_INCLUDED diff --git a/Net/testsuite/src/FTPClientTestSuite.cpp b/Net/testsuite/src/FTPClientTestSuite.cpp index d8c0f9526..14e1c56c3 100644 --- a/Net/testsuite/src/FTPClientTestSuite.cpp +++ b/Net/testsuite/src/FTPClientTestSuite.cpp @@ -1,46 +1,46 @@ -// -// FTPClientTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/FTPClientTestSuite.cpp#1 $ -// -// 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 "FTPClientTestSuite.h" -#include "FTPClientSessionTest.h" -#include "FTPStreamFactoryTest.h" - - -CppUnit::Test* FTPClientTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FTPClientTestSuite"); - - pSuite->addTest(FTPClientSessionTest::suite()); - pSuite->addTest(FTPStreamFactoryTest::suite()); - - return pSuite; -} +// +// FTPClientTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/FTPClientTestSuite.cpp#1 $ +// +// 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 "FTPClientTestSuite.h" +#include "FTPClientSessionTest.h" +#include "FTPStreamFactoryTest.h" + + +CppUnit::Test* FTPClientTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FTPClientTestSuite"); + + pSuite->addTest(FTPClientSessionTest::suite()); + pSuite->addTest(FTPStreamFactoryTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/FTPClientTestSuite.h b/Net/testsuite/src/FTPClientTestSuite.h index 3fff22477..b1be40863 100644 --- a/Net/testsuite/src/FTPClientTestSuite.h +++ b/Net/testsuite/src/FTPClientTestSuite.h @@ -1,49 +1,49 @@ -// -// FTPClientTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/FTPClientTestSuite.h#1 $ -// -// Definition of the FTPClientTestSuite 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 FTPClientTestSuite_INCLUDED -#define FTPClientTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class FTPClientTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // FTPClientTestSuite_INCLUDED +// +// FTPClientTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/FTPClientTestSuite.h#1 $ +// +// Definition of the FTPClientTestSuite 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 FTPClientTestSuite_INCLUDED +#define FTPClientTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class FTPClientTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // FTPClientTestSuite_INCLUDED diff --git a/Net/testsuite/src/FTPStreamFactoryTest.cpp b/Net/testsuite/src/FTPStreamFactoryTest.cpp index 63197159d..3f015fb4c 100644 --- a/Net/testsuite/src/FTPStreamFactoryTest.cpp +++ b/Net/testsuite/src/FTPStreamFactoryTest.cpp @@ -1,279 +1,279 @@ -// -// FTPStreamFactoryTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/FTPStreamFactoryTest.cpp#1 $ -// -// 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 "FTPStreamFactoryTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "DialogServer.h" -#include "Poco/Net/FTPStreamFactory.h" -#include "Poco/Net/DialogSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/URI.h" -#include "Poco/StreamCopier.h" -#include -#include - - -using Poco::Net::FTPStreamFactory; -using Poco::Net::FTPPasswordProvider; -using Poco::Net::DialogSocket; -using Poco::Net::SocketAddress; -using Poco::Net::FTPException; -using Poco::URI; -using Poco::StreamCopier; - - -namespace -{ - class TestPasswordProvider: public FTPPasswordProvider - { - public: - std::string password(const std::string& username, const std::string& host) - { - return "secret"; - } - }; -} - - -FTPStreamFactoryTest::FTPStreamFactoryTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -FTPStreamFactoryTest::~FTPStreamFactoryTest() -{ -} - - -void FTPStreamFactoryTest::testDownload() -{ - FTPStreamFactory::setPasswordProvider(0); - - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - server.addResponse("200 Type set to A"); - - DialogServer dataServer(false); - dataServer.addResponse("line1\r\nline2"); - std::ostringstream epsv; - epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; - server.addResponse(epsv.str()); - server.addResponse("150 sending data\r\n226 Transfer complete"); - server.addResponse("221 Good bye"); - - URI uri; - uri.setScheme("ftp"); - uri.setHost("localhost"); - uri.setPort(server.port()); - uri.setPath("/test.txt;type=a"); - FTPStreamFactory sf; - std::auto_ptr pStr(sf.open(uri)); - - std::ostringstream dataStr; - StreamCopier::copyStream(*pStr.get(), dataStr); - - pStr.reset(); - - std::string s(dataStr.str()); - assert (s == "line1\r\nline2\r\n"); -} - - -void FTPStreamFactoryTest::testList() -{ - FTPStreamFactory::setPasswordProvider(0); - - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - server.addResponse("250 CWD OK"); - server.addResponse("250 CWD OK"); - - DialogServer dataServer(false); - dataServer.addResponse("file1\r\nfile2"); - std::ostringstream epsv; - epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; - server.addResponse(epsv.str()); - server.addResponse("150 sending data\r\n226 Transfer complete"); - server.addResponse("221 Good bye"); - - URI uri; - uri.setScheme("ftp"); - uri.setHost("localhost"); - uri.setPort(server.port()); - uri.setPath("/usr/guest/data;type=d"); - FTPStreamFactory sf; - std::auto_ptr pStr(sf.open(uri)); - - std::ostringstream dataStr; - StreamCopier::copyStream(*pStr.get(), dataStr); - - pStr.reset(); - - std::string s(dataStr.str()); - assert (s == "file1\r\nfile2\r\n"); -} - - -void FTPStreamFactoryTest::testUserInfo() -{ - FTPStreamFactory::setPasswordProvider(0); - - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - server.addResponse("200 Type set to A"); - - DialogServer dataServer(false); - dataServer.addResponse("line1\r\nline2"); - std::ostringstream epsv; - epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; - server.addResponse(epsv.str()); - server.addResponse("150 sending data\r\n226 Transfer complete"); - server.addResponse("221 Good bye"); - - URI uri; - uri.setScheme("ftp"); - uri.setHost("localhost"); - uri.setPort(server.port()); - uri.setPath("/test.txt;type=a"); - uri.setUserInfo("user:secret"); - FTPStreamFactory sf; - std::auto_ptr pStr(sf.open(uri)); - - std::ostringstream dataStr; - StreamCopier::copyStream(*pStr.get(), dataStr); - - pStr.reset(); - - std::string s(dataStr.str()); - assert (s == "line1\r\nline2\r\n"); -} - - -void FTPStreamFactoryTest::testPasswordProvider() -{ - static TestPasswordProvider tpp; - FTPStreamFactory::setPasswordProvider(&tpp); - - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("331 Password required"); - server.addResponse("230 Welcome"); - server.addResponse("200 Type set to I"); - server.addResponse("200 Type set to A"); - - DialogServer dataServer(false); - dataServer.addResponse("line1\r\nline2"); - std::ostringstream epsv; - epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; - server.addResponse(epsv.str()); - server.addResponse("150 sending data\r\n226 Transfer complete"); - server.addResponse("221 Good bye"); - - URI uri; - uri.setScheme("ftp"); - uri.setHost("localhost"); - uri.setPort(server.port()); - uri.setPath("/test.txt;type=a"); - uri.setUserInfo("user"); - FTPStreamFactory sf; - std::auto_ptr pStr(sf.open(uri)); - - std::ostringstream dataStr; - StreamCopier::copyStream(*pStr.get(), dataStr); - - pStr.reset(); - - std::string s(dataStr.str()); - assert (s == "line1\r\nline2\r\n"); -} - - -void FTPStreamFactoryTest::testMissingPasswordProvider() -{ - FTPStreamFactory::setPasswordProvider(0); - - DialogServer server; - server.addResponse("220 localhost FTP ready"); - server.addResponse("221 Good bye"); - - URI uri; - uri.setScheme("ftp"); - uri.setHost("localhost"); - uri.setPort(server.port()); - uri.setPath("/test.txt;type=a"); - uri.setUserInfo("user"); - - try - { - FTPStreamFactory sf; - std::auto_ptr pStr(sf.open(uri)); - fail("no password provider - must throw"); - } - catch (FTPException&) - { - } -} - - -void FTPStreamFactoryTest::setUp() -{ -} - - -void FTPStreamFactoryTest::tearDown() -{ -} - - -CppUnit::Test* FTPStreamFactoryTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FTPStreamFactoryTest"); - - CppUnit_addTest(pSuite, FTPStreamFactoryTest, testDownload); - CppUnit_addTest(pSuite, FTPStreamFactoryTest, testList); - CppUnit_addTest(pSuite, FTPStreamFactoryTest, testUserInfo); - CppUnit_addTest(pSuite, FTPStreamFactoryTest, testPasswordProvider); - CppUnit_addTest(pSuite, FTPStreamFactoryTest, testMissingPasswordProvider); - - return pSuite; -} +// +// FTPStreamFactoryTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/FTPStreamFactoryTest.cpp#1 $ +// +// 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 "FTPStreamFactoryTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "DialogServer.h" +#include "Poco/Net/FTPStreamFactory.h" +#include "Poco/Net/DialogSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/URI.h" +#include "Poco/StreamCopier.h" +#include +#include + + +using Poco::Net::FTPStreamFactory; +using Poco::Net::FTPPasswordProvider; +using Poco::Net::DialogSocket; +using Poco::Net::SocketAddress; +using Poco::Net::FTPException; +using Poco::URI; +using Poco::StreamCopier; + + +namespace +{ + class TestPasswordProvider: public FTPPasswordProvider + { + public: + std::string password(const std::string& username, const std::string& host) + { + return "secret"; + } + }; +} + + +FTPStreamFactoryTest::FTPStreamFactoryTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +FTPStreamFactoryTest::~FTPStreamFactoryTest() +{ +} + + +void FTPStreamFactoryTest::testDownload() +{ + FTPStreamFactory::setPasswordProvider(0); + + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + server.addResponse("200 Type set to A"); + + DialogServer dataServer(false); + dataServer.addResponse("line1\r\nline2"); + std::ostringstream epsv; + epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; + server.addResponse(epsv.str()); + server.addResponse("150 sending data\r\n226 Transfer complete"); + server.addResponse("221 Good bye"); + + URI uri; + uri.setScheme("ftp"); + uri.setHost("localhost"); + uri.setPort(server.port()); + uri.setPath("/test.txt;type=a"); + FTPStreamFactory sf; + std::auto_ptr pStr(sf.open(uri)); + + std::ostringstream dataStr; + StreamCopier::copyStream(*pStr.get(), dataStr); + + pStr.reset(); + + std::string s(dataStr.str()); + assert (s == "line1\r\nline2\r\n"); +} + + +void FTPStreamFactoryTest::testList() +{ + FTPStreamFactory::setPasswordProvider(0); + + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + server.addResponse("250 CWD OK"); + server.addResponse("250 CWD OK"); + + DialogServer dataServer(false); + dataServer.addResponse("file1\r\nfile2"); + std::ostringstream epsv; + epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; + server.addResponse(epsv.str()); + server.addResponse("150 sending data\r\n226 Transfer complete"); + server.addResponse("221 Good bye"); + + URI uri; + uri.setScheme("ftp"); + uri.setHost("localhost"); + uri.setPort(server.port()); + uri.setPath("/usr/guest/data;type=d"); + FTPStreamFactory sf; + std::auto_ptr pStr(sf.open(uri)); + + std::ostringstream dataStr; + StreamCopier::copyStream(*pStr.get(), dataStr); + + pStr.reset(); + + std::string s(dataStr.str()); + assert (s == "file1\r\nfile2\r\n"); +} + + +void FTPStreamFactoryTest::testUserInfo() +{ + FTPStreamFactory::setPasswordProvider(0); + + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + server.addResponse("200 Type set to A"); + + DialogServer dataServer(false); + dataServer.addResponse("line1\r\nline2"); + std::ostringstream epsv; + epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; + server.addResponse(epsv.str()); + server.addResponse("150 sending data\r\n226 Transfer complete"); + server.addResponse("221 Good bye"); + + URI uri; + uri.setScheme("ftp"); + uri.setHost("localhost"); + uri.setPort(server.port()); + uri.setPath("/test.txt;type=a"); + uri.setUserInfo("user:secret"); + FTPStreamFactory sf; + std::auto_ptr pStr(sf.open(uri)); + + std::ostringstream dataStr; + StreamCopier::copyStream(*pStr.get(), dataStr); + + pStr.reset(); + + std::string s(dataStr.str()); + assert (s == "line1\r\nline2\r\n"); +} + + +void FTPStreamFactoryTest::testPasswordProvider() +{ + static TestPasswordProvider tpp; + FTPStreamFactory::setPasswordProvider(&tpp); + + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("331 Password required"); + server.addResponse("230 Welcome"); + server.addResponse("200 Type set to I"); + server.addResponse("200 Type set to A"); + + DialogServer dataServer(false); + dataServer.addResponse("line1\r\nline2"); + std::ostringstream epsv; + epsv << "229 Entering Extended Passive Mode (|||" << dataServer.port() << "|)"; + server.addResponse(epsv.str()); + server.addResponse("150 sending data\r\n226 Transfer complete"); + server.addResponse("221 Good bye"); + + URI uri; + uri.setScheme("ftp"); + uri.setHost("localhost"); + uri.setPort(server.port()); + uri.setPath("/test.txt;type=a"); + uri.setUserInfo("user"); + FTPStreamFactory sf; + std::auto_ptr pStr(sf.open(uri)); + + std::ostringstream dataStr; + StreamCopier::copyStream(*pStr.get(), dataStr); + + pStr.reset(); + + std::string s(dataStr.str()); + assert (s == "line1\r\nline2\r\n"); +} + + +void FTPStreamFactoryTest::testMissingPasswordProvider() +{ + FTPStreamFactory::setPasswordProvider(0); + + DialogServer server; + server.addResponse("220 localhost FTP ready"); + server.addResponse("221 Good bye"); + + URI uri; + uri.setScheme("ftp"); + uri.setHost("localhost"); + uri.setPort(server.port()); + uri.setPath("/test.txt;type=a"); + uri.setUserInfo("user"); + + try + { + FTPStreamFactory sf; + std::auto_ptr pStr(sf.open(uri)); + fail("no password provider - must throw"); + } + catch (FTPException&) + { + } +} + + +void FTPStreamFactoryTest::setUp() +{ +} + + +void FTPStreamFactoryTest::tearDown() +{ +} + + +CppUnit::Test* FTPStreamFactoryTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FTPStreamFactoryTest"); + + CppUnit_addTest(pSuite, FTPStreamFactoryTest, testDownload); + CppUnit_addTest(pSuite, FTPStreamFactoryTest, testList); + CppUnit_addTest(pSuite, FTPStreamFactoryTest, testUserInfo); + CppUnit_addTest(pSuite, FTPStreamFactoryTest, testPasswordProvider); + CppUnit_addTest(pSuite, FTPStreamFactoryTest, testMissingPasswordProvider); + + return pSuite; +} diff --git a/Net/testsuite/src/FTPStreamFactoryTest.h b/Net/testsuite/src/FTPStreamFactoryTest.h index 6ebb2bd8c..c0165e593 100644 --- a/Net/testsuite/src/FTPStreamFactoryTest.h +++ b/Net/testsuite/src/FTPStreamFactoryTest.h @@ -1,64 +1,64 @@ -// -// FTPStreamFactoryTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/FTPStreamFactoryTest.h#1 $ -// -// Definition of the FTPStreamFactoryTest 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 FTPStreamFactoryTest_INCLUDED -#define FTPStreamFactoryTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class FTPStreamFactoryTest: public CppUnit::TestCase -{ -public: - FTPStreamFactoryTest(const std::string& name); - ~FTPStreamFactoryTest(); - - void testDownload(); - void testList(); - void testUserInfo(); - void testPasswordProvider(); - void testMissingPasswordProvider(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // FTPStreamFactoryTest_INCLUDED +// +// FTPStreamFactoryTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/FTPStreamFactoryTest.h#1 $ +// +// Definition of the FTPStreamFactoryTest 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 FTPStreamFactoryTest_INCLUDED +#define FTPStreamFactoryTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class FTPStreamFactoryTest: public CppUnit::TestCase +{ +public: + FTPStreamFactoryTest(const std::string& name); + ~FTPStreamFactoryTest(); + + void testDownload(); + void testList(); + void testUserInfo(); + void testPasswordProvider(); + void testMissingPasswordProvider(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // FTPStreamFactoryTest_INCLUDED diff --git a/Net/testsuite/src/HTMLFormTest.cpp b/Net/testsuite/src/HTMLFormTest.cpp index 5c31ef1ff..72a046ed8 100644 --- a/Net/testsuite/src/HTMLFormTest.cpp +++ b/Net/testsuite/src/HTMLFormTest.cpp @@ -1,307 +1,307 @@ -// -// HTMLFormTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTMLFormTest.cpp#1 $ -// -// 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 "HTMLFormTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/HTMLForm.h" -#include "Poco/Net/PartSource.h" -#include "Poco/Net/StringPartSource.h" -#include "Poco/Net/PartHandler.h" -#include "Poco/Net/HTTPRequest.h" -#include - - -using Poco::Net::HTMLForm; -using Poco::Net::PartSource; -using Poco::Net::StringPartSource; -using Poco::Net::PartHandler; -using Poco::Net::HTTPRequest; -using Poco::Net::HTTPMessage; -using Poco::Net::MessageHeader; - - -namespace -{ - class StringPartHandler: public PartHandler - { - public: - StringPartHandler() - { - } - - void handlePart(const MessageHeader& header, std::istream& stream) - { - _disp = header["Content-Disposition"]; - _type = header["Content-Type"]; - int ch = stream.get(); - while (ch > 0) - { - _data += (char) ch; - ch = stream.get(); - } - } - - const std::string& data() const - { - return _data; - } - - const std::string& disp() const - { - return _disp; - } - - const std::string& type() const - { - return _type; - } - - private: - std::string _data; - std::string _disp; - std::string _type; - }; -} - - -HTMLFormTest::HTMLFormTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HTMLFormTest::~HTMLFormTest() -{ -} - - -void HTMLFormTest::testWriteUrl() -{ - HTMLForm form; - form.set("field1", "value1"); - form.set("field2", "value 2"); - form.set("field3", "value=3"); - form.set("field4", "value&4"); - - std::ostringstream ostr; - form.write(ostr); - std::string s = ostr.str(); - assert (s == "field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); -} - - -void HTMLFormTest::testWriteMultipart() -{ - HTMLForm form(HTMLForm::ENCODING_MULTIPART); - form.set("field1", "value1"); - form.set("field2", "value 2"); - form.set("field3", "value=3"); - form.set("field4", "value&4"); - - form.addPart("attachment1", new StringPartSource("This is an attachment")); - form.addPart("attachment2", new StringPartSource("This is another attachment", "text/plain", "att2.txt")); - - std::ostringstream ostr; - form.write(ostr, "MIME_boundary_0123456789"); - std::string s = ostr.str(); - assert (s == "\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: form-data; name=\"field1\"\r\n" - "\r\n" - "value1\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: form-data; name=\"field2\"\r\n" - "\r\n" - "value 2\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: form-data; name=\"field3\"\r\n" - "\r\n" - "value=3\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: form-data; name=\"field4\"\r\n" - "\r\n" - "value&4\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: file; name=\"attachment1\"\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "This is an attachment\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: file; name=\"attachment2\"; filename=\"att2.txt\"\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "This is another attachment\r\n" - "--MIME_boundary_0123456789--\r\n" - ); -} - - -void HTMLFormTest::testReadUrl1() -{ - HTTPRequest req("GET", "/form.cgi?field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); - HTMLForm form(req); - assert (form.size() == 4); - assert (form["field1"] == "value1"); - assert (form["field2"] == "value 2"); - assert (form["field3"] == "value=3"); - assert (form["field4"] == "value&4"); -} - - -void HTMLFormTest::testReadUrl2() -{ - HTTPRequest req("POST", "/form.cgi"); - std::istringstream istr("field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); - HTMLForm form(req, istr); - assert (form.size() == 4); - assert (form["field1"] == "value1"); - assert (form["field2"] == "value 2"); - assert (form["field3"] == "value=3"); - assert (form["field4"] == "value&4"); -} - - -void HTMLFormTest::testReadMultipart() -{ - std::istringstream istr( - "\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: form-data; name=\"field1\"\r\n" - "\r\n" - "value1\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: form-data; name=\"field2\"\r\n" - "\r\n" - "value 2\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: form-data; name=\"field3\"\r\n" - "\r\n" - "value=3\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: form-data; name=\"field4\"\r\n" - "\r\n" - "value&4\r\n" - "--MIME_boundary_0123456789\r\n" - "Content-Disposition: file; name=\"attachment1\"; filename=\"att1.txt\"\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "This is an attachment\r\n" - "--MIME_boundary_0123456789--\r\n" - ); - HTTPRequest req("POST", "/form.cgi"); - req.setContentType(HTMLForm::ENCODING_MULTIPART + "; boundary=\"MIME_boundary_0123456789\""); - StringPartHandler sah; - HTMLForm form(req, istr, sah); - assert (form.size() == 4); - assert (form["field1"] == "value1"); - assert (form["field2"] == "value 2"); - assert (form["field3"] == "value=3"); - assert (form["field4"] == "value&4"); - - assert (sah.type() == "text/plain"); - assert (sah.disp() == "file; name=\"attachment1\"; filename=\"att1.txt\""); - assert (sah.data() == "This is an attachment"); -} - - -void HTMLFormTest::testSubmit1() -{ - HTMLForm form; - form.set("field1", "value1"); - form.set("field2", "value 2"); - form.set("field3", "value=3"); - form.set("field4", "value&4"); - - HTTPRequest req("GET", "/form.cgi"); - form.prepareSubmit(req); - assert (req.getURI() == "/form.cgi?field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); -} - - -void HTMLFormTest::testSubmit2() -{ - HTMLForm form; - form.set("field1", "value1"); - form.set("field2", "value 2"); - form.set("field3", "value=3"); - form.set("field4", "value&4"); - - HTTPRequest req("POST", "/form.cgi"); - form.prepareSubmit(req); - assert (req.getContentType() == HTMLForm::ENCODING_URL); -} - - -void HTMLFormTest::testSubmit3() -{ - HTMLForm form(HTMLForm::ENCODING_MULTIPART); - form.set("field1", "value1"); - form.set("field2", "value 2"); - form.set("field3", "value=3"); - form.set("field4", "value&4"); - - HTTPRequest req("POST", "/form.cgi", HTTPMessage::HTTP_1_1); - form.prepareSubmit(req); - std::string expCT(HTMLForm::ENCODING_MULTIPART); - expCT.append("; boundary=\""); - expCT.append(form.boundary()); - expCT.append("\""); - assert (req.getContentType() == expCT); - assert (req.getChunkedTransferEncoding()); -} - - -void HTMLFormTest::setUp() -{ -} - - -void HTMLFormTest::tearDown() -{ -} - - -CppUnit::Test* HTMLFormTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTMLFormTest"); - - CppUnit_addTest(pSuite, HTMLFormTest, testWriteUrl); - CppUnit_addTest(pSuite, HTMLFormTest, testWriteMultipart); - CppUnit_addTest(pSuite, HTMLFormTest, testReadUrl1); - CppUnit_addTest(pSuite, HTMLFormTest, testReadUrl2); - CppUnit_addTest(pSuite, HTMLFormTest, testReadMultipart); - CppUnit_addTest(pSuite, HTMLFormTest, testSubmit1); - CppUnit_addTest(pSuite, HTMLFormTest, testSubmit2); - CppUnit_addTest(pSuite, HTMLFormTest, testSubmit3); - - return pSuite; -} +// +// HTMLFormTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTMLFormTest.cpp#1 $ +// +// 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 "HTMLFormTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/HTMLForm.h" +#include "Poco/Net/PartSource.h" +#include "Poco/Net/StringPartSource.h" +#include "Poco/Net/PartHandler.h" +#include "Poco/Net/HTTPRequest.h" +#include + + +using Poco::Net::HTMLForm; +using Poco::Net::PartSource; +using Poco::Net::StringPartSource; +using Poco::Net::PartHandler; +using Poco::Net::HTTPRequest; +using Poco::Net::HTTPMessage; +using Poco::Net::MessageHeader; + + +namespace +{ + class StringPartHandler: public PartHandler + { + public: + StringPartHandler() + { + } + + void handlePart(const MessageHeader& header, std::istream& stream) + { + _disp = header["Content-Disposition"]; + _type = header["Content-Type"]; + int ch = stream.get(); + while (ch > 0) + { + _data += (char) ch; + ch = stream.get(); + } + } + + const std::string& data() const + { + return _data; + } + + const std::string& disp() const + { + return _disp; + } + + const std::string& type() const + { + return _type; + } + + private: + std::string _data; + std::string _disp; + std::string _type; + }; +} + + +HTMLFormTest::HTMLFormTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HTMLFormTest::~HTMLFormTest() +{ +} + + +void HTMLFormTest::testWriteUrl() +{ + HTMLForm form; + form.set("field1", "value1"); + form.set("field2", "value 2"); + form.set("field3", "value=3"); + form.set("field4", "value&4"); + + std::ostringstream ostr; + form.write(ostr); + std::string s = ostr.str(); + assert (s == "field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); +} + + +void HTMLFormTest::testWriteMultipart() +{ + HTMLForm form(HTMLForm::ENCODING_MULTIPART); + form.set("field1", "value1"); + form.set("field2", "value 2"); + form.set("field3", "value=3"); + form.set("field4", "value&4"); + + form.addPart("attachment1", new StringPartSource("This is an attachment")); + form.addPart("attachment2", new StringPartSource("This is another attachment", "text/plain", "att2.txt")); + + std::ostringstream ostr; + form.write(ostr, "MIME_boundary_0123456789"); + std::string s = ostr.str(); + assert (s == "\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: form-data; name=\"field1\"\r\n" + "\r\n" + "value1\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: form-data; name=\"field2\"\r\n" + "\r\n" + "value 2\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: form-data; name=\"field3\"\r\n" + "\r\n" + "value=3\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: form-data; name=\"field4\"\r\n" + "\r\n" + "value&4\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: file; name=\"attachment1\"\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "This is an attachment\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: file; name=\"attachment2\"; filename=\"att2.txt\"\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "This is another attachment\r\n" + "--MIME_boundary_0123456789--\r\n" + ); +} + + +void HTMLFormTest::testReadUrl1() +{ + HTTPRequest req("GET", "/form.cgi?field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); + HTMLForm form(req); + assert (form.size() == 4); + assert (form["field1"] == "value1"); + assert (form["field2"] == "value 2"); + assert (form["field3"] == "value=3"); + assert (form["field4"] == "value&4"); +} + + +void HTMLFormTest::testReadUrl2() +{ + HTTPRequest req("POST", "/form.cgi"); + std::istringstream istr("field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); + HTMLForm form(req, istr); + assert (form.size() == 4); + assert (form["field1"] == "value1"); + assert (form["field2"] == "value 2"); + assert (form["field3"] == "value=3"); + assert (form["field4"] == "value&4"); +} + + +void HTMLFormTest::testReadMultipart() +{ + std::istringstream istr( + "\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: form-data; name=\"field1\"\r\n" + "\r\n" + "value1\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: form-data; name=\"field2\"\r\n" + "\r\n" + "value 2\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: form-data; name=\"field3\"\r\n" + "\r\n" + "value=3\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: form-data; name=\"field4\"\r\n" + "\r\n" + "value&4\r\n" + "--MIME_boundary_0123456789\r\n" + "Content-Disposition: file; name=\"attachment1\"; filename=\"att1.txt\"\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "This is an attachment\r\n" + "--MIME_boundary_0123456789--\r\n" + ); + HTTPRequest req("POST", "/form.cgi"); + req.setContentType(HTMLForm::ENCODING_MULTIPART + "; boundary=\"MIME_boundary_0123456789\""); + StringPartHandler sah; + HTMLForm form(req, istr, sah); + assert (form.size() == 4); + assert (form["field1"] == "value1"); + assert (form["field2"] == "value 2"); + assert (form["field3"] == "value=3"); + assert (form["field4"] == "value&4"); + + assert (sah.type() == "text/plain"); + assert (sah.disp() == "file; name=\"attachment1\"; filename=\"att1.txt\""); + assert (sah.data() == "This is an attachment"); +} + + +void HTMLFormTest::testSubmit1() +{ + HTMLForm form; + form.set("field1", "value1"); + form.set("field2", "value 2"); + form.set("field3", "value=3"); + form.set("field4", "value&4"); + + HTTPRequest req("GET", "/form.cgi"); + form.prepareSubmit(req); + assert (req.getURI() == "/form.cgi?field1=value1&field2=value%202&field3=value%3D3&field4=value%264"); +} + + +void HTMLFormTest::testSubmit2() +{ + HTMLForm form; + form.set("field1", "value1"); + form.set("field2", "value 2"); + form.set("field3", "value=3"); + form.set("field4", "value&4"); + + HTTPRequest req("POST", "/form.cgi"); + form.prepareSubmit(req); + assert (req.getContentType() == HTMLForm::ENCODING_URL); +} + + +void HTMLFormTest::testSubmit3() +{ + HTMLForm form(HTMLForm::ENCODING_MULTIPART); + form.set("field1", "value1"); + form.set("field2", "value 2"); + form.set("field3", "value=3"); + form.set("field4", "value&4"); + + HTTPRequest req("POST", "/form.cgi", HTTPMessage::HTTP_1_1); + form.prepareSubmit(req); + std::string expCT(HTMLForm::ENCODING_MULTIPART); + expCT.append("; boundary=\""); + expCT.append(form.boundary()); + expCT.append("\""); + assert (req.getContentType() == expCT); + assert (req.getChunkedTransferEncoding()); +} + + +void HTMLFormTest::setUp() +{ +} + + +void HTMLFormTest::tearDown() +{ +} + + +CppUnit::Test* HTMLFormTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTMLFormTest"); + + CppUnit_addTest(pSuite, HTMLFormTest, testWriteUrl); + CppUnit_addTest(pSuite, HTMLFormTest, testWriteMultipart); + CppUnit_addTest(pSuite, HTMLFormTest, testReadUrl1); + CppUnit_addTest(pSuite, HTMLFormTest, testReadUrl2); + CppUnit_addTest(pSuite, HTMLFormTest, testReadMultipart); + CppUnit_addTest(pSuite, HTMLFormTest, testSubmit1); + CppUnit_addTest(pSuite, HTMLFormTest, testSubmit2); + CppUnit_addTest(pSuite, HTMLFormTest, testSubmit3); + + return pSuite; +} diff --git a/Net/testsuite/src/HTMLFormTest.h b/Net/testsuite/src/HTMLFormTest.h index 69326163a..afd677784 100644 --- a/Net/testsuite/src/HTMLFormTest.h +++ b/Net/testsuite/src/HTMLFormTest.h @@ -1,67 +1,67 @@ -// -// HTMLFormTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTMLFormTest.h#1 $ -// -// Definition of the HTMLFormTest 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 HTMLFormTest_INCLUDED -#define HTMLFormTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class HTMLFormTest: public CppUnit::TestCase -{ -public: - HTMLFormTest(const std::string& name); - ~HTMLFormTest(); - - void testWriteUrl(); - void testWriteMultipart(); - void testReadUrl1(); - void testReadUrl2(); - void testReadMultipart(); - void testSubmit1(); - void testSubmit2(); - void testSubmit3(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HTMLFormTest_INCLUDED +// +// HTMLFormTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTMLFormTest.h#1 $ +// +// Definition of the HTMLFormTest 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 HTMLFormTest_INCLUDED +#define HTMLFormTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class HTMLFormTest: public CppUnit::TestCase +{ +public: + HTMLFormTest(const std::string& name); + ~HTMLFormTest(); + + void testWriteUrl(); + void testWriteMultipart(); + void testReadUrl1(); + void testReadUrl2(); + void testReadMultipart(); + void testSubmit1(); + void testSubmit2(); + void testSubmit3(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HTMLFormTest_INCLUDED diff --git a/Net/testsuite/src/HTMLTestSuite.cpp b/Net/testsuite/src/HTMLTestSuite.cpp index f918ca455..fa42fbd64 100644 --- a/Net/testsuite/src/HTMLTestSuite.cpp +++ b/Net/testsuite/src/HTMLTestSuite.cpp @@ -1,44 +1,44 @@ -// -// HTMLTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTMLTestSuite.cpp#1 $ -// -// 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 "HTMLTestSuite.h" -#include "HTMLFormTest.h" - - -CppUnit::Test* HTMLTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTMLTestSuite"); - - pSuite->addTest(HTMLFormTest::suite()); - - return pSuite; -} +// +// HTMLTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTMLTestSuite.cpp#1 $ +// +// 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 "HTMLTestSuite.h" +#include "HTMLFormTest.h" + + +CppUnit::Test* HTMLTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTMLTestSuite"); + + pSuite->addTest(HTMLFormTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/HTMLTestSuite.h b/Net/testsuite/src/HTMLTestSuite.h index 228147b4e..28217e53d 100644 --- a/Net/testsuite/src/HTMLTestSuite.h +++ b/Net/testsuite/src/HTMLTestSuite.h @@ -1,49 +1,49 @@ -// -// HTMLTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTMLTestSuite.h#1 $ -// -// Definition of the HTMLTestSuite 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 HTMLTestSuite_INCLUDED -#define HTMLTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class HTMLTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // HTMLTestSuite_INCLUDED +// +// HTMLTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTMLTestSuite.h#1 $ +// +// Definition of the HTMLTestSuite 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 HTMLTestSuite_INCLUDED +#define HTMLTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class HTMLTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // HTMLTestSuite_INCLUDED diff --git a/Net/testsuite/src/HTTPClientSessionTest.cpp b/Net/testsuite/src/HTTPClientSessionTest.cpp index e8438ff73..00af1621f 100644 --- a/Net/testsuite/src/HTTPClientSessionTest.cpp +++ b/Net/testsuite/src/HTTPClientSessionTest.cpp @@ -1,307 +1,307 @@ -// -// HTTPClientSessionTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPClientSessionTest.cpp#1 $ -// -// 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 "HTTPClientSessionTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/HTTPClientSession.h" -#include "Poco/Net/HTTPRequest.h" -#include "Poco/Net/HTTPResponse.h" -#include "Poco/StreamCopier.h" -#include "HTTPTestServer.h" -#include -#include -#include - - -using Poco::Net::HTTPClientSession; -using Poco::Net::HTTPRequest; -using Poco::Net::HTTPResponse; -using Poco::Net::HTTPMessage; -using Poco::StreamCopier; - - -HTTPClientSessionTest::HTTPClientSessionTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HTTPClientSessionTest::~HTTPClientSessionTest() -{ -} - - -void HTTPClientSessionTest::testGetSmall() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_GET, "/small"); - s.sendRequest(request); - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (response.getContentLength() == HTTPTestServer::SMALL_BODY.length()); - assert (response.getContentType() == "text/plain"); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == HTTPTestServer::SMALL_BODY); -} - - -void HTTPClientSessionTest::testGetLarge() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_GET, "/large"); - s.sendRequest(request); - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (response.getContentLength() == HTTPTestServer::LARGE_BODY.length()); - assert (response.getContentType() == "text/plain"); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == HTTPTestServer::LARGE_BODY); -} - - -void HTTPClientSessionTest::testHead() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_HEAD, "/large"); - s.sendRequest(request); - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (response.getContentLength() == HTTPTestServer::LARGE_BODY.length()); - assert (response.getContentType() == "text/plain"); - std::ostringstream ostr; - assert (StreamCopier::copyStream(rs, ostr) == 0); -} - - -void HTTPClientSessionTest::testPostSmallIdentity() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); - std::string body("this is a random request body\r\n0\r\n"); - request.setContentLength((int) body.length()); - s.sendRequest(request) << body; - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (response.getContentLength() == body.length()); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == body); -} - - -void HTTPClientSessionTest::testPostLargeIdentity() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); - std::string body(8000, 'x'); - body.append("\r\n0\r\n"); - request.setContentLength((int) body.length()); - s.sendRequest(request) << body; - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (response.getContentLength() == body.length()); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == body); -} - - -void HTTPClientSessionTest::testPostSmallChunked() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); - std::string body("this is a random request body"); - request.setChunkedTransferEncoding(true); - s.sendRequest(request) << body; - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (response.getChunkedTransferEncoding()); - assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == body); -} - - -void HTTPClientSessionTest::testPostLargeChunked() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); - std::string body(16000, 'x'); - request.setChunkedTransferEncoding(true); - s.sendRequest(request) << body; - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (response.getChunkedTransferEncoding()); - assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == body); -} - - -void HTTPClientSessionTest::testPostSmallClose() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); - std::string body("this is a random request body"); - s.sendRequest(request) << body; - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (!response.getChunkedTransferEncoding()); - assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == body); -} - - -void HTTPClientSessionTest::testPostLargeClose() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); - std::string body(8000, 'x'); - s.sendRequest(request) << body; - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (!response.getChunkedTransferEncoding()); - assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == body); -} - - -void HTTPClientSessionTest::testKeepAlive() -{ - HTTPTestServer srv; - HTTPClientSession s("localhost", srv.port()); - s.setKeepAlive(true); - HTTPRequest request(HTTPRequest::HTTP_HEAD, "/keepAlive", HTTPMessage::HTTP_1_1); - s.sendRequest(request); - HTTPResponse response; - std::istream& rs1 = s.receiveResponse(response); - assert (response.getContentLength() == HTTPTestServer::SMALL_BODY.length()); - assert (response.getContentType() == "text/plain"); - assert (response.getKeepAlive()); - std::ostringstream ostr1; - assert (StreamCopier::copyStream(rs1, ostr1) == 0); - - request.setMethod(HTTPRequest::HTTP_GET); - request.setURI("/small"); - s.sendRequest(request); - std::istream& rs2 = s.receiveResponse(response); - assert (response.getContentLength() == HTTPTestServer::SMALL_BODY.length()); - assert (response.getKeepAlive()); - std::ostringstream ostr2; - StreamCopier::copyStream(rs2, ostr2); - assert (ostr2.str() == HTTPTestServer::SMALL_BODY); - - request.setMethod(HTTPRequest::HTTP_GET); - request.setURI("/large"); - s.sendRequest(request); - std::istream& rs3 = s.receiveResponse(response); - assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); - assert (response.getChunkedTransferEncoding()); - assert (response.getKeepAlive()); - std::ostringstream ostr3; - int n = StreamCopier::copyStream(rs3, ostr3); - assert (ostr3.str() == HTTPTestServer::LARGE_BODY); - - request.setMethod(HTTPRequest::HTTP_HEAD); - request.setURI("/large"); - s.sendRequest(request); - std::istream& rs4= s.receiveResponse(response); - assert (response.getContentLength() == HTTPTestServer::LARGE_BODY.length()); - assert (response.getContentType() == "text/plain"); - assert (!response.getKeepAlive()); - std::ostringstream ostr4; - assert (StreamCopier::copyStream(rs4, ostr4) == 0); -} - - -void HTTPClientSessionTest::testProxy() -{ - HTTPTestServer srv; - HTTPClientSession s("www.somehost.com"); - s.setProxy("localhost", srv.port()); - HTTPRequest request(HTTPRequest::HTTP_GET, "/large"); - s.sendRequest(request); - HTTPResponse response; - std::istream& rs = s.receiveResponse(response); - assert (response.getContentLength() == HTTPTestServer::LARGE_BODY.length()); - assert (response.getContentType() == "text/plain"); - std::ostringstream ostr; - StreamCopier::copyStream(rs, ostr); - assert (ostr.str() == HTTPTestServer::LARGE_BODY); -} - - -void HTTPClientSessionTest::setUp() -{ -} - - -void HTTPClientSessionTest::tearDown() -{ -} - - -CppUnit::Test* HTTPClientSessionTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPClientSessionTest"); - - CppUnit_addTest(pSuite, HTTPClientSessionTest, testGetSmall); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testGetLarge); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testHead); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostSmallIdentity); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostLargeIdentity); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostSmallChunked); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostLargeChunked); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostSmallClose); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostLargeClose); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testKeepAlive); - CppUnit_addTest(pSuite, HTTPClientSessionTest, testProxy); - - return pSuite; -} +// +// HTTPClientSessionTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPClientSessionTest.cpp#1 $ +// +// 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 "HTTPClientSessionTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/HTTPClientSession.h" +#include "Poco/Net/HTTPRequest.h" +#include "Poco/Net/HTTPResponse.h" +#include "Poco/StreamCopier.h" +#include "HTTPTestServer.h" +#include +#include +#include + + +using Poco::Net::HTTPClientSession; +using Poco::Net::HTTPRequest; +using Poco::Net::HTTPResponse; +using Poco::Net::HTTPMessage; +using Poco::StreamCopier; + + +HTTPClientSessionTest::HTTPClientSessionTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HTTPClientSessionTest::~HTTPClientSessionTest() +{ +} + + +void HTTPClientSessionTest::testGetSmall() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_GET, "/small"); + s.sendRequest(request); + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (response.getContentLength() == HTTPTestServer::SMALL_BODY.length()); + assert (response.getContentType() == "text/plain"); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == HTTPTestServer::SMALL_BODY); +} + + +void HTTPClientSessionTest::testGetLarge() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_GET, "/large"); + s.sendRequest(request); + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (response.getContentLength() == HTTPTestServer::LARGE_BODY.length()); + assert (response.getContentType() == "text/plain"); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == HTTPTestServer::LARGE_BODY); +} + + +void HTTPClientSessionTest::testHead() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_HEAD, "/large"); + s.sendRequest(request); + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (response.getContentLength() == HTTPTestServer::LARGE_BODY.length()); + assert (response.getContentType() == "text/plain"); + std::ostringstream ostr; + assert (StreamCopier::copyStream(rs, ostr) == 0); +} + + +void HTTPClientSessionTest::testPostSmallIdentity() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); + std::string body("this is a random request body\r\n0\r\n"); + request.setContentLength((int) body.length()); + s.sendRequest(request) << body; + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (response.getContentLength() == body.length()); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == body); +} + + +void HTTPClientSessionTest::testPostLargeIdentity() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); + std::string body(8000, 'x'); + body.append("\r\n0\r\n"); + request.setContentLength((int) body.length()); + s.sendRequest(request) << body; + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (response.getContentLength() == body.length()); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == body); +} + + +void HTTPClientSessionTest::testPostSmallChunked() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); + std::string body("this is a random request body"); + request.setChunkedTransferEncoding(true); + s.sendRequest(request) << body; + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (response.getChunkedTransferEncoding()); + assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == body); +} + + +void HTTPClientSessionTest::testPostLargeChunked() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); + std::string body(16000, 'x'); + request.setChunkedTransferEncoding(true); + s.sendRequest(request) << body; + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (response.getChunkedTransferEncoding()); + assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == body); +} + + +void HTTPClientSessionTest::testPostSmallClose() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); + std::string body("this is a random request body"); + s.sendRequest(request) << body; + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (!response.getChunkedTransferEncoding()); + assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == body); +} + + +void HTTPClientSessionTest::testPostLargeClose() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_POST, "/echo"); + std::string body(8000, 'x'); + s.sendRequest(request) << body; + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (!response.getChunkedTransferEncoding()); + assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == body); +} + + +void HTTPClientSessionTest::testKeepAlive() +{ + HTTPTestServer srv; + HTTPClientSession s("localhost", srv.port()); + s.setKeepAlive(true); + HTTPRequest request(HTTPRequest::HTTP_HEAD, "/keepAlive", HTTPMessage::HTTP_1_1); + s.sendRequest(request); + HTTPResponse response; + std::istream& rs1 = s.receiveResponse(response); + assert (response.getContentLength() == HTTPTestServer::SMALL_BODY.length()); + assert (response.getContentType() == "text/plain"); + assert (response.getKeepAlive()); + std::ostringstream ostr1; + assert (StreamCopier::copyStream(rs1, ostr1) == 0); + + request.setMethod(HTTPRequest::HTTP_GET); + request.setURI("/small"); + s.sendRequest(request); + std::istream& rs2 = s.receiveResponse(response); + assert (response.getContentLength() == HTTPTestServer::SMALL_BODY.length()); + assert (response.getKeepAlive()); + std::ostringstream ostr2; + StreamCopier::copyStream(rs2, ostr2); + assert (ostr2.str() == HTTPTestServer::SMALL_BODY); + + request.setMethod(HTTPRequest::HTTP_GET); + request.setURI("/large"); + s.sendRequest(request); + std::istream& rs3 = s.receiveResponse(response); + assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH); + assert (response.getChunkedTransferEncoding()); + assert (response.getKeepAlive()); + std::ostringstream ostr3; + int n = StreamCopier::copyStream(rs3, ostr3); + assert (ostr3.str() == HTTPTestServer::LARGE_BODY); + + request.setMethod(HTTPRequest::HTTP_HEAD); + request.setURI("/large"); + s.sendRequest(request); + std::istream& rs4= s.receiveResponse(response); + assert (response.getContentLength() == HTTPTestServer::LARGE_BODY.length()); + assert (response.getContentType() == "text/plain"); + assert (!response.getKeepAlive()); + std::ostringstream ostr4; + assert (StreamCopier::copyStream(rs4, ostr4) == 0); +} + + +void HTTPClientSessionTest::testProxy() +{ + HTTPTestServer srv; + HTTPClientSession s("www.somehost.com"); + s.setProxy("localhost", srv.port()); + HTTPRequest request(HTTPRequest::HTTP_GET, "/large"); + s.sendRequest(request); + HTTPResponse response; + std::istream& rs = s.receiveResponse(response); + assert (response.getContentLength() == HTTPTestServer::LARGE_BODY.length()); + assert (response.getContentType() == "text/plain"); + std::ostringstream ostr; + StreamCopier::copyStream(rs, ostr); + assert (ostr.str() == HTTPTestServer::LARGE_BODY); +} + + +void HTTPClientSessionTest::setUp() +{ +} + + +void HTTPClientSessionTest::tearDown() +{ +} + + +CppUnit::Test* HTTPClientSessionTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPClientSessionTest"); + + CppUnit_addTest(pSuite, HTTPClientSessionTest, testGetSmall); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testGetLarge); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testHead); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostSmallIdentity); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostLargeIdentity); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostSmallChunked); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostLargeChunked); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostSmallClose); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testPostLargeClose); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testKeepAlive); + CppUnit_addTest(pSuite, HTTPClientSessionTest, testProxy); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPClientSessionTest.h b/Net/testsuite/src/HTTPClientSessionTest.h index d3980a45f..400549971 100644 --- a/Net/testsuite/src/HTTPClientSessionTest.h +++ b/Net/testsuite/src/HTTPClientSessionTest.h @@ -1,70 +1,70 @@ -// -// HTTPClientSessionTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPClientSessionTest.h#1 $ -// -// Definition of the HTTPClientSessionTest 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 HTTPClientSessionTest_INCLUDED -#define HTTPClientSessionTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class HTTPClientSessionTest: public CppUnit::TestCase -{ -public: - HTTPClientSessionTest(const std::string& name); - ~HTTPClientSessionTest(); - - void testGetSmall(); - void testGetLarge(); - void testHead(); - void testPostSmallIdentity(); - void testPostLargeIdentity(); - void testPostSmallChunked(); - void testPostLargeChunked(); - void testPostSmallClose(); - void testPostLargeClose(); - void testKeepAlive(); - void testProxy(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HTTPClientSessionTest_INCLUDED +// +// HTTPClientSessionTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPClientSessionTest.h#1 $ +// +// Definition of the HTTPClientSessionTest 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 HTTPClientSessionTest_INCLUDED +#define HTTPClientSessionTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class HTTPClientSessionTest: public CppUnit::TestCase +{ +public: + HTTPClientSessionTest(const std::string& name); + ~HTTPClientSessionTest(); + + void testGetSmall(); + void testGetLarge(); + void testHead(); + void testPostSmallIdentity(); + void testPostLargeIdentity(); + void testPostSmallChunked(); + void testPostLargeChunked(); + void testPostSmallClose(); + void testPostLargeClose(); + void testKeepAlive(); + void testProxy(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HTTPClientSessionTest_INCLUDED diff --git a/Net/testsuite/src/HTTPClientTestSuite.cpp b/Net/testsuite/src/HTTPClientTestSuite.cpp index 06f7da19f..18eacae09 100644 --- a/Net/testsuite/src/HTTPClientTestSuite.cpp +++ b/Net/testsuite/src/HTTPClientTestSuite.cpp @@ -1,46 +1,46 @@ -// -// HTTPClientTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPClientTestSuite.cpp#1 $ -// -// 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 "HTTPClientTestSuite.h" -#include "HTTPClientSessionTest.h" -#include "HTTPStreamFactoryTest.h" - - -CppUnit::Test* HTTPClientTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPClientTestSuite"); - - pSuite->addTest(HTTPClientSessionTest::suite()); - pSuite->addTest(HTTPStreamFactoryTest::suite()); - - return pSuite; -} +// +// HTTPClientTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPClientTestSuite.cpp#1 $ +// +// 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 "HTTPClientTestSuite.h" +#include "HTTPClientSessionTest.h" +#include "HTTPStreamFactoryTest.h" + + +CppUnit::Test* HTTPClientTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPClientTestSuite"); + + pSuite->addTest(HTTPClientSessionTest::suite()); + pSuite->addTest(HTTPStreamFactoryTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPClientTestSuite.h b/Net/testsuite/src/HTTPClientTestSuite.h index 5adfe9e98..e55456833 100644 --- a/Net/testsuite/src/HTTPClientTestSuite.h +++ b/Net/testsuite/src/HTTPClientTestSuite.h @@ -1,49 +1,49 @@ -// -// HTTPClientTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPClientTestSuite.h#1 $ -// -// Definition of the HTTPClientTestSuite 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 HTTPClientTestSuite_INCLUDED -#define HTTPClientTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class HTTPClientTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // HTTPClientTestSuite_INCLUDED +// +// HTTPClientTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPClientTestSuite.h#1 $ +// +// Definition of the HTTPClientTestSuite 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 HTTPClientTestSuite_INCLUDED +#define HTTPClientTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class HTTPClientTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // HTTPClientTestSuite_INCLUDED diff --git a/Net/testsuite/src/HTTPCookieTest.cpp b/Net/testsuite/src/HTTPCookieTest.cpp index c3f66923f..76a60cfac 100644 --- a/Net/testsuite/src/HTTPCookieTest.cpp +++ b/Net/testsuite/src/HTTPCookieTest.cpp @@ -1,93 +1,93 @@ -// -// HTTPCookieTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPCookieTest.cpp#1 $ -// -// 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 "HTTPCookieTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/HTTPCookie.h" - - -using Poco::Net::HTTPCookie; - - -HTTPCookieTest::HTTPCookieTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HTTPCookieTest::~HTTPCookieTest() -{ -} - - -void HTTPCookieTest::testCookie() -{ - HTTPCookie cookie("name", "value"); - assert (cookie.getName() == "name"); - assert (cookie.getValue() == "value"); - assert (cookie.toString() == "name=value"); - cookie.setPath("/"); - assert (cookie.toString() == "name=value; path=/"); - cookie.setComment("comment"); - assert (cookie.toString() == "name=value; path=/"); - cookie.setDomain("appinf.com"); - assert (cookie.toString() == "name=value; domain=appinf.com; path=/"); - cookie.setSecure(true); - assert (cookie.toString() == "name=value; domain=appinf.com; path=/; secure"); - - cookie.setVersion(1); - assert (cookie.toString() == "name=\"value\"; Comment=\"comment\"; Domain=\"appinf.com\"; Path=\"/\"; secure; Version=\"1\""); - - cookie.setSecure(false); - cookie.setMaxAge(100); - assert (cookie.toString() == "name=\"value\"; Comment=\"comment\"; Domain=\"appinf.com\"; Path=\"/\"; Max-Age=\"100\"; Version=\"1\""); -} - - -void HTTPCookieTest::setUp() -{ -} - - -void HTTPCookieTest::tearDown() -{ -} - - -CppUnit::Test* HTTPCookieTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPCookieTest"); - - CppUnit_addTest(pSuite, HTTPCookieTest, testCookie); - - return pSuite; -} +// +// HTTPCookieTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPCookieTest.cpp#1 $ +// +// 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 "HTTPCookieTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/HTTPCookie.h" + + +using Poco::Net::HTTPCookie; + + +HTTPCookieTest::HTTPCookieTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HTTPCookieTest::~HTTPCookieTest() +{ +} + + +void HTTPCookieTest::testCookie() +{ + HTTPCookie cookie("name", "value"); + assert (cookie.getName() == "name"); + assert (cookie.getValue() == "value"); + assert (cookie.toString() == "name=value"); + cookie.setPath("/"); + assert (cookie.toString() == "name=value; path=/"); + cookie.setComment("comment"); + assert (cookie.toString() == "name=value; path=/"); + cookie.setDomain("appinf.com"); + assert (cookie.toString() == "name=value; domain=appinf.com; path=/"); + cookie.setSecure(true); + assert (cookie.toString() == "name=value; domain=appinf.com; path=/; secure"); + + cookie.setVersion(1); + assert (cookie.toString() == "name=\"value\"; Comment=\"comment\"; Domain=\"appinf.com\"; Path=\"/\"; secure; Version=\"1\""); + + cookie.setSecure(false); + cookie.setMaxAge(100); + assert (cookie.toString() == "name=\"value\"; Comment=\"comment\"; Domain=\"appinf.com\"; Path=\"/\"; Max-Age=\"100\"; Version=\"1\""); +} + + +void HTTPCookieTest::setUp() +{ +} + + +void HTTPCookieTest::tearDown() +{ +} + + +CppUnit::Test* HTTPCookieTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPCookieTest"); + + CppUnit_addTest(pSuite, HTTPCookieTest, testCookie); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPCookieTest.h b/Net/testsuite/src/HTTPCookieTest.h index c53c025be..4ccc04470 100644 --- a/Net/testsuite/src/HTTPCookieTest.h +++ b/Net/testsuite/src/HTTPCookieTest.h @@ -1,60 +1,60 @@ -// -// HTTPCookieTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPCookieTest.h#1 $ -// -// Definition of the HTTPCookieTest 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 HTTPCookieTest_INCLUDED -#define HTTPCookieTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class HTTPCookieTest: public CppUnit::TestCase -{ -public: - HTTPCookieTest(const std::string& name); - ~HTTPCookieTest(); - - void testCookie(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HTTPCookieTest_INCLUDED +// +// HTTPCookieTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPCookieTest.h#1 $ +// +// Definition of the HTTPCookieTest 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 HTTPCookieTest_INCLUDED +#define HTTPCookieTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class HTTPCookieTest: public CppUnit::TestCase +{ +public: + HTTPCookieTest(const std::string& name); + ~HTTPCookieTest(); + + void testCookie(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HTTPCookieTest_INCLUDED diff --git a/Net/testsuite/src/HTTPCredentialsTest.cpp b/Net/testsuite/src/HTTPCredentialsTest.cpp index 90eb56280..d745ff3da 100644 --- a/Net/testsuite/src/HTTPCredentialsTest.cpp +++ b/Net/testsuite/src/HTTPCredentialsTest.cpp @@ -1,125 +1,125 @@ -// -// HTTPCredentialsTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPCredentialsTest.cpp#1 $ -// -// 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 "HTTPCredentialsTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/HTTPRequest.h" -#include "Poco/Net/HTTPBasicCredentials.h" -#include "Poco/Net/NetException.h" - - -using Poco::Net::HTTPRequest; -using Poco::Net::HTTPBasicCredentials; -using Poco::Net::NotAuthenticatedException; - - -HTTPCredentialsTest::HTTPCredentialsTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HTTPCredentialsTest::~HTTPCredentialsTest() -{ -} - - -void HTTPCredentialsTest::testCredentials() -{ - HTTPRequest request; - assert (!request.hasCredentials()); - - HTTPBasicCredentials cred("user", "secret"); - cred.authenticate(request); - assert (request.hasCredentials()); - std::string scheme; - std::string info; - request.getCredentials(scheme, info); - assert (scheme == "Basic"); - assert (info == "dXNlcjpzZWNyZXQ="); - - HTTPBasicCredentials cred2(request); - assert (cred2.getUsername() == "user"); - assert (cred2.getPassword() == "secret"); -} - - -void HTTPCredentialsTest::testBadCredentials() -{ - HTTPRequest request; - - std::string scheme; - std::string info; - try - { - request.getCredentials(scheme, info); - fail("no credentials - must throw"); - } - catch (NotAuthenticatedException&) - { - } - - request.setCredentials("Test", "SomeData"); - request.getCredentials(scheme, info); - assert (scheme == "Test"); - assert (info == "SomeData"); - - try - { - HTTPBasicCredentials cred(request); - fail("bad scheme - must throw"); - } - catch (NotAuthenticatedException&) - { - } -} - - -void HTTPCredentialsTest::setUp() -{ -} - - -void HTTPCredentialsTest::tearDown() -{ -} - - -CppUnit::Test* HTTPCredentialsTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPCredentialsTest"); - - CppUnit_addTest(pSuite, HTTPCredentialsTest, testCredentials); - CppUnit_addTest(pSuite, HTTPCredentialsTest, testBadCredentials); - - return pSuite; -} +// +// HTTPCredentialsTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPCredentialsTest.cpp#1 $ +// +// 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 "HTTPCredentialsTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/HTTPRequest.h" +#include "Poco/Net/HTTPBasicCredentials.h" +#include "Poco/Net/NetException.h" + + +using Poco::Net::HTTPRequest; +using Poco::Net::HTTPBasicCredentials; +using Poco::Net::NotAuthenticatedException; + + +HTTPCredentialsTest::HTTPCredentialsTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HTTPCredentialsTest::~HTTPCredentialsTest() +{ +} + + +void HTTPCredentialsTest::testCredentials() +{ + HTTPRequest request; + assert (!request.hasCredentials()); + + HTTPBasicCredentials cred("user", "secret"); + cred.authenticate(request); + assert (request.hasCredentials()); + std::string scheme; + std::string info; + request.getCredentials(scheme, info); + assert (scheme == "Basic"); + assert (info == "dXNlcjpzZWNyZXQ="); + + HTTPBasicCredentials cred2(request); + assert (cred2.getUsername() == "user"); + assert (cred2.getPassword() == "secret"); +} + + +void HTTPCredentialsTest::testBadCredentials() +{ + HTTPRequest request; + + std::string scheme; + std::string info; + try + { + request.getCredentials(scheme, info); + fail("no credentials - must throw"); + } + catch (NotAuthenticatedException&) + { + } + + request.setCredentials("Test", "SomeData"); + request.getCredentials(scheme, info); + assert (scheme == "Test"); + assert (info == "SomeData"); + + try + { + HTTPBasicCredentials cred(request); + fail("bad scheme - must throw"); + } + catch (NotAuthenticatedException&) + { + } +} + + +void HTTPCredentialsTest::setUp() +{ +} + + +void HTTPCredentialsTest::tearDown() +{ +} + + +CppUnit::Test* HTTPCredentialsTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPCredentialsTest"); + + CppUnit_addTest(pSuite, HTTPCredentialsTest, testCredentials); + CppUnit_addTest(pSuite, HTTPCredentialsTest, testBadCredentials); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPCredentialsTest.h b/Net/testsuite/src/HTTPCredentialsTest.h index 19d31e16c..2ae5726cb 100644 --- a/Net/testsuite/src/HTTPCredentialsTest.h +++ b/Net/testsuite/src/HTTPCredentialsTest.h @@ -1,61 +1,61 @@ -// -// HTTPCredentialsTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPCredentialsTest.h#1 $ -// -// Definition of the HTTPCredentialsTest 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 HTTPCredentialsTest_INCLUDED -#define HTTPCredentialsTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class HTTPCredentialsTest: public CppUnit::TestCase -{ -public: - HTTPCredentialsTest(const std::string& name); - ~HTTPCredentialsTest(); - - void testCredentials(); - void testBadCredentials(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HTTPCredentialsTest_INCLUDED +// +// HTTPCredentialsTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPCredentialsTest.h#1 $ +// +// Definition of the HTTPCredentialsTest 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 HTTPCredentialsTest_INCLUDED +#define HTTPCredentialsTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class HTTPCredentialsTest: public CppUnit::TestCase +{ +public: + HTTPCredentialsTest(const std::string& name); + ~HTTPCredentialsTest(); + + void testCredentials(); + void testBadCredentials(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HTTPCredentialsTest_INCLUDED diff --git a/Net/testsuite/src/HTTPRequestTest.cpp b/Net/testsuite/src/HTTPRequestTest.cpp index 58d51fb13..5e324d0af 100644 --- a/Net/testsuite/src/HTTPRequestTest.cpp +++ b/Net/testsuite/src/HTTPRequestTest.cpp @@ -1,246 +1,246 @@ -// -// HTTPRequestTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPRequestTest.cpp#1 $ -// -// 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 "HTTPRequestTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/HTTPRequest.h" -#include "Poco/Net/NetException.h" -#include - - -using Poco::Net::HTTPRequest; -using Poco::Net::HTTPMessage; -using Poco::Net::MessageException; -using Poco::Net::NameValueCollection; - - -HTTPRequestTest::HTTPRequestTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HTTPRequestTest::~HTTPRequestTest() -{ -} - - -void HTTPRequestTest::testWrite1() -{ - HTTPRequest request; - std::ostringstream ostr; - request.write(ostr); - std::string s = ostr.str(); - assert (s == "GET / HTTP/1.0\r\n\r\n"); -} - - -void HTTPRequestTest::testWrite2() -{ - HTTPRequest request(HTTPRequest::HTTP_HEAD, "/index.html", HTTPMessage::HTTP_1_1); - request.setHost("localhost", 80); - request.setKeepAlive(true); - request.set("User-Agent", "Poco"); - std::ostringstream ostr; - request.write(ostr); - std::string s = ostr.str(); - assert (s == "HEAD /index.html HTTP/1.1\r\nConnection: Keep-Alive\r\nHost: localhost\r\nUser-Agent: Poco\r\n\r\n"); -} - - -void HTTPRequestTest::testWrite3() -{ - HTTPRequest request(HTTPRequest::HTTP_POST, "/test.cgi", HTTPMessage::HTTP_1_1); - request.setHost("localhost", 8000); - request.setKeepAlive(false); - request.set("User-Agent", "Poco"); - request.setContentLength(100); - request.setContentType("text/plain"); - std::ostringstream ostr; - request.write(ostr); - std::string s = ostr.str(); - assert (s == "POST /test.cgi HTTP/1.1\r\nConnection: Close\r\nContent-Length: 100\r\nContent-Type: text/plain\r\nHost: localhost:8000\r\nUser-Agent: Poco\r\n\r\n"); -} - - -void HTTPRequestTest::testRead1() -{ - std::string s("GET / HTTP/1.0\r\n\r\n"); - std::istringstream istr(s); - HTTPRequest request; - request.read(istr); - assert (request.getMethod() == HTTPRequest::HTTP_GET); - assert (request.getURI() == "/"); - assert (request.getVersion() == HTTPMessage::HTTP_1_0); - assert (request.empty()); - assert (istr.get() == -1); -} - - -void HTTPRequestTest::testRead2() -{ - std::string s("HEAD /index.html HTTP/1.1\r\nConnection: Keep-Alive\r\nHost: localhost\r\nUser-Agent: Poco\r\n\r\n"); - std::istringstream istr(s); - HTTPRequest request; - request.read(istr); - assert (request.getMethod() == HTTPRequest::HTTP_HEAD); - assert (request.getURI() == "/index.html"); - assert (request.getVersion() == HTTPMessage::HTTP_1_1); - assert (request.size() == 3); - assert (request["Connection"] == "Keep-Alive"); - assert (request["Host"] == "localhost"); - assert (request["User-Agent"] == "Poco"); - assert (istr.get() == -1); -} - - -void HTTPRequestTest::testRead3() -{ - std::string s("POST /test.cgi HTTP/1.1\r\nConnection: Close\r\nContent-Length: 100\r\nContent-Type: text/plain\r\nHost: localhost:8000\r\nUser-Agent: Poco\r\n\r\n"); - std::istringstream istr(s); - HTTPRequest request; - request.read(istr); - assert (request.getMethod() == HTTPRequest::HTTP_POST); - assert (request.getURI() == "/test.cgi"); - assert (request.getVersion() == HTTPMessage::HTTP_1_1); - assert (request.size() == 5); - assert (request["Connection"] == "Close"); - assert (request["Host"] == "localhost:8000"); - assert (request["User-Agent"] == "Poco"); - assert (request.getContentType() == "text/plain"); - assert (request.getContentLength() == 100); - assert (istr.get() == -1); -} - - -void HTTPRequestTest::testInvalid1() -{ - std::string s(256, 'x'); - std::istringstream istr(s); - HTTPRequest request; - try - { - request.read(istr); - fail("inavalid request - must throw"); - } - catch (MessageException&) - { - } -} - - -void HTTPRequestTest::testInvalid2() -{ - std::string s("GET "); - s.append(8000, 'x'); - s.append("HTTP/1.0"); - std::istringstream istr(s); - HTTPRequest request; - try - { - request.read(istr); - fail("inavalid request - must throw"); - } - catch (MessageException&) - { - } -} - - -void HTTPRequestTest::testInvalid3() -{ - std::string s("GET / HTTP/1.10"); - std::istringstream istr(s); - HTTPRequest request; - try - { - request.read(istr); - fail("inavalid request - must throw"); - } - catch (MessageException&) - { - } -} - - -void HTTPRequestTest::testCookies() -{ - HTTPRequest request1; - NameValueCollection cookies1; - cookies1.add("cookie1", "value1"); - request1.setCookies(cookies1); - assert (request1["Cookie"] == "cookie1=value1"); - - HTTPRequest request2; - NameValueCollection cookies2; - cookies2.add("cookie2", "value2"); - cookies2.add("cookie3", "value3"); - request2.setCookies(cookies2); - assert (request2["Cookie"] == "cookie2=value2; cookie3=value3"); - - request1.setCookies(cookies2); - NameValueCollection cookies3; - request1.getCookies(cookies3); - assert (cookies3.size() == 3); - assert (cookies3["cookie1"] == "value1"); - assert (cookies3["cookie2"] == "value2"); - assert (cookies3["cookie3"] == "value3"); -} - - -void HTTPRequestTest::setUp() -{ -} - - -void HTTPRequestTest::tearDown() -{ -} - - -CppUnit::Test* HTTPRequestTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPRequestTest"); - - CppUnit_addTest(pSuite, HTTPRequestTest, testWrite1); - CppUnit_addTest(pSuite, HTTPRequestTest, testWrite2); - CppUnit_addTest(pSuite, HTTPRequestTest, testWrite3); - CppUnit_addTest(pSuite, HTTPRequestTest, testRead1); - CppUnit_addTest(pSuite, HTTPRequestTest, testRead2); - CppUnit_addTest(pSuite, HTTPRequestTest, testRead3); - CppUnit_addTest(pSuite, HTTPRequestTest, testInvalid1); - CppUnit_addTest(pSuite, HTTPRequestTest, testInvalid2); - CppUnit_addTest(pSuite, HTTPRequestTest, testInvalid3); - CppUnit_addTest(pSuite, HTTPRequestTest, testCookies); - - return pSuite; -} +// +// HTTPRequestTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPRequestTest.cpp#1 $ +// +// 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 "HTTPRequestTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/HTTPRequest.h" +#include "Poco/Net/NetException.h" +#include + + +using Poco::Net::HTTPRequest; +using Poco::Net::HTTPMessage; +using Poco::Net::MessageException; +using Poco::Net::NameValueCollection; + + +HTTPRequestTest::HTTPRequestTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HTTPRequestTest::~HTTPRequestTest() +{ +} + + +void HTTPRequestTest::testWrite1() +{ + HTTPRequest request; + std::ostringstream ostr; + request.write(ostr); + std::string s = ostr.str(); + assert (s == "GET / HTTP/1.0\r\n\r\n"); +} + + +void HTTPRequestTest::testWrite2() +{ + HTTPRequest request(HTTPRequest::HTTP_HEAD, "/index.html", HTTPMessage::HTTP_1_1); + request.setHost("localhost", 80); + request.setKeepAlive(true); + request.set("User-Agent", "Poco"); + std::ostringstream ostr; + request.write(ostr); + std::string s = ostr.str(); + assert (s == "HEAD /index.html HTTP/1.1\r\nConnection: Keep-Alive\r\nHost: localhost\r\nUser-Agent: Poco\r\n\r\n"); +} + + +void HTTPRequestTest::testWrite3() +{ + HTTPRequest request(HTTPRequest::HTTP_POST, "/test.cgi", HTTPMessage::HTTP_1_1); + request.setHost("localhost", 8000); + request.setKeepAlive(false); + request.set("User-Agent", "Poco"); + request.setContentLength(100); + request.setContentType("text/plain"); + std::ostringstream ostr; + request.write(ostr); + std::string s = ostr.str(); + assert (s == "POST /test.cgi HTTP/1.1\r\nConnection: Close\r\nContent-Length: 100\r\nContent-Type: text/plain\r\nHost: localhost:8000\r\nUser-Agent: Poco\r\n\r\n"); +} + + +void HTTPRequestTest::testRead1() +{ + std::string s("GET / HTTP/1.0\r\n\r\n"); + std::istringstream istr(s); + HTTPRequest request; + request.read(istr); + assert (request.getMethod() == HTTPRequest::HTTP_GET); + assert (request.getURI() == "/"); + assert (request.getVersion() == HTTPMessage::HTTP_1_0); + assert (request.empty()); + assert (istr.get() == -1); +} + + +void HTTPRequestTest::testRead2() +{ + std::string s("HEAD /index.html HTTP/1.1\r\nConnection: Keep-Alive\r\nHost: localhost\r\nUser-Agent: Poco\r\n\r\n"); + std::istringstream istr(s); + HTTPRequest request; + request.read(istr); + assert (request.getMethod() == HTTPRequest::HTTP_HEAD); + assert (request.getURI() == "/index.html"); + assert (request.getVersion() == HTTPMessage::HTTP_1_1); + assert (request.size() == 3); + assert (request["Connection"] == "Keep-Alive"); + assert (request["Host"] == "localhost"); + assert (request["User-Agent"] == "Poco"); + assert (istr.get() == -1); +} + + +void HTTPRequestTest::testRead3() +{ + std::string s("POST /test.cgi HTTP/1.1\r\nConnection: Close\r\nContent-Length: 100\r\nContent-Type: text/plain\r\nHost: localhost:8000\r\nUser-Agent: Poco\r\n\r\n"); + std::istringstream istr(s); + HTTPRequest request; + request.read(istr); + assert (request.getMethod() == HTTPRequest::HTTP_POST); + assert (request.getURI() == "/test.cgi"); + assert (request.getVersion() == HTTPMessage::HTTP_1_1); + assert (request.size() == 5); + assert (request["Connection"] == "Close"); + assert (request["Host"] == "localhost:8000"); + assert (request["User-Agent"] == "Poco"); + assert (request.getContentType() == "text/plain"); + assert (request.getContentLength() == 100); + assert (istr.get() == -1); +} + + +void HTTPRequestTest::testInvalid1() +{ + std::string s(256, 'x'); + std::istringstream istr(s); + HTTPRequest request; + try + { + request.read(istr); + fail("inavalid request - must throw"); + } + catch (MessageException&) + { + } +} + + +void HTTPRequestTest::testInvalid2() +{ + std::string s("GET "); + s.append(8000, 'x'); + s.append("HTTP/1.0"); + std::istringstream istr(s); + HTTPRequest request; + try + { + request.read(istr); + fail("inavalid request - must throw"); + } + catch (MessageException&) + { + } +} + + +void HTTPRequestTest::testInvalid3() +{ + std::string s("GET / HTTP/1.10"); + std::istringstream istr(s); + HTTPRequest request; + try + { + request.read(istr); + fail("inavalid request - must throw"); + } + catch (MessageException&) + { + } +} + + +void HTTPRequestTest::testCookies() +{ + HTTPRequest request1; + NameValueCollection cookies1; + cookies1.add("cookie1", "value1"); + request1.setCookies(cookies1); + assert (request1["Cookie"] == "cookie1=value1"); + + HTTPRequest request2; + NameValueCollection cookies2; + cookies2.add("cookie2", "value2"); + cookies2.add("cookie3", "value3"); + request2.setCookies(cookies2); + assert (request2["Cookie"] == "cookie2=value2; cookie3=value3"); + + request1.setCookies(cookies2); + NameValueCollection cookies3; + request1.getCookies(cookies3); + assert (cookies3.size() == 3); + assert (cookies3["cookie1"] == "value1"); + assert (cookies3["cookie2"] == "value2"); + assert (cookies3["cookie3"] == "value3"); +} + + +void HTTPRequestTest::setUp() +{ +} + + +void HTTPRequestTest::tearDown() +{ +} + + +CppUnit::Test* HTTPRequestTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPRequestTest"); + + CppUnit_addTest(pSuite, HTTPRequestTest, testWrite1); + CppUnit_addTest(pSuite, HTTPRequestTest, testWrite2); + CppUnit_addTest(pSuite, HTTPRequestTest, testWrite3); + CppUnit_addTest(pSuite, HTTPRequestTest, testRead1); + CppUnit_addTest(pSuite, HTTPRequestTest, testRead2); + CppUnit_addTest(pSuite, HTTPRequestTest, testRead3); + CppUnit_addTest(pSuite, HTTPRequestTest, testInvalid1); + CppUnit_addTest(pSuite, HTTPRequestTest, testInvalid2); + CppUnit_addTest(pSuite, HTTPRequestTest, testInvalid3); + CppUnit_addTest(pSuite, HTTPRequestTest, testCookies); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPRequestTest.h b/Net/testsuite/src/HTTPRequestTest.h index c99437689..2b2c1a6c6 100644 --- a/Net/testsuite/src/HTTPRequestTest.h +++ b/Net/testsuite/src/HTTPRequestTest.h @@ -1,69 +1,69 @@ -// -// HTTPRequestTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPRequestTest.h#1 $ -// -// Definition of the HTTPRequestTest 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 HTTPRequestTest_INCLUDED -#define HTTPRequestTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class HTTPRequestTest: public CppUnit::TestCase -{ -public: - HTTPRequestTest(const std::string& name); - ~HTTPRequestTest(); - - void testWrite1(); - void testWrite2(); - void testWrite3(); - void testRead1(); - void testRead2(); - void testRead3(); - void testInvalid1(); - void testInvalid2(); - void testInvalid3(); - void testCookies(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HTTPRequestTest_INCLUDED +// +// HTTPRequestTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPRequestTest.h#1 $ +// +// Definition of the HTTPRequestTest 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 HTTPRequestTest_INCLUDED +#define HTTPRequestTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class HTTPRequestTest: public CppUnit::TestCase +{ +public: + HTTPRequestTest(const std::string& name); + ~HTTPRequestTest(); + + void testWrite1(); + void testWrite2(); + void testWrite3(); + void testRead1(); + void testRead2(); + void testRead3(); + void testInvalid1(); + void testInvalid2(); + void testInvalid3(); + void testCookies(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HTTPRequestTest_INCLUDED diff --git a/Net/testsuite/src/HTTPResponseTest.cpp b/Net/testsuite/src/HTTPResponseTest.cpp index 6d20c842f..d59eec02a 100644 --- a/Net/testsuite/src/HTTPResponseTest.cpp +++ b/Net/testsuite/src/HTTPResponseTest.cpp @@ -1,226 +1,226 @@ -// -// HTTPResponseTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPResponseTest.cpp#1 $ -// -// 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 "HTTPResponseTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/HTTPResponse.h" -#include "Poco/Net/HTTPCookie.h" -#include "Poco/Net/NetException.h" -#include - - -using Poco::Net::HTTPResponse; -using Poco::Net::HTTPMessage; -using Poco::Net::HTTPCookie; -using Poco::Net::MessageException; - - -HTTPResponseTest::HTTPResponseTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HTTPResponseTest::~HTTPResponseTest() -{ -} - - -void HTTPResponseTest::testWrite1() -{ - HTTPResponse response; - std::ostringstream ostr; - response.write(ostr); - std::string s = ostr.str(); - assert (s == "HTTP/1.0 200 OK\r\n\r\n"); -} - - -void HTTPResponseTest::testWrite2() -{ - HTTPResponse response(HTTPMessage::HTTP_1_1, HTTPResponse::HTTP_MOVED_PERMANENTLY); - response.set("Location", "http://www.appinf.com/index.html"); - response.set("Server", "Poco/1.0"); - std::ostringstream ostr; - response.write(ostr); - std::string s = ostr.str(); - assert (s == "HTTP/1.1 301 Moved Permanently\r\nLocation: http://www.appinf.com/index.html\r\nServer: Poco/1.0\r\n\r\n"); -} - - -void HTTPResponseTest::testRead1() -{ - std::string s("HTTP/1.1 500 Internal Server Error\r\n\r\n"); - std::istringstream istr(s); - HTTPResponse response; - response.read(istr); - assert (response.getStatus() == HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); - assert (response.getReason() == "Internal Server Error"); - assert (response.getVersion() == HTTPMessage::HTTP_1_1); - assert (response.empty()); - assert (istr.get() == -1); -} - - -void HTTPResponseTest::testRead2() -{ - std::string s("HTTP/1.0 301 Moved Permanently\r\nLocation: http://www.appinf.com/index.html\r\nServer: Poco/1.0\r\n\r\n"); - std::istringstream istr(s); - HTTPResponse response; - response.read(istr); - assert (response.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY); - assert (response.getReason() == "Moved Permanently"); - assert (response.getVersion() == HTTPMessage::HTTP_1_0); - assert (response.size() == 2); - assert (response["Location"] == "http://www.appinf.com/index.html"); - assert (response["Server"] == "Poco/1.0"); - assert (istr.get() == -1); -} - - -void HTTPResponseTest::testInvalid1() -{ - std::string s(256, 'x'); - std::istringstream istr(s); - HTTPResponse response; - try - { - response.read(istr); - fail("inavalid response - must throw"); - } - catch (MessageException&) - { - } -} - - -void HTTPResponseTest::testInvalid2() -{ - std::string s("HTTP/1.1 200 "); - s.append(1000, 'x'); - s.append("\r\n\r\n"); - std::istringstream istr(s); - HTTPResponse response; - try - { - response.read(istr); - fail("inavalid response - must throw"); - } - catch (MessageException&) - { - } -} - - -void HTTPResponseTest::testInvalid3() -{ - std::string s("HTTP/1.0 "); - s.append(8000, 'x'); - s.append("\r\n\r\n"); - std::istringstream istr(s); - HTTPResponse response; - try - { - response.read(istr); - fail("inavalid response - must throw"); - } - catch (MessageException&) - { - } -} - - -void HTTPResponseTest::testCookies() -{ - HTTPResponse response; - HTTPCookie cookie1("cookie1", "value1"); - response.addCookie(cookie1); - std::vector cookies; - response.getCookies(cookies); - assert (cookies.size() == 1); - assert (cookie1.getVersion() == cookies[0].getVersion()); - assert (cookie1.getName() == cookies[0].getName()); - assert (cookie1.getValue() == cookies[0].getValue()); - assert (cookie1.getComment() == cookies[0].getComment()); - assert (cookie1.getDomain() == cookies[0].getDomain()); - assert (cookie1.getPath() == cookies[0].getPath()); - assert (cookie1.getSecure() == cookies[0].getSecure()); - assert (cookie1.getMaxAge() == cookies[0].getMaxAge()); - - HTTPCookie cookie2("cookie2", "value2"); - cookie2.setVersion(1); - cookie2.setMaxAge(42); - cookie2.setSecure(true); - response.addCookie(cookie2); - response.getCookies(cookies); - assert (cookies.size() == 2); - HTTPCookie cookie2a; - if (cookies[0].getName() == cookie2.getName()) - cookie2a = cookies[0]; - else - cookie2a = cookies[1]; - assert (cookie2.getVersion() == cookie2a.getVersion()); - assert (cookie2.getName() == cookie2a.getName()); - assert (cookie2.getValue() == cookie2a.getValue()); - assert (cookie2.getComment() == cookie2a.getComment()); - assert (cookie2.getDomain() == cookie2a.getDomain()); - assert (cookie2.getPath() == cookie2a.getPath()); - assert (cookie2.getSecure() == cookie2a.getSecure()); - assert (cookie2.getMaxAge() == cookie2a.getMaxAge()); -} - - -void HTTPResponseTest::setUp() -{ -} - - -void HTTPResponseTest::tearDown() -{ -} - - -CppUnit::Test* HTTPResponseTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPResponseTest"); - - CppUnit_addTest(pSuite, HTTPResponseTest, testWrite1); - CppUnit_addTest(pSuite, HTTPResponseTest, testWrite2); - CppUnit_addTest(pSuite, HTTPResponseTest, testRead1); - CppUnit_addTest(pSuite, HTTPResponseTest, testRead2); - CppUnit_addTest(pSuite, HTTPResponseTest, testInvalid1); - CppUnit_addTest(pSuite, HTTPResponseTest, testInvalid2); - CppUnit_addTest(pSuite, HTTPResponseTest, testInvalid3); - CppUnit_addTest(pSuite, HTTPResponseTest, testCookies); - - return pSuite; -} +// +// HTTPResponseTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPResponseTest.cpp#1 $ +// +// 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 "HTTPResponseTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/HTTPResponse.h" +#include "Poco/Net/HTTPCookie.h" +#include "Poco/Net/NetException.h" +#include + + +using Poco::Net::HTTPResponse; +using Poco::Net::HTTPMessage; +using Poco::Net::HTTPCookie; +using Poco::Net::MessageException; + + +HTTPResponseTest::HTTPResponseTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HTTPResponseTest::~HTTPResponseTest() +{ +} + + +void HTTPResponseTest::testWrite1() +{ + HTTPResponse response; + std::ostringstream ostr; + response.write(ostr); + std::string s = ostr.str(); + assert (s == "HTTP/1.0 200 OK\r\n\r\n"); +} + + +void HTTPResponseTest::testWrite2() +{ + HTTPResponse response(HTTPMessage::HTTP_1_1, HTTPResponse::HTTP_MOVED_PERMANENTLY); + response.set("Location", "http://www.appinf.com/index.html"); + response.set("Server", "Poco/1.0"); + std::ostringstream ostr; + response.write(ostr); + std::string s = ostr.str(); + assert (s == "HTTP/1.1 301 Moved Permanently\r\nLocation: http://www.appinf.com/index.html\r\nServer: Poco/1.0\r\n\r\n"); +} + + +void HTTPResponseTest::testRead1() +{ + std::string s("HTTP/1.1 500 Internal Server Error\r\n\r\n"); + std::istringstream istr(s); + HTTPResponse response; + response.read(istr); + assert (response.getStatus() == HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); + assert (response.getReason() == "Internal Server Error"); + assert (response.getVersion() == HTTPMessage::HTTP_1_1); + assert (response.empty()); + assert (istr.get() == -1); +} + + +void HTTPResponseTest::testRead2() +{ + std::string s("HTTP/1.0 301 Moved Permanently\r\nLocation: http://www.appinf.com/index.html\r\nServer: Poco/1.0\r\n\r\n"); + std::istringstream istr(s); + HTTPResponse response; + response.read(istr); + assert (response.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY); + assert (response.getReason() == "Moved Permanently"); + assert (response.getVersion() == HTTPMessage::HTTP_1_0); + assert (response.size() == 2); + assert (response["Location"] == "http://www.appinf.com/index.html"); + assert (response["Server"] == "Poco/1.0"); + assert (istr.get() == -1); +} + + +void HTTPResponseTest::testInvalid1() +{ + std::string s(256, 'x'); + std::istringstream istr(s); + HTTPResponse response; + try + { + response.read(istr); + fail("inavalid response - must throw"); + } + catch (MessageException&) + { + } +} + + +void HTTPResponseTest::testInvalid2() +{ + std::string s("HTTP/1.1 200 "); + s.append(1000, 'x'); + s.append("\r\n\r\n"); + std::istringstream istr(s); + HTTPResponse response; + try + { + response.read(istr); + fail("inavalid response - must throw"); + } + catch (MessageException&) + { + } +} + + +void HTTPResponseTest::testInvalid3() +{ + std::string s("HTTP/1.0 "); + s.append(8000, 'x'); + s.append("\r\n\r\n"); + std::istringstream istr(s); + HTTPResponse response; + try + { + response.read(istr); + fail("inavalid response - must throw"); + } + catch (MessageException&) + { + } +} + + +void HTTPResponseTest::testCookies() +{ + HTTPResponse response; + HTTPCookie cookie1("cookie1", "value1"); + response.addCookie(cookie1); + std::vector cookies; + response.getCookies(cookies); + assert (cookies.size() == 1); + assert (cookie1.getVersion() == cookies[0].getVersion()); + assert (cookie1.getName() == cookies[0].getName()); + assert (cookie1.getValue() == cookies[0].getValue()); + assert (cookie1.getComment() == cookies[0].getComment()); + assert (cookie1.getDomain() == cookies[0].getDomain()); + assert (cookie1.getPath() == cookies[0].getPath()); + assert (cookie1.getSecure() == cookies[0].getSecure()); + assert (cookie1.getMaxAge() == cookies[0].getMaxAge()); + + HTTPCookie cookie2("cookie2", "value2"); + cookie2.setVersion(1); + cookie2.setMaxAge(42); + cookie2.setSecure(true); + response.addCookie(cookie2); + response.getCookies(cookies); + assert (cookies.size() == 2); + HTTPCookie cookie2a; + if (cookies[0].getName() == cookie2.getName()) + cookie2a = cookies[0]; + else + cookie2a = cookies[1]; + assert (cookie2.getVersion() == cookie2a.getVersion()); + assert (cookie2.getName() == cookie2a.getName()); + assert (cookie2.getValue() == cookie2a.getValue()); + assert (cookie2.getComment() == cookie2a.getComment()); + assert (cookie2.getDomain() == cookie2a.getDomain()); + assert (cookie2.getPath() == cookie2a.getPath()); + assert (cookie2.getSecure() == cookie2a.getSecure()); + assert (cookie2.getMaxAge() == cookie2a.getMaxAge()); +} + + +void HTTPResponseTest::setUp() +{ +} + + +void HTTPResponseTest::tearDown() +{ +} + + +CppUnit::Test* HTTPResponseTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPResponseTest"); + + CppUnit_addTest(pSuite, HTTPResponseTest, testWrite1); + CppUnit_addTest(pSuite, HTTPResponseTest, testWrite2); + CppUnit_addTest(pSuite, HTTPResponseTest, testRead1); + CppUnit_addTest(pSuite, HTTPResponseTest, testRead2); + CppUnit_addTest(pSuite, HTTPResponseTest, testInvalid1); + CppUnit_addTest(pSuite, HTTPResponseTest, testInvalid2); + CppUnit_addTest(pSuite, HTTPResponseTest, testInvalid3); + CppUnit_addTest(pSuite, HTTPResponseTest, testCookies); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPResponseTest.h b/Net/testsuite/src/HTTPResponseTest.h index bd3769caa..0820586cd 100644 --- a/Net/testsuite/src/HTTPResponseTest.h +++ b/Net/testsuite/src/HTTPResponseTest.h @@ -1,67 +1,67 @@ -// -// HTTPResponseTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPResponseTest.h#1 $ -// -// Definition of the HTTPResponseTest 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 HTTPResponseTest_INCLUDED -#define HTTPResponseTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class HTTPResponseTest: public CppUnit::TestCase -{ -public: - HTTPResponseTest(const std::string& name); - ~HTTPResponseTest(); - - void testWrite1(); - void testWrite2(); - void testRead1(); - void testRead2(); - void testInvalid1(); - void testInvalid2(); - void testInvalid3(); - void testCookies(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HTTPResponseTest_INCLUDED +// +// HTTPResponseTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPResponseTest.h#1 $ +// +// Definition of the HTTPResponseTest 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 HTTPResponseTest_INCLUDED +#define HTTPResponseTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class HTTPResponseTest: public CppUnit::TestCase +{ +public: + HTTPResponseTest(const std::string& name); + ~HTTPResponseTest(); + + void testWrite1(); + void testWrite2(); + void testRead1(); + void testRead2(); + void testInvalid1(); + void testInvalid2(); + void testInvalid3(); + void testCookies(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HTTPResponseTest_INCLUDED diff --git a/Net/testsuite/src/HTTPServerTest.cpp b/Net/testsuite/src/HTTPServerTest.cpp index 299a15edf..bf7439beb 100644 --- a/Net/testsuite/src/HTTPServerTest.cpp +++ b/Net/testsuite/src/HTTPServerTest.cpp @@ -1,445 +1,445 @@ -// -// HTTPServerTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPServerTest.cpp#1 $ -// -// 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 "HTTPServerTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/HTTPServer.h" -#include "Poco/Net/HTTPServerParams.h" -#include "Poco/Net/HTTPRequestHandler.h" -#include "Poco/Net/HTTPRequestHandlerFactory.h" -#include "Poco/Net/HTTPClientSession.h" -#include "Poco/Net/HTTPRequest.h" -#include "Poco/Net/HTTPServerRequest.h" -#include "Poco/Net/HTTPResponse.h" -#include "Poco/Net/HTTPServerResponse.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/StreamCopier.h" -#include - - -using Poco::Net::HTTPServer; -using Poco::Net::HTTPServerParams; -using Poco::Net::HTTPRequestHandler; -using Poco::Net::HTTPRequestHandlerFactory; -using Poco::Net::HTTPClientSession; -using Poco::Net::HTTPRequest; -using Poco::Net::HTTPServerRequest; -using Poco::Net::HTTPResponse; -using Poco::Net::HTTPServerResponse; -using Poco::Net::HTTPMessage; -using Poco::Net::ServerSocket; -using Poco::StreamCopier; - - -namespace -{ - class EchoBodyRequestHandler: public HTTPRequestHandler - { - public: - void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) - { - if (request.getChunkedTransferEncoding()) - response.setChunkedTransferEncoding(true); - else if (request.getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH) - response.setContentLength(request.getContentLength()); - - response.setContentType(request.getContentType()); - - std::istream& istr = request.stream(); - std::ostream& ostr = response.send(); - int n = StreamCopier::copyStream(istr, ostr); - } - }; - - class EchoHeaderRequestHandler: public HTTPRequestHandler - { - public: - void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) - { - std::ostringstream osstr; - request.write(osstr); - int n = (int) osstr.str().length(); - response.setContentLength(n); - std::ostream& ostr = response.send(); - if (request.getMethod() != HTTPRequest::HTTP_HEAD) - request.write(ostr); - } - }; - - class RedirectRequestHandler: public HTTPRequestHandler - { - public: - void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) - { - response.redirect("http://www.appinf.com/"); - } - }; - - class AuthRequestHandler: public HTTPRequestHandler - { - public: - void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) - { - response.requireAuthentication("/auth"); - response.send(); - } - }; - - class RequestHandlerFactory: public HTTPRequestHandlerFactory - { - public: - HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) - { - if (request.getURI() == "/echoBody") - return new EchoBodyRequestHandler; - else if (request.getURI() == "/echoHeader") - return new EchoHeaderRequestHandler; - else if (request.getURI() == "/redirect") - return new RedirectRequestHandler(); - else if (request.getURI() == "/auth") - return new AuthRequestHandler(); - else - return 0; - } - }; -} - - -HTTPServerTest::HTTPServerTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HTTPServerTest::~HTTPServerTest() -{ -} - - -void HTTPServerTest::testIdentityRequest() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(false); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - std::string body(5000, 'x'); - HTTPRequest request("POST", "/echoBody"); - request.setContentLength((int) body.length()); - request.setContentType("text/plain"); - cs.sendRequest(request) << body; - HTTPResponse response; - std::string rbody; - cs.receiveResponse(response) >> rbody; - assert (response.getContentLength() == body.size()); - assert (response.getContentType() == "text/plain"); - assert (rbody == body); -} - - -void HTTPServerTest::testPutIdentityRequest() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(false); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - std::string body(5000, 'x'); - HTTPRequest request("PUT", "/echoBody"); - request.setContentLength((int) body.length()); - request.setContentType("text/plain"); - cs.sendRequest(request) << body; - HTTPResponse response; - std::string rbody; - cs.receiveResponse(response) >> rbody; - assert (response.getContentLength() == body.size()); - assert (response.getContentType() == "text/plain"); - assert (rbody == body); -} - - -void HTTPServerTest::testChunkedRequest() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(false); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - std::string body(5000, 'x'); - HTTPRequest request("POST", "/echoBody"); - request.setContentType("text/plain"); - request.setChunkedTransferEncoding(true); - 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 (rbody == body); -} - - -void HTTPServerTest::testClosedRequest() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(false); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - std::string body(5000, 'x'); - HTTPRequest request("POST", "/echoBody"); - request.setContentType("text/plain"); - 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 (rbody == body); -} - - -void HTTPServerTest::testIdentityRequestKeepAlive() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(true); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - cs.setKeepAlive(true); - std::string body(5000, 'x'); - HTTPRequest request("POST", "/echoBody"); - request.setContentLength((int) body.length()); - request.setContentType("text/plain"); - cs.sendRequest(request) << body; - HTTPResponse response; - std::string rbody; - cs.receiveResponse(response) >> rbody; - assert (response.getContentLength() == body.size()); - assert (response.getContentType() == "text/plain"); - assert (response.getKeepAlive()); - assert (rbody == body); - - body.assign(1000, 'y'); - request.setContentLength((int) body.length()); - cs.setKeepAlive(false); - cs.sendRequest(request) << body; - cs.receiveResponse(response) >> rbody; - assert (response.getContentLength() == body.size()); - assert (response.getContentType() == "text/plain"); - assert (!response.getKeepAlive()); - assert (rbody == body);} - - -void HTTPServerTest::testChunkedRequestKeepAlive() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(true); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - cs.setKeepAlive(true); - std::string body(5000, 'x'); - HTTPRequest request("POST", "/echoBody"); - request.setContentType("text/plain"); - request.setChunkedTransferEncoding(true); - 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 (rbody == body); - - body.assign(1000, 'y'); - cs.setKeepAlive(false); - cs.sendRequest(request) << body; - 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::testClosedRequestKeepAlive() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(true); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - std::string body(5000, 'x'); - HTTPRequest request("POST", "/echoBody"); - request.setContentType("text/plain"); - 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); - int n = (int) rbody.size(); -} - - -void HTTPServerTest::test100Continue() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(false); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - std::string body(5000, 'x'); - HTTPRequest request("POST", "/echoBody"); - request.setContentLength((int) body.length()); - request.setContentType("text/plain"); - request.set("Expect", "100-Continue"); - cs.sendRequest(request) << body; - HTTPResponse response; - std::string rbody; - cs.receiveResponse(response) >> rbody; - assert (response.getContentLength() == body.size()); - assert (response.getContentType() == "text/plain"); - assert (rbody == body); -} - - -void HTTPServerTest::testRedirect() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(false); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - HTTPRequest request("GET", "/redirect"); - cs.sendRequest(request); - HTTPResponse response; - std::string rbody; - cs.receiveResponse(response) >> rbody; - assert (response.getStatus() == HTTPResponse::HTTP_FOUND); - assert (response.get("Location") == "http://www.appinf.com/"); - assert (rbody.empty()); -} - - -void HTTPServerTest::testAuth() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(false); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - HTTPRequest request("GET", "/auth"); - cs.sendRequest(request); - HTTPResponse response; - std::string rbody; - cs.receiveResponse(response) >> rbody; - assert (response.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED); - assert (response.get("WWW-Authenticate") == "Basic realm=\"/auth\""); - assert (rbody.empty()); -} - - -void HTTPServerTest::testNotImpl() -{ - ServerSocket svs(0); - HTTPServerParams* pParams = new HTTPServerParams; - pParams->setKeepAlive(false); - HTTPServer srv(new RequestHandlerFactory, svs, pParams); - srv.start(); - - HTTPClientSession cs("localhost", svs.address().port()); - HTTPRequest request("GET", "/notImpl"); - cs.sendRequest(request); - HTTPResponse response; - std::string rbody; - cs.receiveResponse(response) >> rbody; - assert (response.getStatus() == HTTPResponse::HTTP_NOT_IMPLEMENTED); - assert (rbody.empty()); -} - - -void HTTPServerTest::setUp() -{ -} - - -void HTTPServerTest::tearDown() -{ -} - - -CppUnit::Test* HTTPServerTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPServerTest"); - - CppUnit_addTest(pSuite, HTTPServerTest, testIdentityRequest); - CppUnit_addTest(pSuite, HTTPServerTest, testPutIdentityRequest); - CppUnit_addTest(pSuite, HTTPServerTest, testChunkedRequest); - CppUnit_addTest(pSuite, HTTPServerTest, testClosedRequest); - CppUnit_addTest(pSuite, HTTPServerTest, testIdentityRequestKeepAlive); - CppUnit_addTest(pSuite, HTTPServerTest, testChunkedRequestKeepAlive); - CppUnit_addTest(pSuite, HTTPServerTest, testClosedRequestKeepAlive); - CppUnit_addTest(pSuite, HTTPServerTest, test100Continue); - CppUnit_addTest(pSuite, HTTPServerTest, testRedirect); - CppUnit_addTest(pSuite, HTTPServerTest, testAuth); - CppUnit_addTest(pSuite, HTTPServerTest, testNotImpl); - - return pSuite; -} +// +// HTTPServerTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPServerTest.cpp#1 $ +// +// 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 "HTTPServerTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/HTTPServer.h" +#include "Poco/Net/HTTPServerParams.h" +#include "Poco/Net/HTTPRequestHandler.h" +#include "Poco/Net/HTTPRequestHandlerFactory.h" +#include "Poco/Net/HTTPClientSession.h" +#include "Poco/Net/HTTPRequest.h" +#include "Poco/Net/HTTPServerRequest.h" +#include "Poco/Net/HTTPResponse.h" +#include "Poco/Net/HTTPServerResponse.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/StreamCopier.h" +#include + + +using Poco::Net::HTTPServer; +using Poco::Net::HTTPServerParams; +using Poco::Net::HTTPRequestHandler; +using Poco::Net::HTTPRequestHandlerFactory; +using Poco::Net::HTTPClientSession; +using Poco::Net::HTTPRequest; +using Poco::Net::HTTPServerRequest; +using Poco::Net::HTTPResponse; +using Poco::Net::HTTPServerResponse; +using Poco::Net::HTTPMessage; +using Poco::Net::ServerSocket; +using Poco::StreamCopier; + + +namespace +{ + class EchoBodyRequestHandler: public HTTPRequestHandler + { + public: + void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) + { + if (request.getChunkedTransferEncoding()) + response.setChunkedTransferEncoding(true); + else if (request.getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH) + response.setContentLength(request.getContentLength()); + + response.setContentType(request.getContentType()); + + std::istream& istr = request.stream(); + std::ostream& ostr = response.send(); + int n = StreamCopier::copyStream(istr, ostr); + } + }; + + class EchoHeaderRequestHandler: public HTTPRequestHandler + { + public: + void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) + { + std::ostringstream osstr; + request.write(osstr); + int n = (int) osstr.str().length(); + response.setContentLength(n); + std::ostream& ostr = response.send(); + if (request.getMethod() != HTTPRequest::HTTP_HEAD) + request.write(ostr); + } + }; + + class RedirectRequestHandler: public HTTPRequestHandler + { + public: + void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) + { + response.redirect("http://www.appinf.com/"); + } + }; + + class AuthRequestHandler: public HTTPRequestHandler + { + public: + void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) + { + response.requireAuthentication("/auth"); + response.send(); + } + }; + + class RequestHandlerFactory: public HTTPRequestHandlerFactory + { + public: + HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) + { + if (request.getURI() == "/echoBody") + return new EchoBodyRequestHandler; + else if (request.getURI() == "/echoHeader") + return new EchoHeaderRequestHandler; + else if (request.getURI() == "/redirect") + return new RedirectRequestHandler(); + else if (request.getURI() == "/auth") + return new AuthRequestHandler(); + else + return 0; + } + }; +} + + +HTTPServerTest::HTTPServerTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HTTPServerTest::~HTTPServerTest() +{ +} + + +void HTTPServerTest::testIdentityRequest() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(false); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + std::string body(5000, 'x'); + HTTPRequest request("POST", "/echoBody"); + request.setContentLength((int) body.length()); + request.setContentType("text/plain"); + cs.sendRequest(request) << body; + HTTPResponse response; + std::string rbody; + cs.receiveResponse(response) >> rbody; + assert (response.getContentLength() == body.size()); + assert (response.getContentType() == "text/plain"); + assert (rbody == body); +} + + +void HTTPServerTest::testPutIdentityRequest() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(false); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + std::string body(5000, 'x'); + HTTPRequest request("PUT", "/echoBody"); + request.setContentLength((int) body.length()); + request.setContentType("text/plain"); + cs.sendRequest(request) << body; + HTTPResponse response; + std::string rbody; + cs.receiveResponse(response) >> rbody; + assert (response.getContentLength() == body.size()); + assert (response.getContentType() == "text/plain"); + assert (rbody == body); +} + + +void HTTPServerTest::testChunkedRequest() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(false); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + std::string body(5000, 'x'); + HTTPRequest request("POST", "/echoBody"); + request.setContentType("text/plain"); + request.setChunkedTransferEncoding(true); + 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 (rbody == body); +} + + +void HTTPServerTest::testClosedRequest() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(false); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + std::string body(5000, 'x'); + HTTPRequest request("POST", "/echoBody"); + request.setContentType("text/plain"); + 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 (rbody == body); +} + + +void HTTPServerTest::testIdentityRequestKeepAlive() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(true); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + cs.setKeepAlive(true); + std::string body(5000, 'x'); + HTTPRequest request("POST", "/echoBody"); + request.setContentLength((int) body.length()); + request.setContentType("text/plain"); + cs.sendRequest(request) << body; + HTTPResponse response; + std::string rbody; + cs.receiveResponse(response) >> rbody; + assert (response.getContentLength() == body.size()); + assert (response.getContentType() == "text/plain"); + assert (response.getKeepAlive()); + assert (rbody == body); + + body.assign(1000, 'y'); + request.setContentLength((int) body.length()); + cs.setKeepAlive(false); + cs.sendRequest(request) << body; + cs.receiveResponse(response) >> rbody; + assert (response.getContentLength() == body.size()); + assert (response.getContentType() == "text/plain"); + assert (!response.getKeepAlive()); + assert (rbody == body);} + + +void HTTPServerTest::testChunkedRequestKeepAlive() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(true); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + cs.setKeepAlive(true); + std::string body(5000, 'x'); + HTTPRequest request("POST", "/echoBody"); + request.setContentType("text/plain"); + request.setChunkedTransferEncoding(true); + 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 (rbody == body); + + body.assign(1000, 'y'); + cs.setKeepAlive(false); + cs.sendRequest(request) << body; + 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::testClosedRequestKeepAlive() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(true); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + std::string body(5000, 'x'); + HTTPRequest request("POST", "/echoBody"); + request.setContentType("text/plain"); + 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); + int n = (int) rbody.size(); +} + + +void HTTPServerTest::test100Continue() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(false); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + std::string body(5000, 'x'); + HTTPRequest request("POST", "/echoBody"); + request.setContentLength((int) body.length()); + request.setContentType("text/plain"); + request.set("Expect", "100-Continue"); + cs.sendRequest(request) << body; + HTTPResponse response; + std::string rbody; + cs.receiveResponse(response) >> rbody; + assert (response.getContentLength() == body.size()); + assert (response.getContentType() == "text/plain"); + assert (rbody == body); +} + + +void HTTPServerTest::testRedirect() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(false); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + HTTPRequest request("GET", "/redirect"); + cs.sendRequest(request); + HTTPResponse response; + std::string rbody; + cs.receiveResponse(response) >> rbody; + assert (response.getStatus() == HTTPResponse::HTTP_FOUND); + assert (response.get("Location") == "http://www.appinf.com/"); + assert (rbody.empty()); +} + + +void HTTPServerTest::testAuth() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(false); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + HTTPRequest request("GET", "/auth"); + cs.sendRequest(request); + HTTPResponse response; + std::string rbody; + cs.receiveResponse(response) >> rbody; + assert (response.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED); + assert (response.get("WWW-Authenticate") == "Basic realm=\"/auth\""); + assert (rbody.empty()); +} + + +void HTTPServerTest::testNotImpl() +{ + ServerSocket svs(0); + HTTPServerParams* pParams = new HTTPServerParams; + pParams->setKeepAlive(false); + HTTPServer srv(new RequestHandlerFactory, svs, pParams); + srv.start(); + + HTTPClientSession cs("localhost", svs.address().port()); + HTTPRequest request("GET", "/notImpl"); + cs.sendRequest(request); + HTTPResponse response; + std::string rbody; + cs.receiveResponse(response) >> rbody; + assert (response.getStatus() == HTTPResponse::HTTP_NOT_IMPLEMENTED); + assert (rbody.empty()); +} + + +void HTTPServerTest::setUp() +{ +} + + +void HTTPServerTest::tearDown() +{ +} + + +CppUnit::Test* HTTPServerTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPServerTest"); + + CppUnit_addTest(pSuite, HTTPServerTest, testIdentityRequest); + CppUnit_addTest(pSuite, HTTPServerTest, testPutIdentityRequest); + CppUnit_addTest(pSuite, HTTPServerTest, testChunkedRequest); + CppUnit_addTest(pSuite, HTTPServerTest, testClosedRequest); + CppUnit_addTest(pSuite, HTTPServerTest, testIdentityRequestKeepAlive); + CppUnit_addTest(pSuite, HTTPServerTest, testChunkedRequestKeepAlive); + CppUnit_addTest(pSuite, HTTPServerTest, testClosedRequestKeepAlive); + CppUnit_addTest(pSuite, HTTPServerTest, test100Continue); + CppUnit_addTest(pSuite, HTTPServerTest, testRedirect); + CppUnit_addTest(pSuite, HTTPServerTest, testAuth); + CppUnit_addTest(pSuite, HTTPServerTest, testNotImpl); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPServerTest.h b/Net/testsuite/src/HTTPServerTest.h index 1caae5f59..1e1c3122d 100644 --- a/Net/testsuite/src/HTTPServerTest.h +++ b/Net/testsuite/src/HTTPServerTest.h @@ -1,70 +1,70 @@ -// -// HTTPServerTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPServerTest.h#1 $ -// -// Definition of the HTTPServerTest 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 HTTPServerTest_INCLUDED -#define HTTPServerTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class HTTPServerTest: public CppUnit::TestCase -{ -public: - HTTPServerTest(const std::string& name); - ~HTTPServerTest(); - - void testIdentityRequest(); - void testPutIdentityRequest(); - void testChunkedRequest(); - void testClosedRequest(); - void testIdentityRequestKeepAlive(); - void testChunkedRequestKeepAlive(); - void testClosedRequestKeepAlive(); - void test100Continue(); - void testRedirect(); - void testAuth(); - void testNotImpl(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HTTPServerTest_INCLUDED +// +// HTTPServerTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPServerTest.h#1 $ +// +// Definition of the HTTPServerTest 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 HTTPServerTest_INCLUDED +#define HTTPServerTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class HTTPServerTest: public CppUnit::TestCase +{ +public: + HTTPServerTest(const std::string& name); + ~HTTPServerTest(); + + void testIdentityRequest(); + void testPutIdentityRequest(); + void testChunkedRequest(); + void testClosedRequest(); + void testIdentityRequestKeepAlive(); + void testChunkedRequestKeepAlive(); + void testClosedRequestKeepAlive(); + void test100Continue(); + void testRedirect(); + void testAuth(); + void testNotImpl(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HTTPServerTest_INCLUDED diff --git a/Net/testsuite/src/HTTPServerTestSuite.cpp b/Net/testsuite/src/HTTPServerTestSuite.cpp index d29fb6442..7bb0640d4 100644 --- a/Net/testsuite/src/HTTPServerTestSuite.cpp +++ b/Net/testsuite/src/HTTPServerTestSuite.cpp @@ -1,44 +1,44 @@ -// -// HTTPServerTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPServerTestSuite.cpp#1 $ -// -// 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 "HTTPServerTestSuite.h" -#include "HTTPServerTest.h" - - -CppUnit::Test* HTTPServerTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPServerTestSuite"); - - pSuite->addTest(HTTPServerTest::suite()); - - return pSuite; -} +// +// HTTPServerTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPServerTestSuite.cpp#1 $ +// +// 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 "HTTPServerTestSuite.h" +#include "HTTPServerTest.h" + + +CppUnit::Test* HTTPServerTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPServerTestSuite"); + + pSuite->addTest(HTTPServerTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPServerTestSuite.h b/Net/testsuite/src/HTTPServerTestSuite.h index 4fb439f46..948fd53f6 100644 --- a/Net/testsuite/src/HTTPServerTestSuite.h +++ b/Net/testsuite/src/HTTPServerTestSuite.h @@ -1,49 +1,49 @@ -// -// HTTPServerTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPServerTestSuite.h#1 $ -// -// Definition of the HTTPServerTestSuite 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 HTTPServerTestSuite_INCLUDED -#define HTTPServerTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class HTTPServerTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // HTTPServerTestSuite_INCLUDED +// +// HTTPServerTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPServerTestSuite.h#1 $ +// +// Definition of the HTTPServerTestSuite 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 HTTPServerTestSuite_INCLUDED +#define HTTPServerTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class HTTPServerTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // HTTPServerTestSuite_INCLUDED diff --git a/Net/testsuite/src/HTTPStreamFactoryTest.cpp b/Net/testsuite/src/HTTPStreamFactoryTest.cpp index 790038a6b..01a38a192 100644 --- a/Net/testsuite/src/HTTPStreamFactoryTest.cpp +++ b/Net/testsuite/src/HTTPStreamFactoryTest.cpp @@ -1,152 +1,152 @@ -// -// HTTPStreamFactoryTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPStreamFactoryTest.cpp#1 $ -// -// 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 "HTTPStreamFactoryTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/HTTPStreamFactory.h" -#include "Poco/Net/NetException.h" -#include "Poco/URI.h" -#include "Poco/StreamCopier.h" -#include "HTTPTestServer.h" -#include -#include - - -using Poco::Net::HTTPStreamFactory; -using Poco::Net::NetException; -using Poco::Net::HTTPException; -using Poco::URI; -using Poco::StreamCopier; - - -HTTPStreamFactoryTest::HTTPStreamFactoryTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HTTPStreamFactoryTest::~HTTPStreamFactoryTest() -{ -} - - -void HTTPStreamFactoryTest::testNoRedirect() -{ - HTTPTestServer server; - HTTPStreamFactory factory; - URI uri("http://localhost/large"); - uri.setPort(server.port()); - std::auto_ptr pStr(factory.open(uri)); - std::ostringstream ostr; - StreamCopier::copyStream(*pStr.get(), ostr); - assert (ostr.str() == HTTPTestServer::LARGE_BODY); -} - - -void HTTPStreamFactoryTest::testEmptyPath() -{ - HTTPTestServer server; - HTTPStreamFactory factory; - URI uri("http://localhost"); - uri.setPort(server.port()); - std::auto_ptr pStr(factory.open(uri)); - std::ostringstream ostr; - StreamCopier::copyStream(*pStr.get(), ostr); - assert (ostr.str() == HTTPTestServer::SMALL_BODY); -} - - -void HTTPStreamFactoryTest::testRedirect() -{ - HTTPTestServer server; - HTTPStreamFactory factory; - URI uri("http://localhost/redirect"); - uri.setPort(server.port()); - std::auto_ptr pStr(factory.open(uri)); - std::ostringstream ostr; - StreamCopier::copyStream(*pStr.get(), ostr); - assert (ostr.str() == HTTPTestServer::LARGE_BODY); -} - - -void HTTPStreamFactoryTest::testProxy() -{ - HTTPTestServer server; - HTTPStreamFactory factory("localhost", server.port()); - URI uri("http://www.somehost.com/large"); - std::auto_ptr pStr(factory.open(uri)); - std::ostringstream ostr; - StreamCopier::copyStream(*pStr.get(), ostr); - assert (ostr.str() == HTTPTestServer::LARGE_BODY); -} - - -void HTTPStreamFactoryTest::testError() -{ - HTTPTestServer server; - HTTPStreamFactory factory; - URI uri("http://localhost/notfound"); - uri.setPort(server.port()); - try - { - std::istream* pStr = factory.open(uri); - fail("not found - must throw"); - } - catch (HTTPException& exc) - { - std::string m = exc.displayText(); - } -} - - -void HTTPStreamFactoryTest::setUp() -{ -} - - -void HTTPStreamFactoryTest::tearDown() -{ -} - - -CppUnit::Test* HTTPStreamFactoryTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPStreamFactoryTest"); - - CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testNoRedirect); - CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testEmptyPath); - CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testRedirect); - CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testProxy); - CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testError); - - return pSuite; -} +// +// HTTPStreamFactoryTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPStreamFactoryTest.cpp#1 $ +// +// 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 "HTTPStreamFactoryTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/HTTPStreamFactory.h" +#include "Poco/Net/NetException.h" +#include "Poco/URI.h" +#include "Poco/StreamCopier.h" +#include "HTTPTestServer.h" +#include +#include + + +using Poco::Net::HTTPStreamFactory; +using Poco::Net::NetException; +using Poco::Net::HTTPException; +using Poco::URI; +using Poco::StreamCopier; + + +HTTPStreamFactoryTest::HTTPStreamFactoryTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HTTPStreamFactoryTest::~HTTPStreamFactoryTest() +{ +} + + +void HTTPStreamFactoryTest::testNoRedirect() +{ + HTTPTestServer server; + HTTPStreamFactory factory; + URI uri("http://localhost/large"); + uri.setPort(server.port()); + std::auto_ptr pStr(factory.open(uri)); + std::ostringstream ostr; + StreamCopier::copyStream(*pStr.get(), ostr); + assert (ostr.str() == HTTPTestServer::LARGE_BODY); +} + + +void HTTPStreamFactoryTest::testEmptyPath() +{ + HTTPTestServer server; + HTTPStreamFactory factory; + URI uri("http://localhost"); + uri.setPort(server.port()); + std::auto_ptr pStr(factory.open(uri)); + std::ostringstream ostr; + StreamCopier::copyStream(*pStr.get(), ostr); + assert (ostr.str() == HTTPTestServer::SMALL_BODY); +} + + +void HTTPStreamFactoryTest::testRedirect() +{ + HTTPTestServer server; + HTTPStreamFactory factory; + URI uri("http://localhost/redirect"); + uri.setPort(server.port()); + std::auto_ptr pStr(factory.open(uri)); + std::ostringstream ostr; + StreamCopier::copyStream(*pStr.get(), ostr); + assert (ostr.str() == HTTPTestServer::LARGE_BODY); +} + + +void HTTPStreamFactoryTest::testProxy() +{ + HTTPTestServer server; + HTTPStreamFactory factory("localhost", server.port()); + URI uri("http://www.somehost.com/large"); + std::auto_ptr pStr(factory.open(uri)); + std::ostringstream ostr; + StreamCopier::copyStream(*pStr.get(), ostr); + assert (ostr.str() == HTTPTestServer::LARGE_BODY); +} + + +void HTTPStreamFactoryTest::testError() +{ + HTTPTestServer server; + HTTPStreamFactory factory; + URI uri("http://localhost/notfound"); + uri.setPort(server.port()); + try + { + std::istream* pStr = factory.open(uri); + fail("not found - must throw"); + } + catch (HTTPException& exc) + { + std::string m = exc.displayText(); + } +} + + +void HTTPStreamFactoryTest::setUp() +{ +} + + +void HTTPStreamFactoryTest::tearDown() +{ +} + + +CppUnit::Test* HTTPStreamFactoryTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPStreamFactoryTest"); + + CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testNoRedirect); + CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testEmptyPath); + CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testRedirect); + CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testProxy); + CppUnit_addTest(pSuite, HTTPStreamFactoryTest, testError); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPStreamFactoryTest.h b/Net/testsuite/src/HTTPStreamFactoryTest.h index 21a4c293f..8d2bd1ae9 100644 --- a/Net/testsuite/src/HTTPStreamFactoryTest.h +++ b/Net/testsuite/src/HTTPStreamFactoryTest.h @@ -1,64 +1,64 @@ -// -// HTTPStreamFactoryTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPStreamFactoryTest.h#1 $ -// -// Definition of the HTTPStreamFactoryTest 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 HTTPStreamFactoryTest_INCLUDED -#define HTTPStreamFactoryTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class HTTPStreamFactoryTest: public CppUnit::TestCase -{ -public: - HTTPStreamFactoryTest(const std::string& name); - ~HTTPStreamFactoryTest(); - - void testNoRedirect(); - void testEmptyPath(); - void testRedirect(); - void testProxy(); - void testError(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HTTPStreamFactoryTest_INCLUDED +// +// HTTPStreamFactoryTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPStreamFactoryTest.h#1 $ +// +// Definition of the HTTPStreamFactoryTest 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 HTTPStreamFactoryTest_INCLUDED +#define HTTPStreamFactoryTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class HTTPStreamFactoryTest: public CppUnit::TestCase +{ +public: + HTTPStreamFactoryTest(const std::string& name); + ~HTTPStreamFactoryTest(); + + void testNoRedirect(); + void testEmptyPath(); + void testRedirect(); + void testProxy(); + void testError(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HTTPStreamFactoryTest_INCLUDED diff --git a/Net/testsuite/src/HTTPTestServer.cpp b/Net/testsuite/src/HTTPTestServer.cpp index 2c00faee4..1cdaeef0b 100644 --- a/Net/testsuite/src/HTTPTestServer.cpp +++ b/Net/testsuite/src/HTTPTestServer.cpp @@ -1,236 +1,236 @@ -// -// HTTPTestServer.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPTestServer.cpp#1 $ -// -// 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 "HTTPTestServer.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Timespan.h" -#include "Poco/NumberFormatter.h" -#include - - -using Poco::Net::Socket; -using Poco::Net::StreamSocket; -using Poco::Net::SocketAddress; -using Poco::NumberFormatter; - - -const std::string HTTPTestServer::SMALL_BODY("This is some random text data returned by the server"); -const std::string HTTPTestServer::LARGE_BODY(4000, 'x'); - - -HTTPTestServer::HTTPTestServer(): - _socket(SocketAddress()), - _thread("HTTPTestServer"), - _stop(false) -{ - _thread.start(*this); - _ready.wait(); - _lastRequest.reserve(4000); -} - - -HTTPTestServer::~HTTPTestServer() -{ - _stop = true; - _thread.join(); -} - - -Poco::UInt16 HTTPTestServer::port() const -{ - return _socket.address().port(); -} - - -const std::string& HTTPTestServer::lastRequest() const -{ - return _lastRequest; -} - - -void HTTPTestServer::run() -{ - _ready.set(); - Poco::Timespan span(250000); - while (!_stop) - { - if (_socket.poll(span, Socket::SELECT_READ)) - { - StreamSocket ss = _socket.acceptConnection(); - try - { - _lastRequest.clear(); - char buffer[256]; - int n = ss.receiveBytes(buffer, sizeof(buffer)); - while (n > 0 && !_stop) - { - _lastRequest.append(buffer, n); - if (!requestComplete()) - n = ss.receiveBytes(buffer, sizeof(buffer)); - else - n = 0; - } - std::string response = handleRequest(); - ss.sendBytes(response.data(), (int) response.size()); - Poco::Thread::sleep(1000); - } - catch (Poco::Exception& exc) - { - std::cerr << "HTTPTestServer: " << exc.displayText() << std::endl; - } - } - } -} - - -bool HTTPTestServer::requestComplete() const -{ - return ((_lastRequest.substr(0, 3) == "GET" || _lastRequest.substr(0, 4) == "HEAD") && - (_lastRequest.find("\r\n\r\n") != std::string::npos)) || - (_lastRequest.find("\r\n0\r\n") != std::string::npos); -} - - -std::string HTTPTestServer::handleRequest() const -{ - std::string response; - response.reserve(16000); - if (_lastRequest.substr(0, 10) == "GET /small" || - _lastRequest.substr(0, 11) == "HEAD /small") - { - std::string body(SMALL_BODY); - response.append("HTTP/1.0 200 OK\r\n"); - response.append("Content-Type: text/plain\r\n"); - response.append("Content-Length: "); - response.append(NumberFormatter::format((int) body.size())); - response.append("\r\n"); - response.append("Connection: Close\r\n"); - response.append("\r\n"); - if (_lastRequest.substr(0, 3) == "GET") - response.append(body); - } - else if (_lastRequest.substr(0, 10) == "GET /large" || - _lastRequest.substr(0, 11) == "HEAD /large" || - _lastRequest.substr(0, 36) == "GET http://www.somehost.com:80/large") - { - std::string body(LARGE_BODY); - response.append("HTTP/1.0 200 OK\r\n"); - response.append("Content-Type: text/plain\r\n"); - response.append("Content-Length: "); - response.append(NumberFormatter::format((int) body.size())); - response.append("\r\n"); - response.append("Connection: Close\r\n"); - response.append("\r\n"); - if (_lastRequest.substr(0, 3) == "GET") - response.append(body); - } - else if (_lastRequest.substr(0, 4) == "POST") - { - std::string::size_type pos = _lastRequest.find("\r\n\r\n"); - pos += 4; - std::string body = _lastRequest.substr(pos); - response.append("HTTP/1.0 200 OK\r\n"); - response.append("Content-Type: text/plain\r\n"); - if (_lastRequest.find("Content-Length") != std::string::npos) - { - response.append("Content-Length: "); - response.append(NumberFormatter::format((int) body.size())); - response.append("\r\n"); - } - else if (_lastRequest.find("chunked") != std::string::npos) - { - response.append("Transfer-Encoding: chunked\r\n"); - } - response.append("Connection: Close\r\n"); - response.append("\r\n"); - response.append(body); - } - else if (_lastRequest.substr(0, 15) == "HEAD /keepAlive") - { - std::string body(SMALL_BODY); - response.append("HTTP/1.1 200 OK\r\n"); - response.append("Connection: keep-alive\r\n"); - response.append("Content-Type: text/plain\r\n"); - response.append("Content-Length: "); - response.append(NumberFormatter::format((int) body.size())); - response.append("\r\n\r\n"); - response.append("HTTP/1.1 200 OK\r\n"); - response.append("Connection: Keep-Alive\r\n"); - response.append("Content-Type: text/plain\r\n"); - response.append("Content-Length: "); - response.append(NumberFormatter::format((int) body.size())); - response.append("\r\n\r\n"); - response.append(body); - body = LARGE_BODY; - response.append("HTTP/1.1 200 OK\r\n"); - response.append("Connection: keep-alive\r\n"); - response.append("Content-Type: text/plain\r\n"); - response.append("Transfer-Encoding: chunked\r\n\r\n"); - response.append(NumberFormatter::formatHex((unsigned) body.length())); - response.append("\r\n"); - response.append(body); - response.append("\r\n0\r\n"); - response.append("HTTP/1.1 200 OK\r\n"); - response.append("Connection: close\r\n"); - response.append("Content-Type: text/plain\r\n"); - response.append("Content-Length: "); - response.append(NumberFormatter::format((int) body.size())); - response.append("\r\n\r\n"); - } - else if (_lastRequest.substr(0, 13) == "GET /redirect") - { - response.append("HTTP/1.0 302 Found\r\n"); - response.append("Location: /large\r\n"); - response.append("\r\n"); - } - else if (_lastRequest.substr(0, 13) == "GET /notfound") - { - response.append("HTTP/1.0 404 Not Found\r\n"); - response.append("\r\n"); - } - else if (_lastRequest.substr(0, 5) == "GET /" || - _lastRequest.substr(0, 6) == "HEAD /") - { - std::string body(SMALL_BODY); - response.append("HTTP/1.0 200 OK\r\n"); - response.append("Content-Type: text/plain\r\n"); - response.append("Content-Length: "); - response.append(NumberFormatter::format((int) body.size())); - response.append("\r\n"); - response.append("Connection: Close\r\n"); - response.append("\r\n"); - if (_lastRequest.substr(0, 3) == "GET") - response.append(body); - } - return response; -} +// +// HTTPTestServer.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPTestServer.cpp#1 $ +// +// 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 "HTTPTestServer.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Timespan.h" +#include "Poco/NumberFormatter.h" +#include + + +using Poco::Net::Socket; +using Poco::Net::StreamSocket; +using Poco::Net::SocketAddress; +using Poco::NumberFormatter; + + +const std::string HTTPTestServer::SMALL_BODY("This is some random text data returned by the server"); +const std::string HTTPTestServer::LARGE_BODY(4000, 'x'); + + +HTTPTestServer::HTTPTestServer(): + _socket(SocketAddress()), + _thread("HTTPTestServer"), + _stop(false) +{ + _thread.start(*this); + _ready.wait(); + _lastRequest.reserve(4000); +} + + +HTTPTestServer::~HTTPTestServer() +{ + _stop = true; + _thread.join(); +} + + +Poco::UInt16 HTTPTestServer::port() const +{ + return _socket.address().port(); +} + + +const std::string& HTTPTestServer::lastRequest() const +{ + return _lastRequest; +} + + +void HTTPTestServer::run() +{ + _ready.set(); + Poco::Timespan span(250000); + while (!_stop) + { + if (_socket.poll(span, Socket::SELECT_READ)) + { + StreamSocket ss = _socket.acceptConnection(); + try + { + _lastRequest.clear(); + char buffer[256]; + int n = ss.receiveBytes(buffer, sizeof(buffer)); + while (n > 0 && !_stop) + { + _lastRequest.append(buffer, n); + if (!requestComplete()) + n = ss.receiveBytes(buffer, sizeof(buffer)); + else + n = 0; + } + std::string response = handleRequest(); + ss.sendBytes(response.data(), (int) response.size()); + Poco::Thread::sleep(1000); + } + catch (Poco::Exception& exc) + { + std::cerr << "HTTPTestServer: " << exc.displayText() << std::endl; + } + } + } +} + + +bool HTTPTestServer::requestComplete() const +{ + return ((_lastRequest.substr(0, 3) == "GET" || _lastRequest.substr(0, 4) == "HEAD") && + (_lastRequest.find("\r\n\r\n") != std::string::npos)) || + (_lastRequest.find("\r\n0\r\n") != std::string::npos); +} + + +std::string HTTPTestServer::handleRequest() const +{ + std::string response; + response.reserve(16000); + if (_lastRequest.substr(0, 10) == "GET /small" || + _lastRequest.substr(0, 11) == "HEAD /small") + { + std::string body(SMALL_BODY); + response.append("HTTP/1.0 200 OK\r\n"); + response.append("Content-Type: text/plain\r\n"); + response.append("Content-Length: "); + response.append(NumberFormatter::format((int) body.size())); + response.append("\r\n"); + response.append("Connection: Close\r\n"); + response.append("\r\n"); + if (_lastRequest.substr(0, 3) == "GET") + response.append(body); + } + else if (_lastRequest.substr(0, 10) == "GET /large" || + _lastRequest.substr(0, 11) == "HEAD /large" || + _lastRequest.substr(0, 36) == "GET http://www.somehost.com:80/large") + { + std::string body(LARGE_BODY); + response.append("HTTP/1.0 200 OK\r\n"); + response.append("Content-Type: text/plain\r\n"); + response.append("Content-Length: "); + response.append(NumberFormatter::format((int) body.size())); + response.append("\r\n"); + response.append("Connection: Close\r\n"); + response.append("\r\n"); + if (_lastRequest.substr(0, 3) == "GET") + response.append(body); + } + else if (_lastRequest.substr(0, 4) == "POST") + { + std::string::size_type pos = _lastRequest.find("\r\n\r\n"); + pos += 4; + std::string body = _lastRequest.substr(pos); + response.append("HTTP/1.0 200 OK\r\n"); + response.append("Content-Type: text/plain\r\n"); + if (_lastRequest.find("Content-Length") != std::string::npos) + { + response.append("Content-Length: "); + response.append(NumberFormatter::format((int) body.size())); + response.append("\r\n"); + } + else if (_lastRequest.find("chunked") != std::string::npos) + { + response.append("Transfer-Encoding: chunked\r\n"); + } + response.append("Connection: Close\r\n"); + response.append("\r\n"); + response.append(body); + } + else if (_lastRequest.substr(0, 15) == "HEAD /keepAlive") + { + std::string body(SMALL_BODY); + response.append("HTTP/1.1 200 OK\r\n"); + response.append("Connection: keep-alive\r\n"); + response.append("Content-Type: text/plain\r\n"); + response.append("Content-Length: "); + response.append(NumberFormatter::format((int) body.size())); + response.append("\r\n\r\n"); + response.append("HTTP/1.1 200 OK\r\n"); + response.append("Connection: Keep-Alive\r\n"); + response.append("Content-Type: text/plain\r\n"); + response.append("Content-Length: "); + response.append(NumberFormatter::format((int) body.size())); + response.append("\r\n\r\n"); + response.append(body); + body = LARGE_BODY; + response.append("HTTP/1.1 200 OK\r\n"); + response.append("Connection: keep-alive\r\n"); + response.append("Content-Type: text/plain\r\n"); + response.append("Transfer-Encoding: chunked\r\n\r\n"); + response.append(NumberFormatter::formatHex((unsigned) body.length())); + response.append("\r\n"); + response.append(body); + response.append("\r\n0\r\n"); + response.append("HTTP/1.1 200 OK\r\n"); + response.append("Connection: close\r\n"); + response.append("Content-Type: text/plain\r\n"); + response.append("Content-Length: "); + response.append(NumberFormatter::format((int) body.size())); + response.append("\r\n\r\n"); + } + else if (_lastRequest.substr(0, 13) == "GET /redirect") + { + response.append("HTTP/1.0 302 Found\r\n"); + response.append("Location: /large\r\n"); + response.append("\r\n"); + } + else if (_lastRequest.substr(0, 13) == "GET /notfound") + { + response.append("HTTP/1.0 404 Not Found\r\n"); + response.append("\r\n"); + } + else if (_lastRequest.substr(0, 5) == "GET /" || + _lastRequest.substr(0, 6) == "HEAD /") + { + std::string body(SMALL_BODY); + response.append("HTTP/1.0 200 OK\r\n"); + response.append("Content-Type: text/plain\r\n"); + response.append("Content-Length: "); + response.append(NumberFormatter::format((int) body.size())); + response.append("\r\n"); + response.append("Connection: Close\r\n"); + response.append("\r\n"); + if (_lastRequest.substr(0, 3) == "GET") + response.append(body); + } + return response; +} diff --git a/Net/testsuite/src/HTTPTestServer.h b/Net/testsuite/src/HTTPTestServer.h index f7ec693fe..378a44655 100644 --- a/Net/testsuite/src/HTTPTestServer.h +++ b/Net/testsuite/src/HTTPTestServer.h @@ -1,81 +1,81 @@ -// -// HTTPTestServer.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPTestServer.h#1 $ -// -// Definition of the HTTPTestServer 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 HTTPTestServer_INCLUDED -#define HTTPTestServer_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" - - -class HTTPTestServer: public Poco::Runnable - /// A simple sequential echo server. -{ -public: - HTTPTestServer(); - /// Creates the HTTPTestServer. - - ~HTTPTestServer(); - /// Destroys the HTTPTestServer. - - Poco::UInt16 port() const; - /// Returns the port the echo server is - /// listening on. - - void run(); - /// Does the work. - - const std::string& lastRequest() const; - /// Returns the last request. - - static const std::string SMALL_BODY; - static const std::string LARGE_BODY; - -protected: - bool requestComplete() const; - std::string handleRequest() const; - -private: - Poco::Net::ServerSocket _socket; - Poco::Thread _thread; - Poco::Event _ready; - bool _stop; - std::string _lastRequest; -}; - - -#endif // HTTPTestServer_INCLUDED +// +// HTTPTestServer.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPTestServer.h#1 $ +// +// Definition of the HTTPTestServer 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 HTTPTestServer_INCLUDED +#define HTTPTestServer_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" + + +class HTTPTestServer: public Poco::Runnable + /// A simple sequential echo server. +{ +public: + HTTPTestServer(); + /// Creates the HTTPTestServer. + + ~HTTPTestServer(); + /// Destroys the HTTPTestServer. + + Poco::UInt16 port() const; + /// Returns the port the echo server is + /// listening on. + + void run(); + /// Does the work. + + const std::string& lastRequest() const; + /// Returns the last request. + + static const std::string SMALL_BODY; + static const std::string LARGE_BODY; + +protected: + bool requestComplete() const; + std::string handleRequest() const; + +private: + Poco::Net::ServerSocket _socket; + Poco::Thread _thread; + Poco::Event _ready; + bool _stop; + std::string _lastRequest; +}; + + +#endif // HTTPTestServer_INCLUDED diff --git a/Net/testsuite/src/HTTPTestSuite.cpp b/Net/testsuite/src/HTTPTestSuite.cpp index 83469aba4..9d93d900c 100644 --- a/Net/testsuite/src/HTTPTestSuite.cpp +++ b/Net/testsuite/src/HTTPTestSuite.cpp @@ -1,50 +1,50 @@ -// -// HTTPTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPTestSuite.cpp#1 $ -// -// 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 "HTTPTestSuite.h" -#include "HTTPRequestTest.h" -#include "HTTPResponseTest.h" -#include "HTTPCookieTest.h" -#include "HTTPCredentialsTest.h" - - -CppUnit::Test* HTTPTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPTestSuite"); - - pSuite->addTest(HTTPRequestTest::suite()); - pSuite->addTest(HTTPResponseTest::suite()); - pSuite->addTest(HTTPCookieTest::suite()); - pSuite->addTest(HTTPCredentialsTest::suite()); - - return pSuite; -} +// +// HTTPTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPTestSuite.cpp#1 $ +// +// 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 "HTTPTestSuite.h" +#include "HTTPRequestTest.h" +#include "HTTPResponseTest.h" +#include "HTTPCookieTest.h" +#include "HTTPCredentialsTest.h" + + +CppUnit::Test* HTTPTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HTTPTestSuite"); + + pSuite->addTest(HTTPRequestTest::suite()); + pSuite->addTest(HTTPResponseTest::suite()); + pSuite->addTest(HTTPCookieTest::suite()); + pSuite->addTest(HTTPCredentialsTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/HTTPTestSuite.h b/Net/testsuite/src/HTTPTestSuite.h index 26b1c3211..53e99376f 100644 --- a/Net/testsuite/src/HTTPTestSuite.h +++ b/Net/testsuite/src/HTTPTestSuite.h @@ -1,49 +1,49 @@ -// -// HTTPTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/HTTPTestSuite.h#1 $ -// -// Definition of the HTTPTestSuite 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 HTTPTestSuite_INCLUDED -#define HTTPTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class HTTPTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // HTTPTestSuite_INCLUDED +// +// HTTPTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/HTTPTestSuite.h#1 $ +// +// Definition of the HTTPTestSuite 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 HTTPTestSuite_INCLUDED +#define HTTPTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class HTTPTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // HTTPTestSuite_INCLUDED diff --git a/Net/testsuite/src/ICMPClientTest.cpp b/Net/testsuite/src/ICMPClientTest.cpp index dac390aa2..6b775c0e6 100644 --- a/Net/testsuite/src/ICMPClientTest.cpp +++ b/Net/testsuite/src/ICMPClientTest.cpp @@ -1,152 +1,152 @@ -// -// ICMPClientTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/ICMPClientTest.cpp#1 $ -// -// 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 "ICMPClientTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/ICMPSocket.h" -#include "Poco/Net/ICMPClient.h" -#include "Poco/Net/ICMPEventArgs.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/AutoPtr.h" -#include "Poco/Delegate.h" -#include -#include - - -using Poco::Net::ICMPSocket; -using Poco::Net::ICMPClient; -using Poco::Net::ICMPEventArgs; -using Poco::Net::SocketAddress; -using Poco::Net::IPAddress; -using Poco::Net::HostNotFoundException; -using Poco::Delegate; -using Poco::AutoPtr; - - -ICMPClientTest::ICMPClientTest(const std::string& name): - CppUnit::TestCase(name), - _icmpClient(IPAddress::IPv4) -{ -} - - -ICMPClientTest::~ICMPClientTest() -{ -} - - -void ICMPClientTest::testPing() -{ - assert(ICMPClient::pingIPv4("localhost") > 0); - - assert(_icmpClient.ping("localhost") > 0); - assert(_icmpClient.ping("www.appinf.com", 4) > 0); - - // warning: may fail depending on the existence of the addresses at test site - // if so, adjust accordingly (i.e. specify non-existent or unreachable IP addresses) - assert(0 == _icmpClient.ping("192.168.243.1")); - assert(0 == _icmpClient.ping("10.0.0.1")); -} - - -void ICMPClientTest::setUp() -{ - _icmpClient.pingBegin += Delegate(this, &ICMPClientTest::onBegin); - _icmpClient.pingReply += Delegate(this, &ICMPClientTest::onReply); - _icmpClient.pingError += Delegate(this, &ICMPClientTest::onError); - _icmpClient.pingEnd += Delegate(this, &ICMPClientTest::onEnd); -} - - -void ICMPClientTest::tearDown() -{ - _icmpClient.pingBegin -= Delegate(this, &ICMPClientTest::onBegin); - _icmpClient.pingReply -= Delegate(this, &ICMPClientTest::onReply); - _icmpClient.pingError -= Delegate(this, &ICMPClientTest::onError); - _icmpClient.pingEnd -= Delegate(this, &ICMPClientTest::onEnd); -} - - -void ICMPClientTest::onBegin(const void* pSender, ICMPEventArgs& args) -{ - std::ostringstream os; - os << std::endl << "Pinging " << args.hostName() << " [" << args.hostAddress() << "] with " - << args.dataSize() << " bytes of data:" - << std::endl << "-------------------------------------------------------" << std::endl; - std::cout << os.str() << std::endl; -} - - -void ICMPClientTest::onReply(const void* pSender, ICMPEventArgs& args) -{ - std::ostringstream os; - os << "Reply from " << args.hostAddress() - << " bytes=" << args.dataSize() - << " time=" << args.replyTime() << "ms" - << " TTL=" << args.ttl(); - std::cout << os.str() << std::endl; -} - - -void ICMPClientTest::onError(const void* pSender, ICMPEventArgs& args) -{ - std::ostringstream os; - os << args.error(); - std::cerr << os.str() << std::endl; -} - - -void ICMPClientTest::onEnd(const void* pSender, ICMPEventArgs& args) -{ - std::ostringstream os; - int received = args.received(); - os << std::endl << "--- Ping statistics for " << args.hostAddress() << " ---" - << std::endl << "Packets: Sent=" << args.sent() << ", Received=" << received - << " Lost=" << args.repetitions() - received << " (" << 100.0 - args.percent() << "% loss)," - << std::endl << "Approximate round trip times in milliseconds: " << std::endl - << "Minimum=" << args.minRTT() << "ms, Maximum=" << args.maxRTT() - << "ms, Average=" << args.avgRTT() << "ms" - << std::endl << "-----------------------------------------------" << std::endl; - std::cout << os.str() << std::endl; -} - - -CppUnit::Test* ICMPClientTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ICMPClientTest"); - - CppUnit_addTest(pSuite, ICMPClientTest, testPing); - - return pSuite; -} +// +// ICMPClientTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/ICMPClientTest.cpp#1 $ +// +// 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 "ICMPClientTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/ICMPSocket.h" +#include "Poco/Net/ICMPClient.h" +#include "Poco/Net/ICMPEventArgs.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/AutoPtr.h" +#include "Poco/Delegate.h" +#include +#include + + +using Poco::Net::ICMPSocket; +using Poco::Net::ICMPClient; +using Poco::Net::ICMPEventArgs; +using Poco::Net::SocketAddress; +using Poco::Net::IPAddress; +using Poco::Net::HostNotFoundException; +using Poco::Delegate; +using Poco::AutoPtr; + + +ICMPClientTest::ICMPClientTest(const std::string& name): + CppUnit::TestCase(name), + _icmpClient(IPAddress::IPv4) +{ +} + + +ICMPClientTest::~ICMPClientTest() +{ +} + + +void ICMPClientTest::testPing() +{ + assert(ICMPClient::pingIPv4("localhost") > 0); + + assert(_icmpClient.ping("localhost") > 0); + assert(_icmpClient.ping("www.appinf.com", 4) > 0); + + // warning: may fail depending on the existence of the addresses at test site + // if so, adjust accordingly (i.e. specify non-existent or unreachable IP addresses) + assert(0 == _icmpClient.ping("192.168.243.1")); + assert(0 == _icmpClient.ping("10.0.0.1")); +} + + +void ICMPClientTest::setUp() +{ + _icmpClient.pingBegin += Delegate(this, &ICMPClientTest::onBegin); + _icmpClient.pingReply += Delegate(this, &ICMPClientTest::onReply); + _icmpClient.pingError += Delegate(this, &ICMPClientTest::onError); + _icmpClient.pingEnd += Delegate(this, &ICMPClientTest::onEnd); +} + + +void ICMPClientTest::tearDown() +{ + _icmpClient.pingBegin -= Delegate(this, &ICMPClientTest::onBegin); + _icmpClient.pingReply -= Delegate(this, &ICMPClientTest::onReply); + _icmpClient.pingError -= Delegate(this, &ICMPClientTest::onError); + _icmpClient.pingEnd -= Delegate(this, &ICMPClientTest::onEnd); +} + + +void ICMPClientTest::onBegin(const void* pSender, ICMPEventArgs& args) +{ + std::ostringstream os; + os << std::endl << "Pinging " << args.hostName() << " [" << args.hostAddress() << "] with " + << args.dataSize() << " bytes of data:" + << std::endl << "-------------------------------------------------------" << std::endl; + std::cout << os.str() << std::endl; +} + + +void ICMPClientTest::onReply(const void* pSender, ICMPEventArgs& args) +{ + std::ostringstream os; + os << "Reply from " << args.hostAddress() + << " bytes=" << args.dataSize() + << " time=" << args.replyTime() << "ms" + << " TTL=" << args.ttl(); + std::cout << os.str() << std::endl; +} + + +void ICMPClientTest::onError(const void* pSender, ICMPEventArgs& args) +{ + std::ostringstream os; + os << args.error(); + std::cerr << os.str() << std::endl; +} + + +void ICMPClientTest::onEnd(const void* pSender, ICMPEventArgs& args) +{ + std::ostringstream os; + int received = args.received(); + os << std::endl << "--- Ping statistics for " << args.hostAddress() << " ---" + << std::endl << "Packets: Sent=" << args.sent() << ", Received=" << received + << " Lost=" << args.repetitions() - received << " (" << 100.0 - args.percent() << "% loss)," + << std::endl << "Approximate round trip times in milliseconds: " << std::endl + << "Minimum=" << args.minRTT() << "ms, Maximum=" << args.maxRTT() + << "ms, Average=" << args.avgRTT() << "ms" + << std::endl << "-----------------------------------------------" << std::endl; + std::cout << os.str() << std::endl; +} + + +CppUnit::Test* ICMPClientTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ICMPClientTest"); + + CppUnit_addTest(pSuite, ICMPClientTest, testPing); + + return pSuite; +} diff --git a/Net/testsuite/src/ICMPClientTest.h b/Net/testsuite/src/ICMPClientTest.h index 9a1134b04..0d221aaa3 100644 --- a/Net/testsuite/src/ICMPClientTest.h +++ b/Net/testsuite/src/ICMPClientTest.h @@ -1,68 +1,68 @@ -// -// ICMPClientTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/ICMPClientTest.h#1 $ -// -// Definition of the ICMPClientTest 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 ICMPClientTest_INCLUDED -#define ICMPClientTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" -#include "Poco/Net/ICMPClient.h" -#include "Poco/Net/ICMPEventArgs.h" - - -class ICMPClientTest: public CppUnit::TestCase -{ -public: - ICMPClientTest(const std::string& name); - ~ICMPClientTest(); - - void testPing(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - - void onBegin(const void* pSender, Poco::Net::ICMPEventArgs& args); - void onReply(const void* pSender, Poco::Net::ICMPEventArgs& args); - void onError(const void* pSender, Poco::Net::ICMPEventArgs& args); - void onEnd(const void* pSender, Poco::Net::ICMPEventArgs& args); - -private: - Poco::Net::ICMPClient _icmpClient; -}; - - -#endif // ICMPClientTest_INCLUDED +// +// ICMPClientTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/ICMPClientTest.h#1 $ +// +// Definition of the ICMPClientTest 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 ICMPClientTest_INCLUDED +#define ICMPClientTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" +#include "Poco/Net/ICMPClient.h" +#include "Poco/Net/ICMPEventArgs.h" + + +class ICMPClientTest: public CppUnit::TestCase +{ +public: + ICMPClientTest(const std::string& name); + ~ICMPClientTest(); + + void testPing(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + + void onBegin(const void* pSender, Poco::Net::ICMPEventArgs& args); + void onReply(const void* pSender, Poco::Net::ICMPEventArgs& args); + void onError(const void* pSender, Poco::Net::ICMPEventArgs& args); + void onEnd(const void* pSender, Poco::Net::ICMPEventArgs& args); + +private: + Poco::Net::ICMPClient _icmpClient; +}; + + +#endif // ICMPClientTest_INCLUDED diff --git a/Net/testsuite/src/ICMPClientTestSuite.cpp b/Net/testsuite/src/ICMPClientTestSuite.cpp index b7f32bac8..a619759c2 100644 --- a/Net/testsuite/src/ICMPClientTestSuite.cpp +++ b/Net/testsuite/src/ICMPClientTestSuite.cpp @@ -1,44 +1,44 @@ -// -// ICMPClientTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/ICMPClientTestSuite.cpp#1 $ -// -// 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 "ICMPClientTestSuite.h" -#include "ICMPClientTest.h" - - -CppUnit::Test* ICMPClientTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ICMPClientTestSuite"); - - pSuite->addTest(ICMPClientTest::suite()); - - return pSuite; -} +// +// ICMPClientTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/ICMPClientTestSuite.cpp#1 $ +// +// 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 "ICMPClientTestSuite.h" +#include "ICMPClientTest.h" + + +CppUnit::Test* ICMPClientTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ICMPClientTestSuite"); + + pSuite->addTest(ICMPClientTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/ICMPClientTestSuite.h b/Net/testsuite/src/ICMPClientTestSuite.h index 6fa7d4b5c..909c56c3a 100644 --- a/Net/testsuite/src/ICMPClientTestSuite.h +++ b/Net/testsuite/src/ICMPClientTestSuite.h @@ -1,49 +1,49 @@ -// -// ICMPClientTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/ICMPClientTestSuite.h#1 $ -// -// Definition of the ICMPClientTestSuite 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 ICMPClientTestSuite_INCLUDED -#define ICMPClientTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class ICMPClientTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // ICMPClientTestSuite_INCLUDED +// +// ICMPClientTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/ICMPClientTestSuite.h#1 $ +// +// Definition of the ICMPClientTestSuite 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 ICMPClientTestSuite_INCLUDED +#define ICMPClientTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class ICMPClientTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // ICMPClientTestSuite_INCLUDED diff --git a/Net/testsuite/src/ICMPSocketTest.cpp b/Net/testsuite/src/ICMPSocketTest.cpp index 365e4abe8..252856e53 100644 --- a/Net/testsuite/src/ICMPSocketTest.cpp +++ b/Net/testsuite/src/ICMPSocketTest.cpp @@ -1,115 +1,115 @@ -// -// ICMPSocketTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/ICMPSocketTest.cpp#1 $ -// -// 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 "ICMPSocketTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "UDPEchoServer.h" -#include "Poco/Net/ICMPSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/Timespan.h" -#include "Poco/Stopwatch.h" - - -using Poco::Net::Socket; -using Poco::Net::ICMPSocket; -using Poco::Net::SocketAddress; -using Poco::Net::IPAddress; -using Poco::Timespan; -using Poco::Stopwatch; -using Poco::TimeoutException; -using Poco::Net::ICMPException; - - -ICMPSocketTest::ICMPSocketTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ICMPSocketTest::~ICMPSocketTest() -{ -} - - -void ICMPSocketTest::testAssign() -{ - ICMPSocket s1(IPAddress::IPv4); - ICMPSocket s2(s1); -} - -void ICMPSocketTest::testSendToReceiveFrom() -{ - ICMPSocket ss(IPAddress::IPv4); - - SocketAddress sa("www.appinf.com", 0); - SocketAddress sr(sa); - - try - { - ss.receiveFrom(sa); - fail("must throw"); - } - catch(ICMPException&) - { - } - catch(TimeoutException&) - { - } - - ss.sendTo(sa); - ss.receiveFrom(sa); - - assert(sr.host().toString() == sa.host().toString()); - ss.close(); -} - - -void ICMPSocketTest::setUp() -{ -} - - -void ICMPSocketTest::tearDown() -{ -} - - -CppUnit::Test* ICMPSocketTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ICMPSocketTest"); - - CppUnit_addTest(pSuite, ICMPSocketTest, testSendToReceiveFrom); - CppUnit_addTest(pSuite, ICMPSocketTest, testAssign); - - return pSuite; -} +// +// ICMPSocketTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/ICMPSocketTest.cpp#1 $ +// +// 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 "ICMPSocketTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "UDPEchoServer.h" +#include "Poco/Net/ICMPSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/Timespan.h" +#include "Poco/Stopwatch.h" + + +using Poco::Net::Socket; +using Poco::Net::ICMPSocket; +using Poco::Net::SocketAddress; +using Poco::Net::IPAddress; +using Poco::Timespan; +using Poco::Stopwatch; +using Poco::TimeoutException; +using Poco::Net::ICMPException; + + +ICMPSocketTest::ICMPSocketTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ICMPSocketTest::~ICMPSocketTest() +{ +} + + +void ICMPSocketTest::testAssign() +{ + ICMPSocket s1(IPAddress::IPv4); + ICMPSocket s2(s1); +} + +void ICMPSocketTest::testSendToReceiveFrom() +{ + ICMPSocket ss(IPAddress::IPv4); + + SocketAddress sa("www.appinf.com", 0); + SocketAddress sr(sa); + + try + { + ss.receiveFrom(sa); + fail("must throw"); + } + catch(ICMPException&) + { + } + catch(TimeoutException&) + { + } + + ss.sendTo(sa); + ss.receiveFrom(sa); + + assert(sr.host().toString() == sa.host().toString()); + ss.close(); +} + + +void ICMPSocketTest::setUp() +{ +} + + +void ICMPSocketTest::tearDown() +{ +} + + +CppUnit::Test* ICMPSocketTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ICMPSocketTest"); + + CppUnit_addTest(pSuite, ICMPSocketTest, testSendToReceiveFrom); + CppUnit_addTest(pSuite, ICMPSocketTest, testAssign); + + return pSuite; +} diff --git a/Net/testsuite/src/ICMPSocketTest.h b/Net/testsuite/src/ICMPSocketTest.h index c7629cebf..ea3642943 100644 --- a/Net/testsuite/src/ICMPSocketTest.h +++ b/Net/testsuite/src/ICMPSocketTest.h @@ -1,61 +1,61 @@ -// -// ICMPSocketTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/ICMPSocketTest.h#1 $ -// -// Definition of the ICMPSocketTest 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 ICMPSocketTest_INCLUDED -#define ICMPSocketTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class ICMPSocketTest: public CppUnit::TestCase -{ -public: - ICMPSocketTest(const std::string& name); - ~ICMPSocketTest(); - - void testSendToReceiveFrom(); - void testAssign(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ICMPSocketTest_INCLUDED +// +// ICMPSocketTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/ICMPSocketTest.h#1 $ +// +// Definition of the ICMPSocketTest 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 ICMPSocketTest_INCLUDED +#define ICMPSocketTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class ICMPSocketTest: public CppUnit::TestCase +{ +public: + ICMPSocketTest(const std::string& name); + ~ICMPSocketTest(); + + void testSendToReceiveFrom(); + void testAssign(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ICMPSocketTest_INCLUDED diff --git a/Net/testsuite/src/IPAddressTest.cpp b/Net/testsuite/src/IPAddressTest.cpp index 40ccdf084..7200c6335 100644 --- a/Net/testsuite/src/IPAddressTest.cpp +++ b/Net/testsuite/src/IPAddressTest.cpp @@ -1,392 +1,392 @@ -// -// IPAddressTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/IPAddressTest.cpp#1 $ -// -// 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 "IPAddressTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/IPAddress.h" -#include "Poco/Net/NetException.h" - - -using Poco::Net::IPAddress; -using Poco::Net::InvalidAddressException; - - -IPAddressTest::IPAddressTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -IPAddressTest::~IPAddressTest() -{ -} - - -void IPAddressTest::testStringConv() -{ - IPAddress ia1("127.0.0.1"); - assert (ia1.family() == IPAddress::IPv4); - assert (ia1.toString() == "127.0.0.1"); - - IPAddress ia2("192.168.1.120"); - assert (ia2.family() == IPAddress::IPv4); - assert (ia2.toString() == "192.168.1.120"); - - IPAddress ia3("255.255.255.255"); - assert (ia3.family() == IPAddress::IPv4); - assert (ia3.toString() == "255.255.255.255"); - - IPAddress ia4("0.0.0.0"); - assert (ia4.family() == IPAddress::IPv4); - assert (ia4.toString() == "0.0.0.0"); -} - - -void IPAddressTest::testStringConv6() -{ -#ifdef POCO_HAVE_IPv6 - IPAddress ia1("1080:0:0:0:8:600:200A:425C"); - assert (ia1.family() == IPAddress::IPv6); - assert (ia1.toString() == "1080::8:600:200A:425C"); - - IPAddress ia2("1080::8:600:200A:425C"); - assert (ia2.family() == IPAddress::IPv6); - assert (ia2.toString() == "1080::8:600:200A:425C"); - - IPAddress ia3("::192.168.1.120"); - assert (ia3.family() == IPAddress::IPv6); - assert (ia3.toString() == "::192.168.1.120"); - - IPAddress ia4("::FFFF:192.168.1.120"); - assert (ia4.family() == IPAddress::IPv6); - assert (ia4.toString() == "::FFFF:192.168.1.120"); -#endif -} - - -void IPAddressTest::testParse() -{ - IPAddress ip; - assert (IPAddress::tryParse("192.168.1.120", ip)); - - assert (!IPAddress::tryParse("192.168.1.280", ip)); - - ip = IPAddress::parse("192.168.1.120"); - try - { - ip = IPAddress::parse("192.168.1.280"); - fail("bad address - must throw"); - } - catch (InvalidAddressException&) - { - } -} - - -void IPAddressTest::testClassification() -{ - IPAddress ip1("0.0.0.0"); // wildcard - assert (ip1.isWildcard()); - assert (!ip1.isBroadcast()); - assert (!ip1.isLoopback()); - assert (!ip1.isMulticast()); - assert (!ip1.isUnicast()); - assert (!ip1.isLinkLocal()); - assert (!ip1.isSiteLocal()); - assert (!ip1.isWellKnownMC()); - assert (!ip1.isNodeLocalMC()); - assert (!ip1.isLinkLocalMC()); - assert (!ip1.isSiteLocalMC()); - assert (!ip1.isOrgLocalMC()); - assert (!ip1.isGlobalMC()); - - IPAddress ip2("255.255.255.255"); // broadcast - assert (!ip2.isWildcard()); - assert (ip2.isBroadcast()); - assert (!ip2.isLoopback()); - assert (!ip2.isMulticast()); - assert (!ip2.isUnicast()); - assert (!ip2.isLinkLocal()); - assert (!ip2.isSiteLocal()); - assert (!ip2.isWellKnownMC()); - assert (!ip2.isNodeLocalMC()); - assert (!ip2.isLinkLocalMC()); - assert (!ip2.isSiteLocalMC()); - assert (!ip2.isOrgLocalMC()); - assert (!ip2.isGlobalMC()); - - IPAddress ip3("127.0.0.1"); // loopback - assert (!ip3.isWildcard()); - assert (!ip3.isBroadcast()); - assert (ip3.isLoopback()); - assert (!ip3.isMulticast()); - assert (ip3.isUnicast()); - assert (!ip3.isLinkLocal()); - assert (!ip3.isSiteLocal()); - assert (!ip3.isWellKnownMC()); - assert (!ip3.isNodeLocalMC()); - assert (!ip3.isLinkLocalMC()); - assert (!ip3.isSiteLocalMC()); - assert (!ip3.isOrgLocalMC()); - assert (!ip3.isGlobalMC()); - - IPAddress ip4("80.122.195.86"); // unicast - assert (!ip4.isWildcard()); - assert (!ip4.isBroadcast()); - assert (!ip4.isLoopback()); - assert (!ip4.isMulticast()); - assert (ip4.isUnicast()); - assert (!ip4.isLinkLocal()); - assert (!ip4.isSiteLocal()); - assert (!ip4.isWellKnownMC()); - assert (!ip4.isNodeLocalMC()); - assert (!ip4.isLinkLocalMC()); - assert (!ip4.isSiteLocalMC()); - assert (!ip4.isOrgLocalMC()); - assert (!ip4.isGlobalMC()); - - IPAddress ip5("169.254.1.20"); // link local unicast - assert (!ip5.isWildcard()); - assert (!ip5.isBroadcast()); - assert (!ip5.isLoopback()); - assert (!ip5.isMulticast()); - assert (ip5.isUnicast()); - assert (ip5.isLinkLocal()); - assert (!ip5.isSiteLocal()); - assert (!ip5.isWellKnownMC()); - assert (!ip5.isNodeLocalMC()); - assert (!ip5.isLinkLocalMC()); - assert (!ip5.isSiteLocalMC()); - assert (!ip5.isOrgLocalMC()); - assert (!ip5.isGlobalMC()); - - IPAddress ip6("192.168.1.120"); // site local unicast - assert (!ip6.isWildcard()); - assert (!ip6.isBroadcast()); - assert (!ip6.isLoopback()); - assert (!ip6.isMulticast()); - assert (ip6.isUnicast()); - assert (!ip6.isLinkLocal()); - assert (ip6.isSiteLocal()); - assert (!ip6.isWellKnownMC()); - assert (!ip6.isNodeLocalMC()); - assert (!ip6.isLinkLocalMC()); - assert (!ip6.isSiteLocalMC()); - assert (!ip6.isOrgLocalMC()); - assert (!ip6.isGlobalMC()); - - IPAddress ip7("10.0.0.138"); // site local unicast - assert (!ip7.isWildcard()); - assert (!ip7.isBroadcast()); - assert (!ip7.isLoopback()); - assert (!ip7.isMulticast()); - assert (ip7.isUnicast()); - assert (!ip7.isLinkLocal()); - assert (ip7.isSiteLocal()); - assert (!ip7.isWellKnownMC()); - assert (!ip7.isNodeLocalMC()); - assert (!ip7.isLinkLocalMC()); - assert (!ip7.isSiteLocalMC()); - assert (!ip7.isOrgLocalMC()); - assert (!ip7.isGlobalMC()); - - IPAddress ip8("172.18.1.200"); // site local unicast - assert (!ip8.isWildcard()); - assert (!ip8.isBroadcast()); - assert (!ip8.isLoopback()); - assert (!ip8.isMulticast()); - assert (ip8.isUnicast()); - assert (!ip8.isLinkLocal()); - assert (ip8.isSiteLocal()); - assert (!ip8.isWellKnownMC()); - assert (!ip8.isNodeLocalMC()); - assert (!ip8.isLinkLocalMC()); - assert (!ip8.isSiteLocalMC()); - assert (!ip8.isOrgLocalMC()); - assert (!ip8.isGlobalMC()); -} - - -void IPAddressTest::testMCClassification() -{ - IPAddress ip1("224.0.0.100"); // well-known multicast - assert (!ip1.isWildcard()); - assert (!ip1.isBroadcast()); - assert (!ip1.isLoopback()); - assert (ip1.isMulticast()); - assert (!ip1.isUnicast()); - assert (!ip1.isLinkLocal()); - assert (!ip1.isSiteLocal()); - assert (ip1.isWellKnownMC()); - assert (!ip1.isNodeLocalMC()); - assert (ip1.isLinkLocalMC()); // well known are in the range of link local - assert (!ip1.isSiteLocalMC()); - assert (!ip1.isOrgLocalMC()); - assert (!ip1.isGlobalMC()); - - IPAddress ip2("224.1.0.100"); // link local unicast - assert (!ip2.isWildcard()); - assert (!ip2.isBroadcast()); - assert (!ip2.isLoopback()); - assert (ip2.isMulticast()); - assert (!ip2.isUnicast()); - assert (!ip2.isLinkLocal()); - assert (!ip2.isSiteLocal()); - assert (!ip2.isWellKnownMC()); - assert (!ip2.isNodeLocalMC()); - assert (ip2.isLinkLocalMC()); - assert (!ip2.isSiteLocalMC()); - assert (!ip2.isOrgLocalMC()); - assert (ip2.isGlobalMC()); // link local fall in the range of global - - IPAddress ip3("239.255.0.100"); // site local unicast - assert (!ip3.isWildcard()); - assert (!ip3.isBroadcast()); - assert (!ip3.isLoopback()); - assert (ip3.isMulticast()); - assert (!ip3.isUnicast()); - assert (!ip3.isLinkLocal()); - assert (!ip3.isSiteLocal()); - assert (!ip3.isWellKnownMC()); - assert (!ip3.isNodeLocalMC()); - assert (!ip3.isLinkLocalMC()); - assert (ip3.isSiteLocalMC()); - assert (!ip3.isOrgLocalMC()); - assert (!ip3.isGlobalMC()); - - IPAddress ip4("239.192.0.100"); // org local unicast - assert (!ip4.isWildcard()); - assert (!ip4.isBroadcast()); - assert (!ip4.isLoopback()); - assert (ip4.isMulticast()); - assert (!ip4.isUnicast()); - assert (!ip4.isLinkLocal()); - assert (!ip4.isSiteLocal()); - assert (!ip4.isWellKnownMC()); - assert (!ip4.isNodeLocalMC()); - assert (!ip4.isLinkLocalMC()); - assert (!ip4.isSiteLocalMC()); - assert (ip4.isOrgLocalMC()); - assert (!ip4.isGlobalMC()); - - IPAddress ip5("224.2.127.254"); // global unicast - assert (!ip5.isWildcard()); - assert (!ip5.isBroadcast()); - assert (!ip5.isLoopback()); - assert (ip5.isMulticast()); - assert (!ip5.isUnicast()); - assert (!ip5.isLinkLocal()); - assert (!ip5.isSiteLocal()); - assert (!ip5.isWellKnownMC()); - assert (!ip5.isNodeLocalMC()); - assert (ip5.isLinkLocalMC()); // link local fall in the range of global - assert (!ip5.isSiteLocalMC()); - assert (!ip5.isOrgLocalMC()); - assert (ip5.isGlobalMC()); -} - - -void IPAddressTest::testClassification6() -{ -#ifdef POCO_HAVE_IPv6 -#endif -} - - -void IPAddressTest::testMCClassification6() -{ -#ifdef POCO_HAVE_IPv6 -#endif -} - - -void IPAddressTest::testRelationals() -{ - IPAddress ip1("192.168.1.120"); - IPAddress ip2(ip1); - IPAddress ip3; - IPAddress ip4("10.0.0.138"); - - assert (ip1 != ip4); - assert (ip1 == ip2); - assert (!(ip1 != ip2)); - assert (!(ip1 == ip4)); - assert (ip1 > ip4); - assert (ip1 >= ip4); - assert (ip4 < ip1); - assert (ip4 <= ip1); - assert (!(ip1 < ip4)); - assert (!(ip1 <= ip4)); - assert (!(ip4 > ip1)); - assert (!(ip4 >= ip1)); - - ip3 = ip1; - assert (ip1 == ip3); - ip3 = ip4; - assert (ip1 != ip3); - assert (ip3 == ip4); -} - - -void IPAddressTest::testRelationals6() -{ -#ifdef POCO_HAVE_IPv6 -#endif -} - - -void IPAddressTest::setUp() -{ -} - - -void IPAddressTest::tearDown() -{ -} - - -CppUnit::Test* IPAddressTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("IPAddressTest"); - - CppUnit_addTest(pSuite, IPAddressTest, testStringConv); - CppUnit_addTest(pSuite, IPAddressTest, testStringConv6); - CppUnit_addTest(pSuite, IPAddressTest, testParse); - CppUnit_addTest(pSuite, IPAddressTest, testClassification); - CppUnit_addTest(pSuite, IPAddressTest, testMCClassification); - CppUnit_addTest(pSuite, IPAddressTest, testClassification6); - CppUnit_addTest(pSuite, IPAddressTest, testMCClassification6); - CppUnit_addTest(pSuite, IPAddressTest, testRelationals); - CppUnit_addTest(pSuite, IPAddressTest, testRelationals6); - - return pSuite; -} +// +// IPAddressTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/IPAddressTest.cpp#1 $ +// +// 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 "IPAddressTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/IPAddress.h" +#include "Poco/Net/NetException.h" + + +using Poco::Net::IPAddress; +using Poco::Net::InvalidAddressException; + + +IPAddressTest::IPAddressTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +IPAddressTest::~IPAddressTest() +{ +} + + +void IPAddressTest::testStringConv() +{ + IPAddress ia1("127.0.0.1"); + assert (ia1.family() == IPAddress::IPv4); + assert (ia1.toString() == "127.0.0.1"); + + IPAddress ia2("192.168.1.120"); + assert (ia2.family() == IPAddress::IPv4); + assert (ia2.toString() == "192.168.1.120"); + + IPAddress ia3("255.255.255.255"); + assert (ia3.family() == IPAddress::IPv4); + assert (ia3.toString() == "255.255.255.255"); + + IPAddress ia4("0.0.0.0"); + assert (ia4.family() == IPAddress::IPv4); + assert (ia4.toString() == "0.0.0.0"); +} + + +void IPAddressTest::testStringConv6() +{ +#ifdef POCO_HAVE_IPv6 + IPAddress ia1("1080:0:0:0:8:600:200A:425C"); + assert (ia1.family() == IPAddress::IPv6); + assert (ia1.toString() == "1080::8:600:200A:425C"); + + IPAddress ia2("1080::8:600:200A:425C"); + assert (ia2.family() == IPAddress::IPv6); + assert (ia2.toString() == "1080::8:600:200A:425C"); + + IPAddress ia3("::192.168.1.120"); + assert (ia3.family() == IPAddress::IPv6); + assert (ia3.toString() == "::192.168.1.120"); + + IPAddress ia4("::FFFF:192.168.1.120"); + assert (ia4.family() == IPAddress::IPv6); + assert (ia4.toString() == "::FFFF:192.168.1.120"); +#endif +} + + +void IPAddressTest::testParse() +{ + IPAddress ip; + assert (IPAddress::tryParse("192.168.1.120", ip)); + + assert (!IPAddress::tryParse("192.168.1.280", ip)); + + ip = IPAddress::parse("192.168.1.120"); + try + { + ip = IPAddress::parse("192.168.1.280"); + fail("bad address - must throw"); + } + catch (InvalidAddressException&) + { + } +} + + +void IPAddressTest::testClassification() +{ + IPAddress ip1("0.0.0.0"); // wildcard + assert (ip1.isWildcard()); + assert (!ip1.isBroadcast()); + assert (!ip1.isLoopback()); + assert (!ip1.isMulticast()); + assert (!ip1.isUnicast()); + assert (!ip1.isLinkLocal()); + assert (!ip1.isSiteLocal()); + assert (!ip1.isWellKnownMC()); + assert (!ip1.isNodeLocalMC()); + assert (!ip1.isLinkLocalMC()); + assert (!ip1.isSiteLocalMC()); + assert (!ip1.isOrgLocalMC()); + assert (!ip1.isGlobalMC()); + + IPAddress ip2("255.255.255.255"); // broadcast + assert (!ip2.isWildcard()); + assert (ip2.isBroadcast()); + assert (!ip2.isLoopback()); + assert (!ip2.isMulticast()); + assert (!ip2.isUnicast()); + assert (!ip2.isLinkLocal()); + assert (!ip2.isSiteLocal()); + assert (!ip2.isWellKnownMC()); + assert (!ip2.isNodeLocalMC()); + assert (!ip2.isLinkLocalMC()); + assert (!ip2.isSiteLocalMC()); + assert (!ip2.isOrgLocalMC()); + assert (!ip2.isGlobalMC()); + + IPAddress ip3("127.0.0.1"); // loopback + assert (!ip3.isWildcard()); + assert (!ip3.isBroadcast()); + assert (ip3.isLoopback()); + assert (!ip3.isMulticast()); + assert (ip3.isUnicast()); + assert (!ip3.isLinkLocal()); + assert (!ip3.isSiteLocal()); + assert (!ip3.isWellKnownMC()); + assert (!ip3.isNodeLocalMC()); + assert (!ip3.isLinkLocalMC()); + assert (!ip3.isSiteLocalMC()); + assert (!ip3.isOrgLocalMC()); + assert (!ip3.isGlobalMC()); + + IPAddress ip4("80.122.195.86"); // unicast + assert (!ip4.isWildcard()); + assert (!ip4.isBroadcast()); + assert (!ip4.isLoopback()); + assert (!ip4.isMulticast()); + assert (ip4.isUnicast()); + assert (!ip4.isLinkLocal()); + assert (!ip4.isSiteLocal()); + assert (!ip4.isWellKnownMC()); + assert (!ip4.isNodeLocalMC()); + assert (!ip4.isLinkLocalMC()); + assert (!ip4.isSiteLocalMC()); + assert (!ip4.isOrgLocalMC()); + assert (!ip4.isGlobalMC()); + + IPAddress ip5("169.254.1.20"); // link local unicast + assert (!ip5.isWildcard()); + assert (!ip5.isBroadcast()); + assert (!ip5.isLoopback()); + assert (!ip5.isMulticast()); + assert (ip5.isUnicast()); + assert (ip5.isLinkLocal()); + assert (!ip5.isSiteLocal()); + assert (!ip5.isWellKnownMC()); + assert (!ip5.isNodeLocalMC()); + assert (!ip5.isLinkLocalMC()); + assert (!ip5.isSiteLocalMC()); + assert (!ip5.isOrgLocalMC()); + assert (!ip5.isGlobalMC()); + + IPAddress ip6("192.168.1.120"); // site local unicast + assert (!ip6.isWildcard()); + assert (!ip6.isBroadcast()); + assert (!ip6.isLoopback()); + assert (!ip6.isMulticast()); + assert (ip6.isUnicast()); + assert (!ip6.isLinkLocal()); + assert (ip6.isSiteLocal()); + assert (!ip6.isWellKnownMC()); + assert (!ip6.isNodeLocalMC()); + assert (!ip6.isLinkLocalMC()); + assert (!ip6.isSiteLocalMC()); + assert (!ip6.isOrgLocalMC()); + assert (!ip6.isGlobalMC()); + + IPAddress ip7("10.0.0.138"); // site local unicast + assert (!ip7.isWildcard()); + assert (!ip7.isBroadcast()); + assert (!ip7.isLoopback()); + assert (!ip7.isMulticast()); + assert (ip7.isUnicast()); + assert (!ip7.isLinkLocal()); + assert (ip7.isSiteLocal()); + assert (!ip7.isWellKnownMC()); + assert (!ip7.isNodeLocalMC()); + assert (!ip7.isLinkLocalMC()); + assert (!ip7.isSiteLocalMC()); + assert (!ip7.isOrgLocalMC()); + assert (!ip7.isGlobalMC()); + + IPAddress ip8("172.18.1.200"); // site local unicast + assert (!ip8.isWildcard()); + assert (!ip8.isBroadcast()); + assert (!ip8.isLoopback()); + assert (!ip8.isMulticast()); + assert (ip8.isUnicast()); + assert (!ip8.isLinkLocal()); + assert (ip8.isSiteLocal()); + assert (!ip8.isWellKnownMC()); + assert (!ip8.isNodeLocalMC()); + assert (!ip8.isLinkLocalMC()); + assert (!ip8.isSiteLocalMC()); + assert (!ip8.isOrgLocalMC()); + assert (!ip8.isGlobalMC()); +} + + +void IPAddressTest::testMCClassification() +{ + IPAddress ip1("224.0.0.100"); // well-known multicast + assert (!ip1.isWildcard()); + assert (!ip1.isBroadcast()); + assert (!ip1.isLoopback()); + assert (ip1.isMulticast()); + assert (!ip1.isUnicast()); + assert (!ip1.isLinkLocal()); + assert (!ip1.isSiteLocal()); + assert (ip1.isWellKnownMC()); + assert (!ip1.isNodeLocalMC()); + assert (ip1.isLinkLocalMC()); // well known are in the range of link local + assert (!ip1.isSiteLocalMC()); + assert (!ip1.isOrgLocalMC()); + assert (!ip1.isGlobalMC()); + + IPAddress ip2("224.1.0.100"); // link local unicast + assert (!ip2.isWildcard()); + assert (!ip2.isBroadcast()); + assert (!ip2.isLoopback()); + assert (ip2.isMulticast()); + assert (!ip2.isUnicast()); + assert (!ip2.isLinkLocal()); + assert (!ip2.isSiteLocal()); + assert (!ip2.isWellKnownMC()); + assert (!ip2.isNodeLocalMC()); + assert (ip2.isLinkLocalMC()); + assert (!ip2.isSiteLocalMC()); + assert (!ip2.isOrgLocalMC()); + assert (ip2.isGlobalMC()); // link local fall in the range of global + + IPAddress ip3("239.255.0.100"); // site local unicast + assert (!ip3.isWildcard()); + assert (!ip3.isBroadcast()); + assert (!ip3.isLoopback()); + assert (ip3.isMulticast()); + assert (!ip3.isUnicast()); + assert (!ip3.isLinkLocal()); + assert (!ip3.isSiteLocal()); + assert (!ip3.isWellKnownMC()); + assert (!ip3.isNodeLocalMC()); + assert (!ip3.isLinkLocalMC()); + assert (ip3.isSiteLocalMC()); + assert (!ip3.isOrgLocalMC()); + assert (!ip3.isGlobalMC()); + + IPAddress ip4("239.192.0.100"); // org local unicast + assert (!ip4.isWildcard()); + assert (!ip4.isBroadcast()); + assert (!ip4.isLoopback()); + assert (ip4.isMulticast()); + assert (!ip4.isUnicast()); + assert (!ip4.isLinkLocal()); + assert (!ip4.isSiteLocal()); + assert (!ip4.isWellKnownMC()); + assert (!ip4.isNodeLocalMC()); + assert (!ip4.isLinkLocalMC()); + assert (!ip4.isSiteLocalMC()); + assert (ip4.isOrgLocalMC()); + assert (!ip4.isGlobalMC()); + + IPAddress ip5("224.2.127.254"); // global unicast + assert (!ip5.isWildcard()); + assert (!ip5.isBroadcast()); + assert (!ip5.isLoopback()); + assert (ip5.isMulticast()); + assert (!ip5.isUnicast()); + assert (!ip5.isLinkLocal()); + assert (!ip5.isSiteLocal()); + assert (!ip5.isWellKnownMC()); + assert (!ip5.isNodeLocalMC()); + assert (ip5.isLinkLocalMC()); // link local fall in the range of global + assert (!ip5.isSiteLocalMC()); + assert (!ip5.isOrgLocalMC()); + assert (ip5.isGlobalMC()); +} + + +void IPAddressTest::testClassification6() +{ +#ifdef POCO_HAVE_IPv6 +#endif +} + + +void IPAddressTest::testMCClassification6() +{ +#ifdef POCO_HAVE_IPv6 +#endif +} + + +void IPAddressTest::testRelationals() +{ + IPAddress ip1("192.168.1.120"); + IPAddress ip2(ip1); + IPAddress ip3; + IPAddress ip4("10.0.0.138"); + + assert (ip1 != ip4); + assert (ip1 == ip2); + assert (!(ip1 != ip2)); + assert (!(ip1 == ip4)); + assert (ip1 > ip4); + assert (ip1 >= ip4); + assert (ip4 < ip1); + assert (ip4 <= ip1); + assert (!(ip1 < ip4)); + assert (!(ip1 <= ip4)); + assert (!(ip4 > ip1)); + assert (!(ip4 >= ip1)); + + ip3 = ip1; + assert (ip1 == ip3); + ip3 = ip4; + assert (ip1 != ip3); + assert (ip3 == ip4); +} + + +void IPAddressTest::testRelationals6() +{ +#ifdef POCO_HAVE_IPv6 +#endif +} + + +void IPAddressTest::setUp() +{ +} + + +void IPAddressTest::tearDown() +{ +} + + +CppUnit::Test* IPAddressTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("IPAddressTest"); + + CppUnit_addTest(pSuite, IPAddressTest, testStringConv); + CppUnit_addTest(pSuite, IPAddressTest, testStringConv6); + CppUnit_addTest(pSuite, IPAddressTest, testParse); + CppUnit_addTest(pSuite, IPAddressTest, testClassification); + CppUnit_addTest(pSuite, IPAddressTest, testMCClassification); + CppUnit_addTest(pSuite, IPAddressTest, testClassification6); + CppUnit_addTest(pSuite, IPAddressTest, testMCClassification6); + CppUnit_addTest(pSuite, IPAddressTest, testRelationals); + CppUnit_addTest(pSuite, IPAddressTest, testRelationals6); + + return pSuite; +} diff --git a/Net/testsuite/src/IPAddressTest.h b/Net/testsuite/src/IPAddressTest.h index e10b7bf8c..c47bb650d 100644 --- a/Net/testsuite/src/IPAddressTest.h +++ b/Net/testsuite/src/IPAddressTest.h @@ -1,68 +1,68 @@ -// -// IPAddressTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/IPAddressTest.h#1 $ -// -// Definition of the IPAddressTest 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 IPAddressTest_INCLUDED -#define IPAddressTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class IPAddressTest: public CppUnit::TestCase -{ -public: - IPAddressTest(const std::string& name); - ~IPAddressTest(); - - void testStringConv(); - void testStringConv6(); - void testParse(); - void testClassification(); - void testMCClassification(); - void testClassification6(); - void testMCClassification6(); - void testRelationals(); - void testRelationals6(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // IPAddressTest_INCLUDED +// +// IPAddressTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/IPAddressTest.h#1 $ +// +// Definition of the IPAddressTest 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 IPAddressTest_INCLUDED +#define IPAddressTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class IPAddressTest: public CppUnit::TestCase +{ +public: + IPAddressTest(const std::string& name); + ~IPAddressTest(); + + void testStringConv(); + void testStringConv6(); + void testParse(); + void testClassification(); + void testMCClassification(); + void testClassification6(); + void testMCClassification6(); + void testRelationals(); + void testRelationals6(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // IPAddressTest_INCLUDED diff --git a/Net/testsuite/src/MailMessageTest.cpp b/Net/testsuite/src/MailMessageTest.cpp index b00d92c46..40fe16e38 100644 --- a/Net/testsuite/src/MailMessageTest.cpp +++ b/Net/testsuite/src/MailMessageTest.cpp @@ -1,441 +1,441 @@ -// -// MailMessageTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MailMessageTest.cpp#1 $ -// -// 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 "MailMessageTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/MailMessage.h" -#include "Poco/Net/MailRecipient.h" -#include "Poco/Net/PartHandler.h" -#include "Poco/Net/StringPartSource.h" -#include "Poco/Net/MediaType.h" -#include "Poco/Timestamp.h" -#include -#include - - -using Poco::Net::MailMessage; -using Poco::Net::MailRecipient; -using Poco::Net::MessageHeader; -using Poco::Net::PartHandler; -using Poco::Net::MediaType; -using Poco::Net::StringPartSource; -using Poco::Timestamp; - - -namespace -{ - class StringPartHandler: public PartHandler - { - public: - StringPartHandler() - { - } - - void handlePart(const MessageHeader& header, std::istream& stream) - { - _disp.push_back(header["Content-Disposition"]); - _type.push_back(header["Content-Type"]); - std::string data; - int ch = stream.get(); - while (ch > 0) - { - data += (char) ch; - ch = stream.get(); - } - _data.push_back(data); - } - - const std::vector& data() const - { - return _data; - } - - const std::vector& disp() const - { - return _disp; - } - - const std::vector& type() const - { - return _type; - } - - private: - std::vector _data; - std::vector _disp; - std::vector _type; - }; -} - - -MailMessageTest::MailMessageTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MailMessageTest::~MailMessageTest() -{ -} - - -void MailMessageTest::testWriteQP() -{ - MailMessage message; - MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); - MailRecipient r2(MailRecipient::CC_RECIPIENT, "jane.doe@no.where", "Jane Doe"); - MailRecipient r3(MailRecipient::BCC_RECIPIENT, "walter.foo@no.where", "Frank Foo"); - MailRecipient r4(MailRecipient::BCC_RECIPIENT, "bernie.bar@no.where", "Bernie Bar"); - message.addRecipient(r1); - message.addRecipient(r2); - message.addRecipient(r3); - message.addRecipient(r4); - message.setSubject("Test Message"); - message.setSender("poco@appinf.com"); - message.setContent( - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n" - "To test the quoted-printable encoding, we'll put an extra long line here. This should be enough.\r\n" - "And here is some more =fe.\r\n" - ); - Timestamp ts(0); - message.setDate(ts); - - assert (!message.isMultipart()); - - std::ostringstream str; - message.write(str); - std::string s = str.str(); - assert (s == - "CC: Jane Doe \r\n" - "Content-Transfer-Encoding: quoted-printable\r\n" - "Content-Type: text/plain\r\n" - "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" - "From: poco@appinf.com\r\n" - "Subject: Test Message\r\n" - "To: John Doe \r\n" - "\r\n" - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n" - "To test the quoted-printable encoding, we'll put an extra long line here. T=\r\n" - "his should be enough.\r\n" - "And here is some more =3Dfe.\r\n" - ); -} - - -void MailMessageTest::testWrite8Bit() -{ - MailMessage message; - MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); - message.addRecipient(r1); - message.setSubject("Test Message"); - message.setSender("poco@appinf.com"); - message.setContent( - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n", - MailMessage::ENCODING_8BIT - ); - Timestamp ts(0); - message.setDate(ts); - - std::ostringstream str; - message.write(str); - std::string s = str.str(); - assert (s == - "Content-Transfer-Encoding: 8bit\r\n" - "Content-Type: text/plain\r\n" - "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" - "From: poco@appinf.com\r\n" - "Subject: Test Message\r\n" - "To: John Doe \r\n" - "\r\n" - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n" - ); -} - - -void MailMessageTest::testWriteBase64() -{ - MailMessage message; - MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); - message.addRecipient(r1); - message.setSubject("Test Message"); - message.setSender("poco@appinf.com"); - message.setContent( - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n", - MailMessage::ENCODING_BASE64 - ); - Timestamp ts(0); - message.setDate(ts); - - std::ostringstream str; - message.write(str); - std::string s = str.str(); - assert (s == - "Content-Transfer-Encoding: base64\r\n" - "Content-Type: text/plain\r\n" - "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" - "From: poco@appinf.com\r\n" - "Subject: Test Message\r\n" - "To: John Doe \r\n" - "\r\n" - "SGVsbG8sIHdvcmxkIQ0KVGhpcyBpcyBhIHRlc3QgZm9yIHRoZSBNYWlsTWVzc2FnZSBjbGFz\r\n" - "cy4NCg==" - ); -} - - -void MailMessageTest::testWriteManyRecipients() -{ - MailMessage message; - MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); - MailRecipient r2(MailRecipient::PRIMARY_RECIPIENT, "jane.doe@no.where", "Jane Doe"); - MailRecipient r3(MailRecipient::PRIMARY_RECIPIENT, "walter.foo@no.where", "Frank Foo"); - MailRecipient r4(MailRecipient::PRIMARY_RECIPIENT, "bernie.bar@no.where", "Bernie Bar"); - MailRecipient r5(MailRecipient::PRIMARY_RECIPIENT, "joe.spammer@no.where", "Joe Spammer"); - message.addRecipient(r1); - message.addRecipient(r2); - message.addRecipient(r3); - message.addRecipient(r4); - message.addRecipient(r5); - message.setSubject("Test Message"); - message.setSender("poco@appinf.com"); - message.setContent( - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n", - MailMessage::ENCODING_8BIT - ); - Timestamp ts(0); - message.setDate(ts); - - std::ostringstream str; - message.write(str); - std::string s = str.str(); - assert (s == - "Content-Transfer-Encoding: 8bit\r\n" - "Content-Type: text/plain\r\n" - "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" - "From: poco@appinf.com\r\n" - "Subject: Test Message\r\n" - "To: John Doe , Jane Doe , \r\n" - "\tFrank Foo , Bernie Bar , \r\n" - "\tJoe Spammer \r\n" - "\r\n" - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n" - ); -} - - -void MailMessageTest::testWriteMultiPart() -{ - MailMessage message; - MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); - message.addRecipient(r1); - message.setSubject("Test Message"); - message.setSender("poco@appinf.com"); - Timestamp ts(0); - message.setDate(ts); - message.addContent(new StringPartSource("Hello World!\r\n", "text/plain"), MailMessage::ENCODING_8BIT); - message.addAttachment("sample", new StringPartSource("This is some binary data. Really.", "application/octet-stream", "sample.dat")); - - assert (message.isMultipart()); - - std::ostringstream str; - message.write(str); - std::string s = str.str(); - std::string rawMsg( - "Content-Type: multipart/mixed; boundary=$\r\n" - "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" - "From: poco@appinf.com\r\n" - "Mime-Version: 1.0\r\n" - "Subject: Test Message\r\n" - "To: John Doe \r\n" - "\r\n" - "\r\n" - "--$\r\n" - "Content-Disposition: inline\r\n" - "Content-Transfer-Encoding: 8bit\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "Hello World!\r\n" - "\r\n" - "--$\r\n" - "Content-Disposition: attachment; filename=sample.dat\r\n" - "Content-Transfer-Encoding: base64\r\n" - "Content-Type: application/octet-stream; name=sample\r\n" - "\r\n" - "VGhpcyBpcyBzb21lIGJpbmFyeSBkYXRhLiBSZWFsbHku\r\n" - "--$--\r\n" - ); - std::string::size_type p1 = s.find('=') + 1; - std::string::size_type p2 = s.find('\r'); - std::string boundary(s, p1, p2 - p1); - std::string msg; - for (std::string::const_iterator it = rawMsg.begin(); it != rawMsg.end(); ++it) - { - if (*it == '$') - msg += boundary; - else - msg += *it; - } - assert (s == msg); -} - - -void MailMessageTest::testReadQP() -{ - std::istringstream istr( - "Content-Transfer-Encoding: quoted-printable\r\n" - "Content-Type: text/plain\r\n" - "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" - "From: poco@appinf.com\r\n" - "Subject: Test Message\r\n" - "To: John Doe \r\n" - "\r\n" - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n" - "To test the quoted-printable encoding, we'll put an extra long line here. T=\r\n" - "his should be enough.\r\n" - "And here is some more =3Dfe.\r\n" - ); - - MailMessage message; - message.read(istr); - - assert (message.getSender() == "poco@appinf.com"); - assert (message.getContentType() == "text/plain"); - assert (message.getContent() == - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n" - "To test the quoted-printable encoding, we'll put an extra long line here. This should be enough.\r\n" - "And here is some more =fe.\r\n" - ); -} - - -void MailMessageTest::testRead8Bit() -{ - std::istringstream istr( - "Content-Transfer-Encoding: 8bit\r\n" - "Content-Type: text/plain\r\n" - "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" - "From: poco@appinf.com\r\n" - "Subject: Test Message\r\n" - "To: John Doe \r\n" - "\r\n" - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n" - ); - - MailMessage message; - message.read(istr); - - assert (message.getSender() == "poco@appinf.com"); - assert (message.getContentType() == "text/plain"); - assert (message.getContent() == - "Hello, world!\r\n" - "This is a test for the MailMessage class.\r\n" - ); -} - - -void MailMessageTest::testReadMultiPart() -{ - std::istringstream istr( - "Content-Type: multipart/mixed; boundary=MIME_boundary_01234567\r\n" - "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" - "From: poco@appinf.com\r\n" - "Mime-Version: 1.0\r\n" - "Subject: Test Message\r\n" - "To: John Doe \r\n" - "\r\n" - "\r\n" - "--MIME_boundary_01234567\r\n" - "Content-Disposition: inline\r\n" - "Content-Transfer-Encoding: 8bit\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "Hello World!\r\n" - "\r\n" - "--MIME_boundary_01234567\r\n" - "Content-Disposition: attachment; filename=sample.dat\r\n" - "Content-Transfer-Encoding: base64\r\n" - "Content-Type: application/octet-stream; name=sample\r\n" - "\r\n" - "VGhpcyBpcyBzb21lIGJpbmFyeSBkYXRhLiBSZWFsbHku\r\n" - "--MIME_boundary_01234567--\r\n" - ); - - StringPartHandler handler; - MailMessage message; - message.read(istr, handler); - - assert (handler.data().size() == 2); - assert (handler.data()[0] == "Hello World!\r\n"); - assert (handler.type()[0] == "text/plain"); - assert (handler.disp()[0] == "inline"); - - assert (handler.data()[1] == "This is some binary data. Really."); - assert (handler.type()[1] == "application/octet-stream; name=sample"); - assert (handler.disp()[1] == "attachment; filename=sample.dat"); -} - - -void MailMessageTest::setUp() -{ -} - - -void MailMessageTest::tearDown() -{ -} - - -CppUnit::Test* MailMessageTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailMessageTest"); - - CppUnit_addTest(pSuite, MailMessageTest, testWriteQP); - CppUnit_addTest(pSuite, MailMessageTest, testWrite8Bit); - CppUnit_addTest(pSuite, MailMessageTest, testWriteBase64); - CppUnit_addTest(pSuite, MailMessageTest, testWriteManyRecipients); - CppUnit_addTest(pSuite, MailMessageTest, testWriteMultiPart); - CppUnit_addTest(pSuite, MailMessageTest, testReadQP); - CppUnit_addTest(pSuite, MailMessageTest, testRead8Bit); - CppUnit_addTest(pSuite, MailMessageTest, testReadMultiPart); - - return pSuite; -} +// +// MailMessageTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MailMessageTest.cpp#1 $ +// +// 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 "MailMessageTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/MailMessage.h" +#include "Poco/Net/MailRecipient.h" +#include "Poco/Net/PartHandler.h" +#include "Poco/Net/StringPartSource.h" +#include "Poco/Net/MediaType.h" +#include "Poco/Timestamp.h" +#include +#include + + +using Poco::Net::MailMessage; +using Poco::Net::MailRecipient; +using Poco::Net::MessageHeader; +using Poco::Net::PartHandler; +using Poco::Net::MediaType; +using Poco::Net::StringPartSource; +using Poco::Timestamp; + + +namespace +{ + class StringPartHandler: public PartHandler + { + public: + StringPartHandler() + { + } + + void handlePart(const MessageHeader& header, std::istream& stream) + { + _disp.push_back(header["Content-Disposition"]); + _type.push_back(header["Content-Type"]); + std::string data; + int ch = stream.get(); + while (ch > 0) + { + data += (char) ch; + ch = stream.get(); + } + _data.push_back(data); + } + + const std::vector& data() const + { + return _data; + } + + const std::vector& disp() const + { + return _disp; + } + + const std::vector& type() const + { + return _type; + } + + private: + std::vector _data; + std::vector _disp; + std::vector _type; + }; +} + + +MailMessageTest::MailMessageTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MailMessageTest::~MailMessageTest() +{ +} + + +void MailMessageTest::testWriteQP() +{ + MailMessage message; + MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); + MailRecipient r2(MailRecipient::CC_RECIPIENT, "jane.doe@no.where", "Jane Doe"); + MailRecipient r3(MailRecipient::BCC_RECIPIENT, "walter.foo@no.where", "Frank Foo"); + MailRecipient r4(MailRecipient::BCC_RECIPIENT, "bernie.bar@no.where", "Bernie Bar"); + message.addRecipient(r1); + message.addRecipient(r2); + message.addRecipient(r3); + message.addRecipient(r4); + message.setSubject("Test Message"); + message.setSender("poco@appinf.com"); + message.setContent( + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n" + "To test the quoted-printable encoding, we'll put an extra long line here. This should be enough.\r\n" + "And here is some more =fe.\r\n" + ); + Timestamp ts(0); + message.setDate(ts); + + assert (!message.isMultipart()); + + std::ostringstream str; + message.write(str); + std::string s = str.str(); + assert (s == + "CC: Jane Doe \r\n" + "Content-Transfer-Encoding: quoted-printable\r\n" + "Content-Type: text/plain\r\n" + "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" + "From: poco@appinf.com\r\n" + "Subject: Test Message\r\n" + "To: John Doe \r\n" + "\r\n" + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n" + "To test the quoted-printable encoding, we'll put an extra long line here. T=\r\n" + "his should be enough.\r\n" + "And here is some more =3Dfe.\r\n" + ); +} + + +void MailMessageTest::testWrite8Bit() +{ + MailMessage message; + MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); + message.addRecipient(r1); + message.setSubject("Test Message"); + message.setSender("poco@appinf.com"); + message.setContent( + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n", + MailMessage::ENCODING_8BIT + ); + Timestamp ts(0); + message.setDate(ts); + + std::ostringstream str; + message.write(str); + std::string s = str.str(); + assert (s == + "Content-Transfer-Encoding: 8bit\r\n" + "Content-Type: text/plain\r\n" + "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" + "From: poco@appinf.com\r\n" + "Subject: Test Message\r\n" + "To: John Doe \r\n" + "\r\n" + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n" + ); +} + + +void MailMessageTest::testWriteBase64() +{ + MailMessage message; + MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); + message.addRecipient(r1); + message.setSubject("Test Message"); + message.setSender("poco@appinf.com"); + message.setContent( + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n", + MailMessage::ENCODING_BASE64 + ); + Timestamp ts(0); + message.setDate(ts); + + std::ostringstream str; + message.write(str); + std::string s = str.str(); + assert (s == + "Content-Transfer-Encoding: base64\r\n" + "Content-Type: text/plain\r\n" + "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" + "From: poco@appinf.com\r\n" + "Subject: Test Message\r\n" + "To: John Doe \r\n" + "\r\n" + "SGVsbG8sIHdvcmxkIQ0KVGhpcyBpcyBhIHRlc3QgZm9yIHRoZSBNYWlsTWVzc2FnZSBjbGFz\r\n" + "cy4NCg==" + ); +} + + +void MailMessageTest::testWriteManyRecipients() +{ + MailMessage message; + MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); + MailRecipient r2(MailRecipient::PRIMARY_RECIPIENT, "jane.doe@no.where", "Jane Doe"); + MailRecipient r3(MailRecipient::PRIMARY_RECIPIENT, "walter.foo@no.where", "Frank Foo"); + MailRecipient r4(MailRecipient::PRIMARY_RECIPIENT, "bernie.bar@no.where", "Bernie Bar"); + MailRecipient r5(MailRecipient::PRIMARY_RECIPIENT, "joe.spammer@no.where", "Joe Spammer"); + message.addRecipient(r1); + message.addRecipient(r2); + message.addRecipient(r3); + message.addRecipient(r4); + message.addRecipient(r5); + message.setSubject("Test Message"); + message.setSender("poco@appinf.com"); + message.setContent( + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n", + MailMessage::ENCODING_8BIT + ); + Timestamp ts(0); + message.setDate(ts); + + std::ostringstream str; + message.write(str); + std::string s = str.str(); + assert (s == + "Content-Transfer-Encoding: 8bit\r\n" + "Content-Type: text/plain\r\n" + "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" + "From: poco@appinf.com\r\n" + "Subject: Test Message\r\n" + "To: John Doe , Jane Doe , \r\n" + "\tFrank Foo , Bernie Bar , \r\n" + "\tJoe Spammer \r\n" + "\r\n" + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n" + ); +} + + +void MailMessageTest::testWriteMultiPart() +{ + MailMessage message; + MailRecipient r1(MailRecipient::PRIMARY_RECIPIENT, "john.doe@no.where", "John Doe"); + message.addRecipient(r1); + message.setSubject("Test Message"); + message.setSender("poco@appinf.com"); + Timestamp ts(0); + message.setDate(ts); + message.addContent(new StringPartSource("Hello World!\r\n", "text/plain"), MailMessage::ENCODING_8BIT); + message.addAttachment("sample", new StringPartSource("This is some binary data. Really.", "application/octet-stream", "sample.dat")); + + assert (message.isMultipart()); + + std::ostringstream str; + message.write(str); + std::string s = str.str(); + std::string rawMsg( + "Content-Type: multipart/mixed; boundary=$\r\n" + "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" + "From: poco@appinf.com\r\n" + "Mime-Version: 1.0\r\n" + "Subject: Test Message\r\n" + "To: John Doe \r\n" + "\r\n" + "\r\n" + "--$\r\n" + "Content-Disposition: inline\r\n" + "Content-Transfer-Encoding: 8bit\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Hello World!\r\n" + "\r\n" + "--$\r\n" + "Content-Disposition: attachment; filename=sample.dat\r\n" + "Content-Transfer-Encoding: base64\r\n" + "Content-Type: application/octet-stream; name=sample\r\n" + "\r\n" + "VGhpcyBpcyBzb21lIGJpbmFyeSBkYXRhLiBSZWFsbHku\r\n" + "--$--\r\n" + ); + std::string::size_type p1 = s.find('=') + 1; + std::string::size_type p2 = s.find('\r'); + std::string boundary(s, p1, p2 - p1); + std::string msg; + for (std::string::const_iterator it = rawMsg.begin(); it != rawMsg.end(); ++it) + { + if (*it == '$') + msg += boundary; + else + msg += *it; + } + assert (s == msg); +} + + +void MailMessageTest::testReadQP() +{ + std::istringstream istr( + "Content-Transfer-Encoding: quoted-printable\r\n" + "Content-Type: text/plain\r\n" + "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" + "From: poco@appinf.com\r\n" + "Subject: Test Message\r\n" + "To: John Doe \r\n" + "\r\n" + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n" + "To test the quoted-printable encoding, we'll put an extra long line here. T=\r\n" + "his should be enough.\r\n" + "And here is some more =3Dfe.\r\n" + ); + + MailMessage message; + message.read(istr); + + assert (message.getSender() == "poco@appinf.com"); + assert (message.getContentType() == "text/plain"); + assert (message.getContent() == + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n" + "To test the quoted-printable encoding, we'll put an extra long line here. This should be enough.\r\n" + "And here is some more =fe.\r\n" + ); +} + + +void MailMessageTest::testRead8Bit() +{ + std::istringstream istr( + "Content-Transfer-Encoding: 8bit\r\n" + "Content-Type: text/plain\r\n" + "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" + "From: poco@appinf.com\r\n" + "Subject: Test Message\r\n" + "To: John Doe \r\n" + "\r\n" + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n" + ); + + MailMessage message; + message.read(istr); + + assert (message.getSender() == "poco@appinf.com"); + assert (message.getContentType() == "text/plain"); + assert (message.getContent() == + "Hello, world!\r\n" + "This is a test for the MailMessage class.\r\n" + ); +} + + +void MailMessageTest::testReadMultiPart() +{ + std::istringstream istr( + "Content-Type: multipart/mixed; boundary=MIME_boundary_01234567\r\n" + "Date: Thu, 1 Jan 1970 00:00:00 GMT\r\n" + "From: poco@appinf.com\r\n" + "Mime-Version: 1.0\r\n" + "Subject: Test Message\r\n" + "To: John Doe \r\n" + "\r\n" + "\r\n" + "--MIME_boundary_01234567\r\n" + "Content-Disposition: inline\r\n" + "Content-Transfer-Encoding: 8bit\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Hello World!\r\n" + "\r\n" + "--MIME_boundary_01234567\r\n" + "Content-Disposition: attachment; filename=sample.dat\r\n" + "Content-Transfer-Encoding: base64\r\n" + "Content-Type: application/octet-stream; name=sample\r\n" + "\r\n" + "VGhpcyBpcyBzb21lIGJpbmFyeSBkYXRhLiBSZWFsbHku\r\n" + "--MIME_boundary_01234567--\r\n" + ); + + StringPartHandler handler; + MailMessage message; + message.read(istr, handler); + + assert (handler.data().size() == 2); + assert (handler.data()[0] == "Hello World!\r\n"); + assert (handler.type()[0] == "text/plain"); + assert (handler.disp()[0] == "inline"); + + assert (handler.data()[1] == "This is some binary data. Really."); + assert (handler.type()[1] == "application/octet-stream; name=sample"); + assert (handler.disp()[1] == "attachment; filename=sample.dat"); +} + + +void MailMessageTest::setUp() +{ +} + + +void MailMessageTest::tearDown() +{ +} + + +CppUnit::Test* MailMessageTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailMessageTest"); + + CppUnit_addTest(pSuite, MailMessageTest, testWriteQP); + CppUnit_addTest(pSuite, MailMessageTest, testWrite8Bit); + CppUnit_addTest(pSuite, MailMessageTest, testWriteBase64); + CppUnit_addTest(pSuite, MailMessageTest, testWriteManyRecipients); + CppUnit_addTest(pSuite, MailMessageTest, testWriteMultiPart); + CppUnit_addTest(pSuite, MailMessageTest, testReadQP); + CppUnit_addTest(pSuite, MailMessageTest, testRead8Bit); + CppUnit_addTest(pSuite, MailMessageTest, testReadMultiPart); + + return pSuite; +} diff --git a/Net/testsuite/src/MailMessageTest.h b/Net/testsuite/src/MailMessageTest.h index 28894146e..df60b71d7 100644 --- a/Net/testsuite/src/MailMessageTest.h +++ b/Net/testsuite/src/MailMessageTest.h @@ -1,67 +1,67 @@ -// -// MailMessageTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/MailMessageTest.h#1 $ -// -// Definition of the MailMessageTest 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 MailMessageTest_INCLUDED -#define MailMessageTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class MailMessageTest: public CppUnit::TestCase -{ -public: - MailMessageTest(const std::string& name); - ~MailMessageTest(); - - void testWriteQP(); - void testWrite8Bit(); - void testWriteBase64(); - void testWriteManyRecipients(); - void testWriteMultiPart(); - void testReadQP(); - void testRead8Bit(); - void testReadMultiPart(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MailMessageTest_INCLUDED +// +// MailMessageTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/MailMessageTest.h#1 $ +// +// Definition of the MailMessageTest 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 MailMessageTest_INCLUDED +#define MailMessageTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class MailMessageTest: public CppUnit::TestCase +{ +public: + MailMessageTest(const std::string& name); + ~MailMessageTest(); + + void testWriteQP(); + void testWrite8Bit(); + void testWriteBase64(); + void testWriteManyRecipients(); + void testWriteMultiPart(); + void testReadQP(); + void testRead8Bit(); + void testReadMultiPart(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MailMessageTest_INCLUDED diff --git a/Net/testsuite/src/MailStreamTest.cpp b/Net/testsuite/src/MailStreamTest.cpp index 13a01676f..ab7804401 100644 --- a/Net/testsuite/src/MailStreamTest.cpp +++ b/Net/testsuite/src/MailStreamTest.cpp @@ -1,141 +1,141 @@ -// -// MailStreamTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MailStreamTest.cpp#1 $ -// -// 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 "MailStreamTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/MailStream.h" -#include "Poco/StreamCopier.h" -#include - - -using Poco::Net::MailInputStream; -using Poco::Net::MailOutputStream; -using Poco::StreamCopier; - - -MailStreamTest::MailStreamTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MailStreamTest::~MailStreamTest() -{ -} - - -void MailStreamTest::testMailInputStream() -{ - std::istringstream istr( - "From: john.doe@no.domain\r\n" - "To: jane.doe@no.domain\r\n" - "Subject: test\r\n" - "\r\n" - "This is a test.\r\n" - "\rThis.is.\ngarbage\r.\r\n" - ".This line starts with a period.\r\n" - "..and this one too\r\n" - "..\r\n" - ".\r\n" - ); - - MailInputStream mis(istr); - std::ostringstream ostr; - StreamCopier::copyStream(mis, ostr); - std::string s(ostr.str()); - assert (s == - "From: john.doe@no.domain\r\n" - "To: jane.doe@no.domain\r\n" - "Subject: test\r\n" - "\r\n" - "This is a test.\r\n" - "\rThis.is.\ngarbage\r.\r\n" - ".This line starts with a period.\r\n" - ".and this one too\r\n" - ".\r\n" - ); -} - - -void MailStreamTest::testMailOutputStream() -{ - std::string msg( - "From: john.doe@no.domain\r\n" - "To: jane.doe@no.domain\r\n" - "Subject: test\r\n" - "\r\n" - "This is a test.\r\n" - "\rThis.is.\ngarbage\r.\r\n" - ".This line starts with a period.\r\n" - ".and this one too\r\n" - ".\r\n" - ); - - std::ostringstream ostr; - MailOutputStream mos(ostr); - mos << msg; - mos.close(); - std::string s(ostr.str()); - assert (s == - "From: john.doe@no.domain\r\n" - "To: jane.doe@no.domain\r\n" - "Subject: test\r\n" - "\r\n" - "This is a test.\r\n" - "\rThis.is.\ngarbage\r.\r\n" - "..This line starts with a period.\r\n" - "..and this one too\r\n" - "..\r\n" - ".\r\n" - ); -} - - -void MailStreamTest::setUp() -{ -} - - -void MailStreamTest::tearDown() -{ -} - - -CppUnit::Test* MailStreamTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailStreamTest"); - - CppUnit_addTest(pSuite, MailStreamTest, testMailInputStream); - CppUnit_addTest(pSuite, MailStreamTest, testMailOutputStream); - - return pSuite; -} +// +// MailStreamTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MailStreamTest.cpp#1 $ +// +// 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 "MailStreamTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/MailStream.h" +#include "Poco/StreamCopier.h" +#include + + +using Poco::Net::MailInputStream; +using Poco::Net::MailOutputStream; +using Poco::StreamCopier; + + +MailStreamTest::MailStreamTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MailStreamTest::~MailStreamTest() +{ +} + + +void MailStreamTest::testMailInputStream() +{ + std::istringstream istr( + "From: john.doe@no.domain\r\n" + "To: jane.doe@no.domain\r\n" + "Subject: test\r\n" + "\r\n" + "This is a test.\r\n" + "\rThis.is.\ngarbage\r.\r\n" + ".This line starts with a period.\r\n" + "..and this one too\r\n" + "..\r\n" + ".\r\n" + ); + + MailInputStream mis(istr); + std::ostringstream ostr; + StreamCopier::copyStream(mis, ostr); + std::string s(ostr.str()); + assert (s == + "From: john.doe@no.domain\r\n" + "To: jane.doe@no.domain\r\n" + "Subject: test\r\n" + "\r\n" + "This is a test.\r\n" + "\rThis.is.\ngarbage\r.\r\n" + ".This line starts with a period.\r\n" + ".and this one too\r\n" + ".\r\n" + ); +} + + +void MailStreamTest::testMailOutputStream() +{ + std::string msg( + "From: john.doe@no.domain\r\n" + "To: jane.doe@no.domain\r\n" + "Subject: test\r\n" + "\r\n" + "This is a test.\r\n" + "\rThis.is.\ngarbage\r.\r\n" + ".This line starts with a period.\r\n" + ".and this one too\r\n" + ".\r\n" + ); + + std::ostringstream ostr; + MailOutputStream mos(ostr); + mos << msg; + mos.close(); + std::string s(ostr.str()); + assert (s == + "From: john.doe@no.domain\r\n" + "To: jane.doe@no.domain\r\n" + "Subject: test\r\n" + "\r\n" + "This is a test.\r\n" + "\rThis.is.\ngarbage\r.\r\n" + "..This line starts with a period.\r\n" + "..and this one too\r\n" + "..\r\n" + ".\r\n" + ); +} + + +void MailStreamTest::setUp() +{ +} + + +void MailStreamTest::tearDown() +{ +} + + +CppUnit::Test* MailStreamTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailStreamTest"); + + CppUnit_addTest(pSuite, MailStreamTest, testMailInputStream); + CppUnit_addTest(pSuite, MailStreamTest, testMailOutputStream); + + return pSuite; +} diff --git a/Net/testsuite/src/MailStreamTest.h b/Net/testsuite/src/MailStreamTest.h index 88f4a701c..312d48acd 100644 --- a/Net/testsuite/src/MailStreamTest.h +++ b/Net/testsuite/src/MailStreamTest.h @@ -1,61 +1,61 @@ -// -// MailStreamTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/MailStreamTest.h#1 $ -// -// Definition of the MailStreamTest 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 MailStreamTest_INCLUDED -#define MailStreamTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class MailStreamTest: public CppUnit::TestCase -{ -public: - MailStreamTest(const std::string& name); - ~MailStreamTest(); - - void testMailInputStream(); - void testMailOutputStream(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MailStreamTest_INCLUDED +// +// MailStreamTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/MailStreamTest.h#1 $ +// +// Definition of the MailStreamTest 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 MailStreamTest_INCLUDED +#define MailStreamTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class MailStreamTest: public CppUnit::TestCase +{ +public: + MailStreamTest(const std::string& name); + ~MailStreamTest(); + + void testMailInputStream(); + void testMailOutputStream(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MailStreamTest_INCLUDED diff --git a/Net/testsuite/src/MailTestSuite.cpp b/Net/testsuite/src/MailTestSuite.cpp index 6cde46c34..b32263ebe 100644 --- a/Net/testsuite/src/MailTestSuite.cpp +++ b/Net/testsuite/src/MailTestSuite.cpp @@ -1,50 +1,50 @@ -// -// MailTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MailTestSuite.cpp#1 $ -// -// 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 "MailTestSuite.h" -#include "MailMessageTest.h" -#include "MailStreamTest.h" -#include "SMTPClientSessionTest.h" -#include "POP3ClientSessionTest.h" - - -CppUnit::Test* MailTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailTestSuite"); - - pSuite->addTest(MailMessageTest::suite()); - pSuite->addTest(MailStreamTest::suite()); - pSuite->addTest(SMTPClientSessionTest::suite()); - pSuite->addTest(POP3ClientSessionTest::suite()); - - return pSuite; -} +// +// MailTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MailTestSuite.cpp#1 $ +// +// 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 "MailTestSuite.h" +#include "MailMessageTest.h" +#include "MailStreamTest.h" +#include "SMTPClientSessionTest.h" +#include "POP3ClientSessionTest.h" + + +CppUnit::Test* MailTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailTestSuite"); + + pSuite->addTest(MailMessageTest::suite()); + pSuite->addTest(MailStreamTest::suite()); + pSuite->addTest(SMTPClientSessionTest::suite()); + pSuite->addTest(POP3ClientSessionTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/MailTestSuite.h b/Net/testsuite/src/MailTestSuite.h index bc81c0351..cc6b8ff43 100644 --- a/Net/testsuite/src/MailTestSuite.h +++ b/Net/testsuite/src/MailTestSuite.h @@ -1,49 +1,49 @@ -// -// MailTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/MailTestSuite.h#1 $ -// -// Definition of the MailTestSuite 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 MailTestSuite_INCLUDED -#define MailTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class MailTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // MailTestSuite_INCLUDED +// +// MailTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/MailTestSuite.h#1 $ +// +// Definition of the MailTestSuite 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 MailTestSuite_INCLUDED +#define MailTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class MailTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // MailTestSuite_INCLUDED diff --git a/Net/testsuite/src/MediaTypeTest.cpp b/Net/testsuite/src/MediaTypeTest.cpp index a2a9b1c2d..0d0bbf925 100644 --- a/Net/testsuite/src/MediaTypeTest.cpp +++ b/Net/testsuite/src/MediaTypeTest.cpp @@ -1,121 +1,121 @@ -// -// MediaTypeTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MediaTypeTest.cpp#1 $ -// -// 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 "MediaTypeTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/MediaType.h" - - -using Poco::Net::MediaType; - - -MediaTypeTest::MediaTypeTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MediaTypeTest::~MediaTypeTest() -{ -} - - -void MediaTypeTest::testParse() -{ - MediaType mt1("text/plain"); - assert (mt1.getType() == "text"); - assert (mt1.getSubType() == "plain"); - assert (mt1.parameters().empty()); - - MediaType mt2("text/xml;charset=us-ascii"); - assert (mt2.getType() == "text"); - assert (mt2.getSubType() == "xml"); - assert (!mt2.parameters().empty()); - assert (mt2.getParameter("charset") == "us-ascii"); - - MediaType mt3("application/test; param1=value1; param2=\"value 2\""); - assert (mt3.getType() == "application"); - assert (mt3.getSubType() == "test"); - assert (!mt3.parameters().empty()); - assert (mt3.getParameter("param1") == "value1"); - assert (mt3.getParameter("PARAM2") == "value 2"); -} - - -void MediaTypeTest::testToString() -{ - MediaType mt1("text", "plain"); - assert (mt1.toString() == "text/plain"); - - mt1.setParameter("charset", "iso-8859-1"); - assert (mt1.toString() == "text/plain; charset=iso-8859-1"); - - MediaType mt2("application", "test"); - mt2.setParameter("param1", "value1"); - mt2.setParameter("param2", "value 2"); - assert (mt2.toString() == "application/test; param1=value1; param2=\"value 2\""); -} - - -void MediaTypeTest::testMatch() -{ - MediaType mt1("Text/Plain"); - MediaType mt2("text/plain"); - MediaType mt3("text/xml"); - assert (mt1.matches(mt2)); - assert (!mt1.matches(mt3)); - assert (mt1.matches("text")); - assert (mt2.matches("text")); - assert (mt3.matches("text")); -} - - -void MediaTypeTest::setUp() -{ -} - - -void MediaTypeTest::tearDown() -{ -} - - -CppUnit::Test* MediaTypeTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MediaTypeTest"); - - CppUnit_addTest(pSuite, MediaTypeTest, testParse); - CppUnit_addTest(pSuite, MediaTypeTest, testToString); - CppUnit_addTest(pSuite, MediaTypeTest, testMatch); - - return pSuite; -} +// +// MediaTypeTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MediaTypeTest.cpp#1 $ +// +// 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 "MediaTypeTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/MediaType.h" + + +using Poco::Net::MediaType; + + +MediaTypeTest::MediaTypeTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MediaTypeTest::~MediaTypeTest() +{ +} + + +void MediaTypeTest::testParse() +{ + MediaType mt1("text/plain"); + assert (mt1.getType() == "text"); + assert (mt1.getSubType() == "plain"); + assert (mt1.parameters().empty()); + + MediaType mt2("text/xml;charset=us-ascii"); + assert (mt2.getType() == "text"); + assert (mt2.getSubType() == "xml"); + assert (!mt2.parameters().empty()); + assert (mt2.getParameter("charset") == "us-ascii"); + + MediaType mt3("application/test; param1=value1; param2=\"value 2\""); + assert (mt3.getType() == "application"); + assert (mt3.getSubType() == "test"); + assert (!mt3.parameters().empty()); + assert (mt3.getParameter("param1") == "value1"); + assert (mt3.getParameter("PARAM2") == "value 2"); +} + + +void MediaTypeTest::testToString() +{ + MediaType mt1("text", "plain"); + assert (mt1.toString() == "text/plain"); + + mt1.setParameter("charset", "iso-8859-1"); + assert (mt1.toString() == "text/plain; charset=iso-8859-1"); + + MediaType mt2("application", "test"); + mt2.setParameter("param1", "value1"); + mt2.setParameter("param2", "value 2"); + assert (mt2.toString() == "application/test; param1=value1; param2=\"value 2\""); +} + + +void MediaTypeTest::testMatch() +{ + MediaType mt1("Text/Plain"); + MediaType mt2("text/plain"); + MediaType mt3("text/xml"); + assert (mt1.matches(mt2)); + assert (!mt1.matches(mt3)); + assert (mt1.matches("text")); + assert (mt2.matches("text")); + assert (mt3.matches("text")); +} + + +void MediaTypeTest::setUp() +{ +} + + +void MediaTypeTest::tearDown() +{ +} + + +CppUnit::Test* MediaTypeTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MediaTypeTest"); + + CppUnit_addTest(pSuite, MediaTypeTest, testParse); + CppUnit_addTest(pSuite, MediaTypeTest, testToString); + CppUnit_addTest(pSuite, MediaTypeTest, testMatch); + + return pSuite; +} diff --git a/Net/testsuite/src/MediaTypeTest.h b/Net/testsuite/src/MediaTypeTest.h index 93457016b..dfdcb2336 100644 --- a/Net/testsuite/src/MediaTypeTest.h +++ b/Net/testsuite/src/MediaTypeTest.h @@ -1,62 +1,62 @@ -// -// MediaTypeTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/MediaTypeTest.h#1 $ -// -// Definition of the MediaTypeTest 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 MediaTypeTest_INCLUDED -#define MediaTypeTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class MediaTypeTest: public CppUnit::TestCase -{ -public: - MediaTypeTest(const std::string& name); - ~MediaTypeTest(); - - void testParse(); - void testToString(); - void testMatch(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MediaTypeTest_INCLUDED +// +// MediaTypeTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/MediaTypeTest.h#1 $ +// +// Definition of the MediaTypeTest 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 MediaTypeTest_INCLUDED +#define MediaTypeTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class MediaTypeTest: public CppUnit::TestCase +{ +public: + MediaTypeTest(const std::string& name); + ~MediaTypeTest(); + + void testParse(); + void testToString(); + void testMatch(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MediaTypeTest_INCLUDED diff --git a/Net/testsuite/src/MessageHeaderTest.cpp b/Net/testsuite/src/MessageHeaderTest.cpp index baafea579..5031a877c 100644 --- a/Net/testsuite/src/MessageHeaderTest.cpp +++ b/Net/testsuite/src/MessageHeaderTest.cpp @@ -1,385 +1,385 @@ -// -// MessageHeaderTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MessageHeaderTest.cpp#1 $ -// -// 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 "MessageHeaderTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/MessageHeader.h" -#include "Poco/Net/NetException.h" -#include - - -using Poco::Net::MessageHeader; -using Poco::Net::NameValueCollection; -using Poco::Net::MessageException; - - -MessageHeaderTest::MessageHeaderTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MessageHeaderTest::~MessageHeaderTest() -{ -} - - -void MessageHeaderTest::testWrite() -{ - MessageHeader mh; - mh.set("name1", "value1"); - mh.set("name2", "value2"); - mh.set("name3", "value3"); - - std::ostringstream ostr; - mh.write(ostr); - std::string s = ostr.str(); - assert (s == "name1: value1\r\nname2: value2\r\nname3: value3\r\n"); -} - - -void MessageHeaderTest::testRead1() -{ - std::string s("name1: value1\r\nname2: value2\r\nname3: value3\r\n"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 3); - assert (mh["name1"] == "value1"); - assert (mh["name2"] == "value2"); - assert (mh["name3"] == "value3"); -} - - -void MessageHeaderTest::testRead2() -{ - std::string s("name1: value1\nname2: value2\nname3: value3\n"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 3); - assert (mh["name1"] == "value1"); - assert (mh["name2"] == "value2"); - assert (mh["name3"] == "value3"); -} - - -void MessageHeaderTest::testRead3() -{ - std::string s("name1: value1\r\n"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 1); - assert (mh["name1"] == "value1"); -} - - - -void MessageHeaderTest::testRead4() -{ - std::string s("name1: value1\r\nname2: value2\r\n\r\nsomedata"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 2); - assert (mh["name1"] == "value1"); - assert (mh["name2"] == "value2"); - int ch = istr.get(); - assert (ch == '\r'); - ch = istr.get(); - assert (ch == '\n'); - ch = istr.get(); - assert (ch == 's'); -} - - -void MessageHeaderTest::testReadFolding1() -{ - std::string s("name1: value1\r\nname2: value21\r\n value22\r\nname3: value3\r\n"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 3); - assert (mh["name1"] == "value1"); - assert (mh["name2"] == "value21 value22"); - assert (mh["name3"] == "value3"); -} - - -void MessageHeaderTest::testReadFolding2() -{ - std::string s("name1: value1\nname2: value21\n\tvalue22\nname3: value3\n"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 3); - assert (mh["name1"] == "value1"); - assert (mh["name2"] == "value21\tvalue22"); - assert (mh["name3"] == "value3"); -} - - -void MessageHeaderTest::testReadFolding3() -{ - std::string s("name1: value1\r\nname2: value21\r\n value22\r\n"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 2); - assert (mh["name1"] == "value1"); - assert (mh["name2"] == "value21 value22"); -} - - -void MessageHeaderTest::testReadFolding4() -{ - std::string s("name1: value1\r\nname2: value21\r\n value22\r\n value23"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 2); - assert (mh["name1"] == "value1"); - assert (mh["name2"] == "value21 value22 value23"); -} - - -void MessageHeaderTest::testReadFolding5() -{ - std::string s("name1: value1\r\nname2: value21\r\n value22\r\n value23\r\nname3: value3"); - std::istringstream istr(s); - MessageHeader mh; - mh.read(istr); - assert (mh.size() == 3); - assert (mh["name1"] == "value1"); - assert (mh["name2"] == "value21 value22 value23"); - assert (mh["name3"] == "value3"); -} - - -void MessageHeaderTest::testReadInvalid1() -{ - std::string s("name1: value1\r\nname2: value21\r\n value22\r\n value23\r\n"); - s.append(300, 'x'); - std::istringstream istr(s); - MessageHeader mh; - try - { - mh.read(istr); - fail("malformed message - must throw"); - } - catch (MessageException&) - { - } -} - - -void MessageHeaderTest::testReadInvalid2() -{ - std::string s("name1: value1\r\nname2: "); - s.append(8000, 'x'); - std::istringstream istr(s); - MessageHeader mh; - try - { - mh.read(istr); - fail("malformed message - must throw"); - } - catch (MessageException&) - { - } -} - - -void MessageHeaderTest::testSplitElements() -{ - std::string s; - std::vector v; - MessageHeader::splitElements(s, v); - assert (v.empty()); - - s = "foo"; - MessageHeader::splitElements(s, v); - assert (v.size() == 1); - assert (v[0] == "foo"); - - s = " foo "; - MessageHeader::splitElements(s, v); - assert (v.size() == 1); - assert (v[0] == "foo"); - - s = "foo,bar"; - MessageHeader::splitElements(s, v); - assert (v.size() == 2); - assert (v[0] == "foo"); - assert (v[1] == "bar"); - - s = "foo,,bar"; - MessageHeader::splitElements(s, v); - assert (v.size() == 2); - assert (v[0] == "foo"); - assert (v[1] == "bar"); - - MessageHeader::splitElements(s, v, false); - assert (v.size() == 3); - assert (v[0] == "foo"); - assert (v[1] == ""); - assert (v[2] == "bar"); - - s = "foo;param=\"a,b\",bar;param=\"c,d\""; - MessageHeader::splitElements(s, v); - assert (v.size() == 2); - assert (v[0] == "foo;param=\"a,b\""); - assert (v[1] == "bar;param=\"c,d\""); - - s = "foo; param=\"a,b\", bar; param=\"c,d\""; - MessageHeader::splitElements(s, v); - assert (v.size() == 2); - assert (v[0] == "foo; param=\"a,b\""); - assert (v[1] == "bar; param=\"c,d\""); - - s = "foo, bar, f00, baz"; - MessageHeader::splitElements(s, v); - assert (v.size() == 4); - assert (v[0] == "foo"); - assert (v[1] == "bar"); - assert (v[2] == "f00"); - assert (v[3] == "baz"); - - s = "a,b,c"; - MessageHeader::splitElements(s, v); - assert (v.size() == 3); - assert (v[0] == "a"); - assert (v[1] == "b"); - assert (v[2] == "c"); - - s = "a=\"value=\\\\\\\"foo, bar\\\\\\\"\",b=foo"; - MessageHeader::splitElements(s, v); - assert (v.size() == 2); - assert (v[0] == "a=\"value=\\\"foo, bar\\\"\""); - assert (v[1] == "b=foo"); - - s = "a=\\\",b=\\\""; - MessageHeader::splitElements(s, v); - assert (v.size() == 2); - assert (v[0] == "a=\""); - assert (v[1] == "b=\""); - -} - - -void MessageHeaderTest::testSplitParameters() -{ - std::string s; - std::string v; - NameValueCollection p; - - MessageHeader::splitParameters(s, v, p); - assert (v.empty()); - assert (p.empty()); - - s = "multipart/related"; - MessageHeader::splitParameters(s, v, p); - assert (v == "multipart/related"); - assert (p.empty()); - - s = "multipart/related; boundary=MIME_boundary_01234567"; - MessageHeader::splitParameters(s, v, p); - assert (v == "multipart/related"); - assert (p.size() == 1); - assert (p["boundary"] == "MIME_boundary_01234567"); - - s = "multipart/related; boundary=\"MIME_boundary_76543210\""; - MessageHeader::splitParameters(s, v, p); - assert (v == "multipart/related"); - assert (p.size() == 1); - assert (p["boundary"] == "MIME_boundary_76543210"); - - s = "text/plain; charset=us-ascii"; - MessageHeader::splitParameters(s, v, p); - assert (v == "text/plain"); - assert (p.size() == 1); - assert (p["charset"] == "us-ascii"); - - s = "value; p1=foo; p2=bar"; - MessageHeader::splitParameters(s, v, p); - assert (v == "value"); - assert (p.size() == 2); - assert (p["p1"] == "foo"); - assert (p["p2"] == "bar"); - - s = "value; p1=\"foo; bar\""; - MessageHeader::splitParameters(s, v, p); - assert (v == "value"); - assert (p.size() == 1); - assert (p["p1"] == "foo; bar"); - - s = "value ; p1=foo ; p2=bar "; - MessageHeader::splitParameters(s, v, p); - assert (v == "value"); - assert (p.size() == 2); - assert (p["p1"] == "foo"); - assert (p["p2"] == "bar"); -} - - -void MessageHeaderTest::setUp() -{ -} - - -void MessageHeaderTest::tearDown() -{ -} - - -CppUnit::Test* MessageHeaderTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MessageHeaderTest"); - - CppUnit_addTest(pSuite, MessageHeaderTest, testWrite); - CppUnit_addTest(pSuite, MessageHeaderTest, testRead1); - CppUnit_addTest(pSuite, MessageHeaderTest, testRead2); - CppUnit_addTest(pSuite, MessageHeaderTest, testRead3); - CppUnit_addTest(pSuite, MessageHeaderTest, testRead4); - CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding1); - CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding2); - CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding3); - CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding4); - CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding5); - CppUnit_addTest(pSuite, MessageHeaderTest, testReadInvalid1); - CppUnit_addTest(pSuite, MessageHeaderTest, testReadInvalid2); - CppUnit_addTest(pSuite, MessageHeaderTest, testSplitElements); - CppUnit_addTest(pSuite, MessageHeaderTest, testSplitParameters); - - return pSuite; -} +// +// MessageHeaderTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MessageHeaderTest.cpp#1 $ +// +// 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 "MessageHeaderTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/MessageHeader.h" +#include "Poco/Net/NetException.h" +#include + + +using Poco::Net::MessageHeader; +using Poco::Net::NameValueCollection; +using Poco::Net::MessageException; + + +MessageHeaderTest::MessageHeaderTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MessageHeaderTest::~MessageHeaderTest() +{ +} + + +void MessageHeaderTest::testWrite() +{ + MessageHeader mh; + mh.set("name1", "value1"); + mh.set("name2", "value2"); + mh.set("name3", "value3"); + + std::ostringstream ostr; + mh.write(ostr); + std::string s = ostr.str(); + assert (s == "name1: value1\r\nname2: value2\r\nname3: value3\r\n"); +} + + +void MessageHeaderTest::testRead1() +{ + std::string s("name1: value1\r\nname2: value2\r\nname3: value3\r\n"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 3); + assert (mh["name1"] == "value1"); + assert (mh["name2"] == "value2"); + assert (mh["name3"] == "value3"); +} + + +void MessageHeaderTest::testRead2() +{ + std::string s("name1: value1\nname2: value2\nname3: value3\n"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 3); + assert (mh["name1"] == "value1"); + assert (mh["name2"] == "value2"); + assert (mh["name3"] == "value3"); +} + + +void MessageHeaderTest::testRead3() +{ + std::string s("name1: value1\r\n"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 1); + assert (mh["name1"] == "value1"); +} + + + +void MessageHeaderTest::testRead4() +{ + std::string s("name1: value1\r\nname2: value2\r\n\r\nsomedata"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 2); + assert (mh["name1"] == "value1"); + assert (mh["name2"] == "value2"); + int ch = istr.get(); + assert (ch == '\r'); + ch = istr.get(); + assert (ch == '\n'); + ch = istr.get(); + assert (ch == 's'); +} + + +void MessageHeaderTest::testReadFolding1() +{ + std::string s("name1: value1\r\nname2: value21\r\n value22\r\nname3: value3\r\n"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 3); + assert (mh["name1"] == "value1"); + assert (mh["name2"] == "value21 value22"); + assert (mh["name3"] == "value3"); +} + + +void MessageHeaderTest::testReadFolding2() +{ + std::string s("name1: value1\nname2: value21\n\tvalue22\nname3: value3\n"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 3); + assert (mh["name1"] == "value1"); + assert (mh["name2"] == "value21\tvalue22"); + assert (mh["name3"] == "value3"); +} + + +void MessageHeaderTest::testReadFolding3() +{ + std::string s("name1: value1\r\nname2: value21\r\n value22\r\n"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 2); + assert (mh["name1"] == "value1"); + assert (mh["name2"] == "value21 value22"); +} + + +void MessageHeaderTest::testReadFolding4() +{ + std::string s("name1: value1\r\nname2: value21\r\n value22\r\n value23"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 2); + assert (mh["name1"] == "value1"); + assert (mh["name2"] == "value21 value22 value23"); +} + + +void MessageHeaderTest::testReadFolding5() +{ + std::string s("name1: value1\r\nname2: value21\r\n value22\r\n value23\r\nname3: value3"); + std::istringstream istr(s); + MessageHeader mh; + mh.read(istr); + assert (mh.size() == 3); + assert (mh["name1"] == "value1"); + assert (mh["name2"] == "value21 value22 value23"); + assert (mh["name3"] == "value3"); +} + + +void MessageHeaderTest::testReadInvalid1() +{ + std::string s("name1: value1\r\nname2: value21\r\n value22\r\n value23\r\n"); + s.append(300, 'x'); + std::istringstream istr(s); + MessageHeader mh; + try + { + mh.read(istr); + fail("malformed message - must throw"); + } + catch (MessageException&) + { + } +} + + +void MessageHeaderTest::testReadInvalid2() +{ + std::string s("name1: value1\r\nname2: "); + s.append(8000, 'x'); + std::istringstream istr(s); + MessageHeader mh; + try + { + mh.read(istr); + fail("malformed message - must throw"); + } + catch (MessageException&) + { + } +} + + +void MessageHeaderTest::testSplitElements() +{ + std::string s; + std::vector v; + MessageHeader::splitElements(s, v); + assert (v.empty()); + + s = "foo"; + MessageHeader::splitElements(s, v); + assert (v.size() == 1); + assert (v[0] == "foo"); + + s = " foo "; + MessageHeader::splitElements(s, v); + assert (v.size() == 1); + assert (v[0] == "foo"); + + s = "foo,bar"; + MessageHeader::splitElements(s, v); + assert (v.size() == 2); + assert (v[0] == "foo"); + assert (v[1] == "bar"); + + s = "foo,,bar"; + MessageHeader::splitElements(s, v); + assert (v.size() == 2); + assert (v[0] == "foo"); + assert (v[1] == "bar"); + + MessageHeader::splitElements(s, v, false); + assert (v.size() == 3); + assert (v[0] == "foo"); + assert (v[1] == ""); + assert (v[2] == "bar"); + + s = "foo;param=\"a,b\",bar;param=\"c,d\""; + MessageHeader::splitElements(s, v); + assert (v.size() == 2); + assert (v[0] == "foo;param=\"a,b\""); + assert (v[1] == "bar;param=\"c,d\""); + + s = "foo; param=\"a,b\", bar; param=\"c,d\""; + MessageHeader::splitElements(s, v); + assert (v.size() == 2); + assert (v[0] == "foo; param=\"a,b\""); + assert (v[1] == "bar; param=\"c,d\""); + + s = "foo, bar, f00, baz"; + MessageHeader::splitElements(s, v); + assert (v.size() == 4); + assert (v[0] == "foo"); + assert (v[1] == "bar"); + assert (v[2] == "f00"); + assert (v[3] == "baz"); + + s = "a,b,c"; + MessageHeader::splitElements(s, v); + assert (v.size() == 3); + assert (v[0] == "a"); + assert (v[1] == "b"); + assert (v[2] == "c"); + + s = "a=\"value=\\\\\\\"foo, bar\\\\\\\"\",b=foo"; + MessageHeader::splitElements(s, v); + assert (v.size() == 2); + assert (v[0] == "a=\"value=\\\"foo, bar\\\"\""); + assert (v[1] == "b=foo"); + + s = "a=\\\",b=\\\""; + MessageHeader::splitElements(s, v); + assert (v.size() == 2); + assert (v[0] == "a=\""); + assert (v[1] == "b=\""); + +} + + +void MessageHeaderTest::testSplitParameters() +{ + std::string s; + std::string v; + NameValueCollection p; + + MessageHeader::splitParameters(s, v, p); + assert (v.empty()); + assert (p.empty()); + + s = "multipart/related"; + MessageHeader::splitParameters(s, v, p); + assert (v == "multipart/related"); + assert (p.empty()); + + s = "multipart/related; boundary=MIME_boundary_01234567"; + MessageHeader::splitParameters(s, v, p); + assert (v == "multipart/related"); + assert (p.size() == 1); + assert (p["boundary"] == "MIME_boundary_01234567"); + + s = "multipart/related; boundary=\"MIME_boundary_76543210\""; + MessageHeader::splitParameters(s, v, p); + assert (v == "multipart/related"); + assert (p.size() == 1); + assert (p["boundary"] == "MIME_boundary_76543210"); + + s = "text/plain; charset=us-ascii"; + MessageHeader::splitParameters(s, v, p); + assert (v == "text/plain"); + assert (p.size() == 1); + assert (p["charset"] == "us-ascii"); + + s = "value; p1=foo; p2=bar"; + MessageHeader::splitParameters(s, v, p); + assert (v == "value"); + assert (p.size() == 2); + assert (p["p1"] == "foo"); + assert (p["p2"] == "bar"); + + s = "value; p1=\"foo; bar\""; + MessageHeader::splitParameters(s, v, p); + assert (v == "value"); + assert (p.size() == 1); + assert (p["p1"] == "foo; bar"); + + s = "value ; p1=foo ; p2=bar "; + MessageHeader::splitParameters(s, v, p); + assert (v == "value"); + assert (p.size() == 2); + assert (p["p1"] == "foo"); + assert (p["p2"] == "bar"); +} + + +void MessageHeaderTest::setUp() +{ +} + + +void MessageHeaderTest::tearDown() +{ +} + + +CppUnit::Test* MessageHeaderTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MessageHeaderTest"); + + CppUnit_addTest(pSuite, MessageHeaderTest, testWrite); + CppUnit_addTest(pSuite, MessageHeaderTest, testRead1); + CppUnit_addTest(pSuite, MessageHeaderTest, testRead2); + CppUnit_addTest(pSuite, MessageHeaderTest, testRead3); + CppUnit_addTest(pSuite, MessageHeaderTest, testRead4); + CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding1); + CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding2); + CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding3); + CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding4); + CppUnit_addTest(pSuite, MessageHeaderTest, testReadFolding5); + CppUnit_addTest(pSuite, MessageHeaderTest, testReadInvalid1); + CppUnit_addTest(pSuite, MessageHeaderTest, testReadInvalid2); + CppUnit_addTest(pSuite, MessageHeaderTest, testSplitElements); + CppUnit_addTest(pSuite, MessageHeaderTest, testSplitParameters); + + return pSuite; +} diff --git a/Net/testsuite/src/MessageHeaderTest.h b/Net/testsuite/src/MessageHeaderTest.h index db5319b16..f26b7926a 100644 --- a/Net/testsuite/src/MessageHeaderTest.h +++ b/Net/testsuite/src/MessageHeaderTest.h @@ -1,73 +1,73 @@ -// -// MessageHeaderTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/MessageHeaderTest.h#1 $ -// -// Definition of the MessageHeaderTest 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 MessageHeaderTest_INCLUDED -#define MessageHeaderTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class MessageHeaderTest: public CppUnit::TestCase -{ -public: - MessageHeaderTest(const std::string& name); - ~MessageHeaderTest(); - - void testWrite(); - void testRead1(); - void testRead2(); - void testRead3(); - void testRead4(); - void testReadFolding1(); - void testReadFolding2(); - void testReadFolding3(); - void testReadFolding4(); - void testReadFolding5(); - void testReadInvalid1(); - void testReadInvalid2(); - void testSplitElements(); - void testSplitParameters(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MessageHeaderTest_INCLUDED +// +// MessageHeaderTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/MessageHeaderTest.h#1 $ +// +// Definition of the MessageHeaderTest 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 MessageHeaderTest_INCLUDED +#define MessageHeaderTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class MessageHeaderTest: public CppUnit::TestCase +{ +public: + MessageHeaderTest(const std::string& name); + ~MessageHeaderTest(); + + void testWrite(); + void testRead1(); + void testRead2(); + void testRead3(); + void testRead4(); + void testReadFolding1(); + void testReadFolding2(); + void testReadFolding3(); + void testReadFolding4(); + void testReadFolding5(); + void testReadInvalid1(); + void testReadInvalid2(); + void testSplitElements(); + void testSplitParameters(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MessageHeaderTest_INCLUDED diff --git a/Net/testsuite/src/MessagesTestSuite.cpp b/Net/testsuite/src/MessagesTestSuite.cpp index 28b765e62..7d7f4798a 100644 --- a/Net/testsuite/src/MessagesTestSuite.cpp +++ b/Net/testsuite/src/MessagesTestSuite.cpp @@ -1,54 +1,54 @@ -// -// MessagesTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MessagesTestSuite.cpp#1 $ -// -// 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 "MessagesTestSuite.h" -#include "NameValueCollectionTest.h" -#include "MessageHeaderTest.h" -#include "MediaTypeTest.h" -#include "MultipartWriterTest.h" -#include "MultipartReaderTest.h" -#include "QuotedPrintableTest.h" - - -CppUnit::Test* MessagesTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MessagesTestSuite"); - - pSuite->addTest(NameValueCollectionTest::suite()); - pSuite->addTest(MessageHeaderTest::suite()); - pSuite->addTest(MediaTypeTest::suite()); - pSuite->addTest(MultipartWriterTest::suite()); - pSuite->addTest(MultipartReaderTest::suite()); - pSuite->addTest(QuotedPrintableTest::suite()); - - return pSuite; -} +// +// MessagesTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MessagesTestSuite.cpp#1 $ +// +// 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 "MessagesTestSuite.h" +#include "NameValueCollectionTest.h" +#include "MessageHeaderTest.h" +#include "MediaTypeTest.h" +#include "MultipartWriterTest.h" +#include "MultipartReaderTest.h" +#include "QuotedPrintableTest.h" + + +CppUnit::Test* MessagesTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MessagesTestSuite"); + + pSuite->addTest(NameValueCollectionTest::suite()); + pSuite->addTest(MessageHeaderTest::suite()); + pSuite->addTest(MediaTypeTest::suite()); + pSuite->addTest(MultipartWriterTest::suite()); + pSuite->addTest(MultipartReaderTest::suite()); + pSuite->addTest(QuotedPrintableTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/MessagesTestSuite.h b/Net/testsuite/src/MessagesTestSuite.h index d8c4bf31a..5f1c4743a 100644 --- a/Net/testsuite/src/MessagesTestSuite.h +++ b/Net/testsuite/src/MessagesTestSuite.h @@ -1,49 +1,49 @@ -// -// MessagesTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/MessagesTestSuite.h#1 $ -// -// Definition of the MessagesTestSuite 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 MessagesTestSuite_INCLUDED -#define MessagesTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class MessagesTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // MessagesTestSuite_INCLUDED +// +// MessagesTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/MessagesTestSuite.h#1 $ +// +// Definition of the MessagesTestSuite 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 MessagesTestSuite_INCLUDED +#define MessagesTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class MessagesTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // MessagesTestSuite_INCLUDED diff --git a/Net/testsuite/src/MulticastEchoServer.cpp b/Net/testsuite/src/MulticastEchoServer.cpp index f175c5124..a751e3426 100644 --- a/Net/testsuite/src/MulticastEchoServer.cpp +++ b/Net/testsuite/src/MulticastEchoServer.cpp @@ -1,117 +1,117 @@ -// -// MulticastEchoServer.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MulticastEchoServer.cpp#1 $ -// -// 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 "MulticastEchoServer.h" -#include "Poco/Timespan.h" -#include - - -using Poco::Net::Socket; -using Poco::Net::DatagramSocket; -using Poco::Net::SocketAddress; -using Poco::Net::IPAddress; -using Poco::Net::NetworkInterface; - - -MulticastEchoServer::MulticastEchoServer(): - _group("239.255.1.2", 12345), - _if(findInterface()), - _thread("MulticastEchoServer"), - _stop(false) -{ - _socket.bind(SocketAddress(IPAddress(), _group.port()), true); - _socket.joinGroup(_group.host(), _if); - _thread.start(*this); - _ready.wait(); -} - - -MulticastEchoServer::~MulticastEchoServer() -{ - _stop = true; - _thread.join(); - _socket.leaveGroup(_group.host(), _if); -} - - -Poco::UInt16 MulticastEchoServer::port() const -{ - return _socket.address().port(); -} - - -void MulticastEchoServer::run() -{ - _ready.set(); - Poco::Timespan span(250000); - while (!_stop) - { - if (_socket.poll(span, Socket::SELECT_READ)) - { - try - { - char buffer[256]; - SocketAddress sender; - int n = _socket.receiveFrom(buffer, sizeof(buffer), sender); - _socket.sendTo(buffer, n, sender); - } - catch (Poco::Exception& exc) - { - std::cerr << "MulticastEchoServer: " << exc.displayText() << std::endl; - } - } - } -} - - -const SocketAddress& MulticastEchoServer::group() const -{ - return _group; -} - - -const NetworkInterface& MulticastEchoServer::interface() const -{ - return _if; -} - - -Poco::Net::NetworkInterface MulticastEchoServer::findInterface() -{ - NetworkInterface::NetworkInterfaceList ifs = NetworkInterface::list(); - for (NetworkInterface::NetworkInterfaceList::const_iterator it = ifs.begin(); it != ifs.end(); ++it) - { - if (it->supportsIPv4() && it->address().isUnicast() && !it->address().isLoopback()) - return *it; - } - return NetworkInterface(); -} +// +// MulticastEchoServer.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MulticastEchoServer.cpp#1 $ +// +// 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 "MulticastEchoServer.h" +#include "Poco/Timespan.h" +#include + + +using Poco::Net::Socket; +using Poco::Net::DatagramSocket; +using Poco::Net::SocketAddress; +using Poco::Net::IPAddress; +using Poco::Net::NetworkInterface; + + +MulticastEchoServer::MulticastEchoServer(): + _group("239.255.1.2", 12345), + _if(findInterface()), + _thread("MulticastEchoServer"), + _stop(false) +{ + _socket.bind(SocketAddress(IPAddress(), _group.port()), true); + _socket.joinGroup(_group.host(), _if); + _thread.start(*this); + _ready.wait(); +} + + +MulticastEchoServer::~MulticastEchoServer() +{ + _stop = true; + _thread.join(); + _socket.leaveGroup(_group.host(), _if); +} + + +Poco::UInt16 MulticastEchoServer::port() const +{ + return _socket.address().port(); +} + + +void MulticastEchoServer::run() +{ + _ready.set(); + Poco::Timespan span(250000); + while (!_stop) + { + if (_socket.poll(span, Socket::SELECT_READ)) + { + try + { + char buffer[256]; + SocketAddress sender; + int n = _socket.receiveFrom(buffer, sizeof(buffer), sender); + _socket.sendTo(buffer, n, sender); + } + catch (Poco::Exception& exc) + { + std::cerr << "MulticastEchoServer: " << exc.displayText() << std::endl; + } + } + } +} + + +const SocketAddress& MulticastEchoServer::group() const +{ + return _group; +} + + +const NetworkInterface& MulticastEchoServer::interface() const +{ + return _if; +} + + +Poco::Net::NetworkInterface MulticastEchoServer::findInterface() +{ + NetworkInterface::NetworkInterfaceList ifs = NetworkInterface::list(); + for (NetworkInterface::NetworkInterfaceList::const_iterator it = ifs.begin(); it != ifs.end(); ++it) + { + if (it->supportsIPv4() && it->address().isUnicast() && !it->address().isLoopback()) + return *it; + } + return NetworkInterface(); +} diff --git a/Net/testsuite/src/MulticastEchoServer.h b/Net/testsuite/src/MulticastEchoServer.h index 8e180bd1d..acf888cb9 100644 --- a/Net/testsuite/src/MulticastEchoServer.h +++ b/Net/testsuite/src/MulticastEchoServer.h @@ -1,85 +1,85 @@ -// -// MulticastEchoServer.h -// -// $Id: //poco/1.2/Net/testsuite/src/MulticastEchoServer.h#1 $ -// -// Definition of the MulticastEchoServer 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 MulticastEchoServer_INCLUDED -#define MulticastEchoServer_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/MulticastSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetworkInterface.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" - - -class MulticastEchoServer: public Poco::Runnable - /// A simple sequential Multicast echo server. -{ -public: - MulticastEchoServer(); - /// Creates the MulticastEchoServer. - - ~MulticastEchoServer(); - /// Destroys the MulticastEchoServer. - - Poco::UInt16 port() const; - /// Returns the port the echo server is - /// listening on. - - void run(); - /// Does the work. - - const Poco::Net::SocketAddress& group() const; - /// Returns the group address where the server listens. - - const Poco::Net::NetworkInterface& interface() const; - /// Returns the network interface for multicasting. - -protected: - static Poco::Net::NetworkInterface findInterface(); - /// Finds an appropriate network interface for - /// multicasting. - -private: - Poco::Net::MulticastSocket _socket; - Poco::Net::SocketAddress _group; - Poco::Net::NetworkInterface _if; - Poco::Thread _thread; - Poco::Event _ready; - bool _stop; -}; - - -#endif // MulticastEchoServer_INCLUDED +// +// MulticastEchoServer.h +// +// $Id: //poco/1.2/Net/testsuite/src/MulticastEchoServer.h#1 $ +// +// Definition of the MulticastEchoServer 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 MulticastEchoServer_INCLUDED +#define MulticastEchoServer_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/MulticastSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetworkInterface.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" + + +class MulticastEchoServer: public Poco::Runnable + /// A simple sequential Multicast echo server. +{ +public: + MulticastEchoServer(); + /// Creates the MulticastEchoServer. + + ~MulticastEchoServer(); + /// Destroys the MulticastEchoServer. + + Poco::UInt16 port() const; + /// Returns the port the echo server is + /// listening on. + + void run(); + /// Does the work. + + const Poco::Net::SocketAddress& group() const; + /// Returns the group address where the server listens. + + const Poco::Net::NetworkInterface& interface() const; + /// Returns the network interface for multicasting. + +protected: + static Poco::Net::NetworkInterface findInterface(); + /// Finds an appropriate network interface for + /// multicasting. + +private: + Poco::Net::MulticastSocket _socket; + Poco::Net::SocketAddress _group; + Poco::Net::NetworkInterface _if; + Poco::Thread _thread; + Poco::Event _ready; + bool _stop; +}; + + +#endif // MulticastEchoServer_INCLUDED diff --git a/Net/testsuite/src/MulticastSocketTest.cpp b/Net/testsuite/src/MulticastSocketTest.cpp index 45bf84ff4..a27c6d78f 100644 --- a/Net/testsuite/src/MulticastSocketTest.cpp +++ b/Net/testsuite/src/MulticastSocketTest.cpp @@ -1,96 +1,96 @@ -// -// MulticastSocketTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MulticastSocketTest.cpp#1 $ -// -// 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 "MulticastSocketTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "MulticastEchoServer.h" -#include "Poco/Net/MulticastSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/Timespan.h" -#include "Poco/Stopwatch.h" - - -using Poco::Net::Socket; -using Poco::Net::MulticastSocket; -using Poco::Net::SocketAddress; -using Poco::Net::IPAddress; -using Poco::Timespan; -using Poco::Stopwatch; -using Poco::TimeoutException; -using Poco::InvalidArgumentException; -using Poco::IOException; - - -MulticastSocketTest::MulticastSocketTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MulticastSocketTest::~MulticastSocketTest() -{ -} - - -void MulticastSocketTest::testMulticast() -{ - MulticastEchoServer echoServer; - MulticastSocket ms; - int n = ms.sendTo("hello", 5, echoServer.group()); - assert (n == 5); - char buffer[256]; - n = ms.receiveBytes(buffer, sizeof(buffer)); - assert (n == 5); - assert (std::string(buffer, n) == "hello"); - ms.close(); -} - - -void MulticastSocketTest::setUp() -{ -} - - -void MulticastSocketTest::tearDown() -{ -} - - -CppUnit::Test* MulticastSocketTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MulticastSocketTest"); - - CppUnit_addTest(pSuite, MulticastSocketTest, testMulticast); - - return pSuite; -} +// +// MulticastSocketTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MulticastSocketTest.cpp#1 $ +// +// 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 "MulticastSocketTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "MulticastEchoServer.h" +#include "Poco/Net/MulticastSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/Timespan.h" +#include "Poco/Stopwatch.h" + + +using Poco::Net::Socket; +using Poco::Net::MulticastSocket; +using Poco::Net::SocketAddress; +using Poco::Net::IPAddress; +using Poco::Timespan; +using Poco::Stopwatch; +using Poco::TimeoutException; +using Poco::InvalidArgumentException; +using Poco::IOException; + + +MulticastSocketTest::MulticastSocketTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MulticastSocketTest::~MulticastSocketTest() +{ +} + + +void MulticastSocketTest::testMulticast() +{ + MulticastEchoServer echoServer; + MulticastSocket ms; + int n = ms.sendTo("hello", 5, echoServer.group()); + assert (n == 5); + char buffer[256]; + n = ms.receiveBytes(buffer, sizeof(buffer)); + assert (n == 5); + assert (std::string(buffer, n) == "hello"); + ms.close(); +} + + +void MulticastSocketTest::setUp() +{ +} + + +void MulticastSocketTest::tearDown() +{ +} + + +CppUnit::Test* MulticastSocketTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MulticastSocketTest"); + + CppUnit_addTest(pSuite, MulticastSocketTest, testMulticast); + + return pSuite; +} diff --git a/Net/testsuite/src/MulticastSocketTest.h b/Net/testsuite/src/MulticastSocketTest.h index cdd121692..a49052f7b 100644 --- a/Net/testsuite/src/MulticastSocketTest.h +++ b/Net/testsuite/src/MulticastSocketTest.h @@ -1,60 +1,60 @@ -// -// MulticastSocketTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/MulticastSocketTest.h#1 $ -// -// Definition of the MulticastSocketTest 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 MulticastSocketTest_INCLUDED -#define MulticastSocketTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class MulticastSocketTest: public CppUnit::TestCase -{ -public: - MulticastSocketTest(const std::string& name); - ~MulticastSocketTest(); - - void testMulticast(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MulticastSocketTest_INCLUDED +// +// MulticastSocketTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/MulticastSocketTest.h#1 $ +// +// Definition of the MulticastSocketTest 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 MulticastSocketTest_INCLUDED +#define MulticastSocketTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class MulticastSocketTest: public CppUnit::TestCase +{ +public: + MulticastSocketTest(const std::string& name); + ~MulticastSocketTest(); + + void testMulticast(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MulticastSocketTest_INCLUDED diff --git a/Net/testsuite/src/MultipartReaderTest.cpp b/Net/testsuite/src/MultipartReaderTest.cpp index 09f190ec7..88c421325 100644 --- a/Net/testsuite/src/MultipartReaderTest.cpp +++ b/Net/testsuite/src/MultipartReaderTest.cpp @@ -1,400 +1,400 @@ -// -// MultipartReaderTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MultipartReaderTest.cpp#2 $ -// -// 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 "MultipartReaderTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/MultipartReader.h" -#include "Poco/Net/MessageHeader.h" -#include "Poco/Net/NetException.h" -#include - - -using Poco::Net::MultipartReader; -using Poco::Net::MessageHeader; -using Poco::Net::MultipartException; - - -MultipartReaderTest::MultipartReaderTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MultipartReaderTest::~MultipartReaderTest() -{ -} - - -void MultipartReaderTest::testReadOnePart() -{ - std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); - std::istringstream istr(s); - MultipartReader r(istr, "MIME_boundary_01234567"); - assert (r.boundary() == "MIME_boundary_01234567"); - assert (r.hasNextPart()); - MessageHeader h; - r.nextPart(h); - assert (h.size() == 1); - assert (h["name1"] == "value1"); - std::istream& i = r.stream(); - int ch = i.get(); - std::string part; - while (ch >= 0) - { - part += (char) ch; - ch = i.get(); - } - assert (part == "this is part 1"); - assert (!r.hasNextPart()); - try - { - r.nextPart(h); - fail("no more parts - must throw"); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::testReadTwoParts() -{ - std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567\r\n\r\nthis is part 2\r\n\r\n--MIME_boundary_01234567--\r\n"); - std::istringstream istr(s); - MultipartReader r(istr, "MIME_boundary_01234567"); - assert (r.hasNextPart()); - MessageHeader h; - r.nextPart(h); - assert (h.size() == 1); - assert (h["name1"] == "value1"); - std::istream& i = r.stream(); - int ch = i.get(); - std::string part; - while (ch >= 0) - { - part += (char) ch; - ch = i.get(); - } - assert (part == "this is part 1"); - assert (r.hasNextPart()); - r.nextPart(h); - assert (h.empty()); - std::istream& ii = r.stream(); - part.clear(); - ch = ii.get(); - while (ch >= 0) - { - part += (char) ch; - ch = ii.get(); - } - assert (part == "this is part 2\r\n"); - - try - { - r.nextPart(h); - fail("no more parts - must throw"); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::testReadEmptyLines() -{ - std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is\r\npart 1\r\n\r\n--MIME_boundary_01234567\r\n\r\nthis\r\n\r\nis part 2\r\n\r\n\r\n--MIME_boundary_01234567--\r\n"); - std::istringstream istr(s); - MultipartReader r(istr, "MIME_boundary_01234567"); - assert (r.hasNextPart()); - MessageHeader h; - r.nextPart(h); - assert (h.size() == 1); - assert (h["name1"] == "value1"); - std::istream& i = r.stream(); - int ch = i.get(); - std::string part; - while (ch >= 0) - { - part += (char) ch; - ch = i.get(); - } - assert (part == "this is\r\npart 1\r\n"); - assert (r.hasNextPart()); - r.nextPart(h); - assert (h.empty()); - std::istream& ii = r.stream(); - part.clear(); - ch = ii.get(); - while (ch >= 0) - { - part += (char) ch; - ch = ii.get(); - } - assert (part == "this\r\n\r\nis part 2\r\n\r\n"); - - try - { - r.nextPart(h); - fail("no more parts - must throw"); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::testReadLongPart() -{ - std::string longPart(3000, 'X'); - std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\n"); - s.append(longPart); - s.append("\r\n--MIME_boundary_01234567\r\n\r\nthis is part 2\r\n--MIME_boundary_01234567--\r\n"); - std::istringstream istr(s); - MultipartReader r(istr, "MIME_boundary_01234567"); - assert (r.hasNextPart()); - MessageHeader h; - r.nextPart(h); - assert (h.size() == 1); - assert (h["name1"] == "value1"); - std::istream& i = r.stream(); - int ch = i.get(); - std::string part; - while (ch >= 0) - { - part += (char) ch; - ch = i.get(); - } - assert (part == longPart); - assert (r.hasNextPart()); - r.nextPart(h); - assert (h.empty()); - std::istream& ii = r.stream(); - part.clear(); - ch = ii.get(); - while (ch >= 0) - { - part += (char) ch; - ch = ii.get(); - } - assert (part == "this is part 2"); - - try - { - r.nextPart(h); - fail("no more parts - must throw"); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::testGuessBoundary() -{ - std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); - std::istringstream istr(s); - MultipartReader r(istr); - assert (r.hasNextPart()); - MessageHeader h; - r.nextPart(h); - assert (r.boundary() == "MIME_boundary_01234567"); - assert (h.size() == 1); - assert (h["name1"] == "value1"); - std::istream& i = r.stream(); - int ch = i.get(); - std::string part; - while (ch >= 0) - { - part += (char) ch; - ch = i.get(); - } - assert (part == "this is part 1"); - assert (!r.hasNextPart()); - try - { - r.nextPart(h); - fail("no more parts - must throw"); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::testPreamble() -{ - std::string s("this is the\r\npreamble\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); - std::istringstream istr(s); - MultipartReader r(istr, "MIME_boundary_01234567"); - assert (r.hasNextPart()); - MessageHeader h; - r.nextPart(h); - assert (h.size() == 1); - assert (h["name1"] == "value1"); - std::istream& i = r.stream(); - int ch = i.get(); - std::string part; - while (ch >= 0) - { - part += (char) ch; - ch = i.get(); - } - assert (part == "this is part 1"); - assert (!r.hasNextPart()); - try - { - r.nextPart(h); - fail("no more parts - must throw"); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::testBadBoundary() -{ - std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); - std::istringstream istr(s); - MultipartReader r(istr, "MIME_boundary_7654321"); - assert (r.hasNextPart()); - MessageHeader h; - try - { - r.nextPart(h); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::testRobustness() -{ - std::string s("--MIME_boundary_01234567\rname1: value1\r\n\nthis is part 1\n--MIME_boundary_01234567--"); - std::istringstream istr(s); - MultipartReader r(istr, "MIME_boundary_01234567"); - assert (r.hasNextPart()); - MessageHeader h; - r.nextPart(h); - assert (h.size() == 1); - assert (h["name1"] == "value1"); - std::istream& i = r.stream(); - int ch = i.get(); - std::string part; - while (ch >= 0) - { - part += (char) ch; - ch = i.get(); - } - assert (part == "this is part 1"); - assert (!r.hasNextPart()); - try - { - r.nextPart(h); - fail("no more parts - must throw"); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::testUnixLineEnds() -{ - std::string s("\n--MIME_boundary_01234567\nname1: value1\n\nthis is part 1\n--MIME_boundary_01234567\n\nthis is part 2\n\n--MIME_boundary_01234567--\n"); - std::istringstream istr(s); - MultipartReader r(istr, "MIME_boundary_01234567"); - assert (r.hasNextPart()); - MessageHeader h; - r.nextPart(h); - assert (h.size() == 1); - assert (h["name1"] == "value1"); - std::istream& i = r.stream(); - int ch = i.get(); - std::string part; - while (ch >= 0) - { - part += (char) ch; - ch = i.get(); - } - assert (part == "this is part 1"); - assert (r.hasNextPart()); - r.nextPart(h); - assert (h.empty()); - std::istream& ii = r.stream(); - part.clear(); - ch = ii.get(); - while (ch >= 0) - { - part += (char) ch; - ch = ii.get(); - } - assert (part == "this is part 2\n"); - - try - { - r.nextPart(h); - fail("no more parts - must throw"); - } - catch (MultipartException&) - { - } -} - - -void MultipartReaderTest::setUp() -{ -} - - -void MultipartReaderTest::tearDown() -{ -} - - -CppUnit::Test* MultipartReaderTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MultipartReaderTest"); - - CppUnit_addTest(pSuite, MultipartReaderTest, testReadOnePart); - CppUnit_addTest(pSuite, MultipartReaderTest, testReadTwoParts); - CppUnit_addTest(pSuite, MultipartReaderTest, testReadEmptyLines); - CppUnit_addTest(pSuite, MultipartReaderTest, testReadLongPart); - CppUnit_addTest(pSuite, MultipartReaderTest, testGuessBoundary); - CppUnit_addTest(pSuite, MultipartReaderTest, testPreamble); - CppUnit_addTest(pSuite, MultipartReaderTest, testBadBoundary); - CppUnit_addTest(pSuite, MultipartReaderTest, testRobustness); - CppUnit_addTest(pSuite, MultipartReaderTest, testUnixLineEnds); - - return pSuite; -} +// +// MultipartReaderTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MultipartReaderTest.cpp#2 $ +// +// 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 "MultipartReaderTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/MultipartReader.h" +#include "Poco/Net/MessageHeader.h" +#include "Poco/Net/NetException.h" +#include + + +using Poco::Net::MultipartReader; +using Poco::Net::MessageHeader; +using Poco::Net::MultipartException; + + +MultipartReaderTest::MultipartReaderTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MultipartReaderTest::~MultipartReaderTest() +{ +} + + +void MultipartReaderTest::testReadOnePart() +{ + std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); + std::istringstream istr(s); + MultipartReader r(istr, "MIME_boundary_01234567"); + assert (r.boundary() == "MIME_boundary_01234567"); + assert (r.hasNextPart()); + MessageHeader h; + r.nextPart(h); + assert (h.size() == 1); + assert (h["name1"] == "value1"); + std::istream& i = r.stream(); + int ch = i.get(); + std::string part; + while (ch >= 0) + { + part += (char) ch; + ch = i.get(); + } + assert (part == "this is part 1"); + assert (!r.hasNextPart()); + try + { + r.nextPart(h); + fail("no more parts - must throw"); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::testReadTwoParts() +{ + std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567\r\n\r\nthis is part 2\r\n\r\n--MIME_boundary_01234567--\r\n"); + std::istringstream istr(s); + MultipartReader r(istr, "MIME_boundary_01234567"); + assert (r.hasNextPart()); + MessageHeader h; + r.nextPart(h); + assert (h.size() == 1); + assert (h["name1"] == "value1"); + std::istream& i = r.stream(); + int ch = i.get(); + std::string part; + while (ch >= 0) + { + part += (char) ch; + ch = i.get(); + } + assert (part == "this is part 1"); + assert (r.hasNextPart()); + r.nextPart(h); + assert (h.empty()); + std::istream& ii = r.stream(); + part.clear(); + ch = ii.get(); + while (ch >= 0) + { + part += (char) ch; + ch = ii.get(); + } + assert (part == "this is part 2\r\n"); + + try + { + r.nextPart(h); + fail("no more parts - must throw"); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::testReadEmptyLines() +{ + std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is\r\npart 1\r\n\r\n--MIME_boundary_01234567\r\n\r\nthis\r\n\r\nis part 2\r\n\r\n\r\n--MIME_boundary_01234567--\r\n"); + std::istringstream istr(s); + MultipartReader r(istr, "MIME_boundary_01234567"); + assert (r.hasNextPart()); + MessageHeader h; + r.nextPart(h); + assert (h.size() == 1); + assert (h["name1"] == "value1"); + std::istream& i = r.stream(); + int ch = i.get(); + std::string part; + while (ch >= 0) + { + part += (char) ch; + ch = i.get(); + } + assert (part == "this is\r\npart 1\r\n"); + assert (r.hasNextPart()); + r.nextPart(h); + assert (h.empty()); + std::istream& ii = r.stream(); + part.clear(); + ch = ii.get(); + while (ch >= 0) + { + part += (char) ch; + ch = ii.get(); + } + assert (part == "this\r\n\r\nis part 2\r\n\r\n"); + + try + { + r.nextPart(h); + fail("no more parts - must throw"); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::testReadLongPart() +{ + std::string longPart(3000, 'X'); + std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\n"); + s.append(longPart); + s.append("\r\n--MIME_boundary_01234567\r\n\r\nthis is part 2\r\n--MIME_boundary_01234567--\r\n"); + std::istringstream istr(s); + MultipartReader r(istr, "MIME_boundary_01234567"); + assert (r.hasNextPart()); + MessageHeader h; + r.nextPart(h); + assert (h.size() == 1); + assert (h["name1"] == "value1"); + std::istream& i = r.stream(); + int ch = i.get(); + std::string part; + while (ch >= 0) + { + part += (char) ch; + ch = i.get(); + } + assert (part == longPart); + assert (r.hasNextPart()); + r.nextPart(h); + assert (h.empty()); + std::istream& ii = r.stream(); + part.clear(); + ch = ii.get(); + while (ch >= 0) + { + part += (char) ch; + ch = ii.get(); + } + assert (part == "this is part 2"); + + try + { + r.nextPart(h); + fail("no more parts - must throw"); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::testGuessBoundary() +{ + std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); + std::istringstream istr(s); + MultipartReader r(istr); + assert (r.hasNextPart()); + MessageHeader h; + r.nextPart(h); + assert (r.boundary() == "MIME_boundary_01234567"); + assert (h.size() == 1); + assert (h["name1"] == "value1"); + std::istream& i = r.stream(); + int ch = i.get(); + std::string part; + while (ch >= 0) + { + part += (char) ch; + ch = i.get(); + } + assert (part == "this is part 1"); + assert (!r.hasNextPart()); + try + { + r.nextPart(h); + fail("no more parts - must throw"); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::testPreamble() +{ + std::string s("this is the\r\npreamble\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); + std::istringstream istr(s); + MultipartReader r(istr, "MIME_boundary_01234567"); + assert (r.hasNextPart()); + MessageHeader h; + r.nextPart(h); + assert (h.size() == 1); + assert (h["name1"] == "value1"); + std::istream& i = r.stream(); + int ch = i.get(); + std::string part; + while (ch >= 0) + { + part += (char) ch; + ch = i.get(); + } + assert (part == "this is part 1"); + assert (!r.hasNextPart()); + try + { + r.nextPart(h); + fail("no more parts - must throw"); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::testBadBoundary() +{ + std::string s("\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); + std::istringstream istr(s); + MultipartReader r(istr, "MIME_boundary_7654321"); + assert (r.hasNextPart()); + MessageHeader h; + try + { + r.nextPart(h); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::testRobustness() +{ + std::string s("--MIME_boundary_01234567\rname1: value1\r\n\nthis is part 1\n--MIME_boundary_01234567--"); + std::istringstream istr(s); + MultipartReader r(istr, "MIME_boundary_01234567"); + assert (r.hasNextPart()); + MessageHeader h; + r.nextPart(h); + assert (h.size() == 1); + assert (h["name1"] == "value1"); + std::istream& i = r.stream(); + int ch = i.get(); + std::string part; + while (ch >= 0) + { + part += (char) ch; + ch = i.get(); + } + assert (part == "this is part 1"); + assert (!r.hasNextPart()); + try + { + r.nextPart(h); + fail("no more parts - must throw"); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::testUnixLineEnds() +{ + std::string s("\n--MIME_boundary_01234567\nname1: value1\n\nthis is part 1\n--MIME_boundary_01234567\n\nthis is part 2\n\n--MIME_boundary_01234567--\n"); + std::istringstream istr(s); + MultipartReader r(istr, "MIME_boundary_01234567"); + assert (r.hasNextPart()); + MessageHeader h; + r.nextPart(h); + assert (h.size() == 1); + assert (h["name1"] == "value1"); + std::istream& i = r.stream(); + int ch = i.get(); + std::string part; + while (ch >= 0) + { + part += (char) ch; + ch = i.get(); + } + assert (part == "this is part 1"); + assert (r.hasNextPart()); + r.nextPart(h); + assert (h.empty()); + std::istream& ii = r.stream(); + part.clear(); + ch = ii.get(); + while (ch >= 0) + { + part += (char) ch; + ch = ii.get(); + } + assert (part == "this is part 2\n"); + + try + { + r.nextPart(h); + fail("no more parts - must throw"); + } + catch (MultipartException&) + { + } +} + + +void MultipartReaderTest::setUp() +{ +} + + +void MultipartReaderTest::tearDown() +{ +} + + +CppUnit::Test* MultipartReaderTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MultipartReaderTest"); + + CppUnit_addTest(pSuite, MultipartReaderTest, testReadOnePart); + CppUnit_addTest(pSuite, MultipartReaderTest, testReadTwoParts); + CppUnit_addTest(pSuite, MultipartReaderTest, testReadEmptyLines); + CppUnit_addTest(pSuite, MultipartReaderTest, testReadLongPart); + CppUnit_addTest(pSuite, MultipartReaderTest, testGuessBoundary); + CppUnit_addTest(pSuite, MultipartReaderTest, testPreamble); + CppUnit_addTest(pSuite, MultipartReaderTest, testBadBoundary); + CppUnit_addTest(pSuite, MultipartReaderTest, testRobustness); + CppUnit_addTest(pSuite, MultipartReaderTest, testUnixLineEnds); + + return pSuite; +} diff --git a/Net/testsuite/src/MultipartReaderTest.h b/Net/testsuite/src/MultipartReaderTest.h index d0e01f5d4..f8a58b40d 100644 --- a/Net/testsuite/src/MultipartReaderTest.h +++ b/Net/testsuite/src/MultipartReaderTest.h @@ -1,68 +1,68 @@ -// -// MultipartReaderTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/MultipartReaderTest.h#2 $ -// -// Definition of the MultipartReaderTest 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 MultipartReaderTest_INCLUDED -#define MultipartReaderTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class MultipartReaderTest: public CppUnit::TestCase -{ -public: - MultipartReaderTest(const std::string& name); - ~MultipartReaderTest(); - - void testReadOnePart(); - void testReadTwoParts(); - void testReadEmptyLines(); - void testReadLongPart(); - void testGuessBoundary(); - void testPreamble(); - void testBadBoundary(); - void testRobustness(); - void testUnixLineEnds(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MultipartReaderTest_INCLUDED +// +// MultipartReaderTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/MultipartReaderTest.h#2 $ +// +// Definition of the MultipartReaderTest 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 MultipartReaderTest_INCLUDED +#define MultipartReaderTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class MultipartReaderTest: public CppUnit::TestCase +{ +public: + MultipartReaderTest(const std::string& name); + ~MultipartReaderTest(); + + void testReadOnePart(); + void testReadTwoParts(); + void testReadEmptyLines(); + void testReadLongPart(); + void testGuessBoundary(); + void testPreamble(); + void testBadBoundary(); + void testRobustness(); + void testUnixLineEnds(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MultipartReaderTest_INCLUDED diff --git a/Net/testsuite/src/MultipartWriterTest.cpp b/Net/testsuite/src/MultipartWriterTest.cpp index f757bd63d..5a0ab068c 100644 --- a/Net/testsuite/src/MultipartWriterTest.cpp +++ b/Net/testsuite/src/MultipartWriterTest.cpp @@ -1,116 +1,116 @@ -// -// MultipartWriterTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/MultipartWriterTest.cpp#1 $ -// -// 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 "MultipartWriterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/MultipartWriter.h" -#include "Poco/Net/MessageHeader.h" -#include - - -using Poco::Net::MultipartWriter; -using Poco::Net::MessageHeader; - - -MultipartWriterTest::MultipartWriterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MultipartWriterTest::~MultipartWriterTest() -{ -} - - -void MultipartWriterTest::testWriteOnePart() -{ - std::ostringstream ostr; - MultipartWriter w(ostr, "MIME_boundary_01234567"); - assert (w.boundary() == "MIME_boundary_01234567"); - MessageHeader h; - h.set("name1", "value1"); - w.nextPart(h); - ostr << "this is part 1"; - w.close(); - std::string s = ostr.str(); - assert (s == "\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); -} - - -void MultipartWriterTest::testWriteTwoParts() -{ - std::ostringstream ostr; - MultipartWriter w(ostr, "MIME_boundary_01234567"); - MessageHeader h; - h.set("name1", "value1"); - w.nextPart(h); - ostr << "this is part 1"; - h.clear(); - w.nextPart(h); - ostr << "this is part 2"; - w.close(); - std::string s = ostr.str(); - assert (s == "\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567\r\n\r\nthis is part 2\r\n--MIME_boundary_01234567--\r\n"); -} - - -void MultipartWriterTest::testBoundary() -{ - std::ostringstream ostr; - MultipartWriter w(ostr); - std::string boundary = w.boundary(); - assert (boundary.substr(0, 14) == "MIME_boundary_"); - assert (boundary.length() == 14 + 16); -} - - -void MultipartWriterTest::setUp() -{ -} - - -void MultipartWriterTest::tearDown() -{ -} - - -CppUnit::Test* MultipartWriterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MultipartWriterTest"); - - CppUnit_addTest(pSuite, MultipartWriterTest, testWriteOnePart); - CppUnit_addTest(pSuite, MultipartWriterTest, testWriteTwoParts); - CppUnit_addTest(pSuite, MultipartWriterTest, testBoundary); - - return pSuite; -} +// +// MultipartWriterTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/MultipartWriterTest.cpp#1 $ +// +// 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 "MultipartWriterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/MultipartWriter.h" +#include "Poco/Net/MessageHeader.h" +#include + + +using Poco::Net::MultipartWriter; +using Poco::Net::MessageHeader; + + +MultipartWriterTest::MultipartWriterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MultipartWriterTest::~MultipartWriterTest() +{ +} + + +void MultipartWriterTest::testWriteOnePart() +{ + std::ostringstream ostr; + MultipartWriter w(ostr, "MIME_boundary_01234567"); + assert (w.boundary() == "MIME_boundary_01234567"); + MessageHeader h; + h.set("name1", "value1"); + w.nextPart(h); + ostr << "this is part 1"; + w.close(); + std::string s = ostr.str(); + assert (s == "\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567--\r\n"); +} + + +void MultipartWriterTest::testWriteTwoParts() +{ + std::ostringstream ostr; + MultipartWriter w(ostr, "MIME_boundary_01234567"); + MessageHeader h; + h.set("name1", "value1"); + w.nextPart(h); + ostr << "this is part 1"; + h.clear(); + w.nextPart(h); + ostr << "this is part 2"; + w.close(); + std::string s = ostr.str(); + assert (s == "\r\n--MIME_boundary_01234567\r\nname1: value1\r\n\r\nthis is part 1\r\n--MIME_boundary_01234567\r\n\r\nthis is part 2\r\n--MIME_boundary_01234567--\r\n"); +} + + +void MultipartWriterTest::testBoundary() +{ + std::ostringstream ostr; + MultipartWriter w(ostr); + std::string boundary = w.boundary(); + assert (boundary.substr(0, 14) == "MIME_boundary_"); + assert (boundary.length() == 14 + 16); +} + + +void MultipartWriterTest::setUp() +{ +} + + +void MultipartWriterTest::tearDown() +{ +} + + +CppUnit::Test* MultipartWriterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MultipartWriterTest"); + + CppUnit_addTest(pSuite, MultipartWriterTest, testWriteOnePart); + CppUnit_addTest(pSuite, MultipartWriterTest, testWriteTwoParts); + CppUnit_addTest(pSuite, MultipartWriterTest, testBoundary); + + return pSuite; +} diff --git a/Net/testsuite/src/MultipartWriterTest.h b/Net/testsuite/src/MultipartWriterTest.h index 2e5c08997..ac631ad29 100644 --- a/Net/testsuite/src/MultipartWriterTest.h +++ b/Net/testsuite/src/MultipartWriterTest.h @@ -1,62 +1,62 @@ -// -// MultipartWriterTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/MultipartWriterTest.h#1 $ -// -// Definition of the MultipartWriterTest 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 MultipartWriterTest_INCLUDED -#define MultipartWriterTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class MultipartWriterTest: public CppUnit::TestCase -{ -public: - MultipartWriterTest(const std::string& name); - ~MultipartWriterTest(); - - void testWriteOnePart(); - void testWriteTwoParts(); - void testBoundary(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MultipartWriterTest_INCLUDED +// +// MultipartWriterTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/MultipartWriterTest.h#1 $ +// +// Definition of the MultipartWriterTest 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 MultipartWriterTest_INCLUDED +#define MultipartWriterTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class MultipartWriterTest: public CppUnit::TestCase +{ +public: + MultipartWriterTest(const std::string& name); + ~MultipartWriterTest(); + + void testWriteOnePart(); + void testWriteTwoParts(); + void testBoundary(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MultipartWriterTest_INCLUDED diff --git a/Net/testsuite/src/NameValueCollectionTest.cpp b/Net/testsuite/src/NameValueCollectionTest.cpp index 90c92e731..fd592b9d9 100644 --- a/Net/testsuite/src/NameValueCollectionTest.cpp +++ b/Net/testsuite/src/NameValueCollectionTest.cpp @@ -1,148 +1,148 @@ -// -// NameValueCollectionTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/NameValueCollectionTest.cpp#1 $ -// -// 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 "NameValueCollectionTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/NameValueCollection.h" -#include "Poco/Exception.h" - - -using Poco::Net::NameValueCollection; -using Poco::NotFoundException; - - -NameValueCollectionTest::NameValueCollectionTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NameValueCollectionTest::~NameValueCollectionTest() -{ -} - - -void NameValueCollectionTest::testNameValueCollection() -{ - NameValueCollection nvc; - - assert (nvc.empty()); - assert (nvc.size() == 0); - - nvc.set("name", "value"); - assert (!nvc.empty()); - assert (nvc["name"] == "value"); - assert (nvc["Name"] == "value"); - - nvc.set("name2", "value2"); - assert (nvc.get("name2") == "value2"); - assert (nvc.get("NAME2") == "value2"); - - assert (nvc.size() == 2); - - try - { - std::string value = nvc.get("name3"); - fail("not found - must throw"); - } - catch (NotFoundException&) - { - } - - try - { - std::string value = nvc["name3"]; - fail("not found - must throw"); - } - catch (NotFoundException&) - { - } - - assert (nvc.get("name", "default") == "value"); - assert (nvc.get("name3", "default") == "default"); - - assert (nvc.has("name")); - assert (nvc.has("name2")); - assert (!nvc.has("name3")); - - nvc.add("name3", "value3"); - assert (nvc.get("name3") == "value3"); - - nvc.add("name3", "value31"); - - NameValueCollection::ConstIterator it = nvc.find("Name3"); - assert (it != nvc.end()); - std::string v1 = it->second; - assert (it->first == "name3"); - ++it; - assert (it != nvc.end()); - std::string v2 = it->second; - assert (it->first == "name3"); - - assert (v1 == "value3" && v2 == "value31" || v1 == "value31" && v2 == "value3"); - - nvc.erase("name3"); - assert (!nvc.has("name3")); - assert (nvc.find("name3") == nvc.end()); - - it = nvc.begin(); - assert (it != nvc.end()); - ++it; - assert (it != nvc.end()); - ++it; - assert (it == nvc.end()); - - nvc.clear(); - assert (nvc.empty()); - - assert (nvc.size() == 0); -} - - -void NameValueCollectionTest::setUp() -{ -} - - -void NameValueCollectionTest::tearDown() -{ -} - - -CppUnit::Test* NameValueCollectionTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NameValueCollectionTest"); - - CppUnit_addTest(pSuite, NameValueCollectionTest, testNameValueCollection); - - return pSuite; -} +// +// NameValueCollectionTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/NameValueCollectionTest.cpp#1 $ +// +// 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 "NameValueCollectionTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/NameValueCollection.h" +#include "Poco/Exception.h" + + +using Poco::Net::NameValueCollection; +using Poco::NotFoundException; + + +NameValueCollectionTest::NameValueCollectionTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NameValueCollectionTest::~NameValueCollectionTest() +{ +} + + +void NameValueCollectionTest::testNameValueCollection() +{ + NameValueCollection nvc; + + assert (nvc.empty()); + assert (nvc.size() == 0); + + nvc.set("name", "value"); + assert (!nvc.empty()); + assert (nvc["name"] == "value"); + assert (nvc["Name"] == "value"); + + nvc.set("name2", "value2"); + assert (nvc.get("name2") == "value2"); + assert (nvc.get("NAME2") == "value2"); + + assert (nvc.size() == 2); + + try + { + std::string value = nvc.get("name3"); + fail("not found - must throw"); + } + catch (NotFoundException&) + { + } + + try + { + std::string value = nvc["name3"]; + fail("not found - must throw"); + } + catch (NotFoundException&) + { + } + + assert (nvc.get("name", "default") == "value"); + assert (nvc.get("name3", "default") == "default"); + + assert (nvc.has("name")); + assert (nvc.has("name2")); + assert (!nvc.has("name3")); + + nvc.add("name3", "value3"); + assert (nvc.get("name3") == "value3"); + + nvc.add("name3", "value31"); + + NameValueCollection::ConstIterator it = nvc.find("Name3"); + assert (it != nvc.end()); + std::string v1 = it->second; + assert (it->first == "name3"); + ++it; + assert (it != nvc.end()); + std::string v2 = it->second; + assert (it->first == "name3"); + + assert (v1 == "value3" && v2 == "value31" || v1 == "value31" && v2 == "value3"); + + nvc.erase("name3"); + assert (!nvc.has("name3")); + assert (nvc.find("name3") == nvc.end()); + + it = nvc.begin(); + assert (it != nvc.end()); + ++it; + assert (it != nvc.end()); + ++it; + assert (it == nvc.end()); + + nvc.clear(); + assert (nvc.empty()); + + assert (nvc.size() == 0); +} + + +void NameValueCollectionTest::setUp() +{ +} + + +void NameValueCollectionTest::tearDown() +{ +} + + +CppUnit::Test* NameValueCollectionTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NameValueCollectionTest"); + + CppUnit_addTest(pSuite, NameValueCollectionTest, testNameValueCollection); + + return pSuite; +} diff --git a/Net/testsuite/src/NameValueCollectionTest.h b/Net/testsuite/src/NameValueCollectionTest.h index 776c588ec..637275c06 100644 --- a/Net/testsuite/src/NameValueCollectionTest.h +++ b/Net/testsuite/src/NameValueCollectionTest.h @@ -1,60 +1,60 @@ -// -// NameValueCollectionTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/NameValueCollectionTest.h#1 $ -// -// Definition of the NameValueCollectionTest 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 NameValueCollectionTest_INCLUDED -#define NameValueCollectionTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class NameValueCollectionTest: public CppUnit::TestCase -{ -public: - NameValueCollectionTest(const std::string& name); - ~NameValueCollectionTest(); - - void testNameValueCollection(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // NameValueCollectionTest_INCLUDED +// +// NameValueCollectionTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/NameValueCollectionTest.h#1 $ +// +// Definition of the NameValueCollectionTest 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 NameValueCollectionTest_INCLUDED +#define NameValueCollectionTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class NameValueCollectionTest: public CppUnit::TestCase +{ +public: + NameValueCollectionTest(const std::string& name); + ~NameValueCollectionTest(); + + void testNameValueCollection(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // NameValueCollectionTest_INCLUDED diff --git a/Net/testsuite/src/NetCoreTestSuite.cpp b/Net/testsuite/src/NetCoreTestSuite.cpp index 3c96e3f13..a224ffccc 100644 --- a/Net/testsuite/src/NetCoreTestSuite.cpp +++ b/Net/testsuite/src/NetCoreTestSuite.cpp @@ -1,48 +1,48 @@ -// -// NetCoreTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/NetCoreTestSuite.cpp#1 $ -// -// 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 "NetCoreTestSuite.h" -#include "IPAddressTest.h" -#include "SocketAddressTest.h" -#include "DNSTest.h" - - -CppUnit::Test* NetCoreTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NetCoreTestSuite"); - - pSuite->addTest(IPAddressTest::suite()); - pSuite->addTest(SocketAddressTest::suite()); - pSuite->addTest(DNSTest::suite()); - - return pSuite; -} +// +// NetCoreTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/NetCoreTestSuite.cpp#1 $ +// +// 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 "NetCoreTestSuite.h" +#include "IPAddressTest.h" +#include "SocketAddressTest.h" +#include "DNSTest.h" + + +CppUnit::Test* NetCoreTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NetCoreTestSuite"); + + pSuite->addTest(IPAddressTest::suite()); + pSuite->addTest(SocketAddressTest::suite()); + pSuite->addTest(DNSTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/NetCoreTestSuite.h b/Net/testsuite/src/NetCoreTestSuite.h index 88a5fb2ad..07aa795c5 100644 --- a/Net/testsuite/src/NetCoreTestSuite.h +++ b/Net/testsuite/src/NetCoreTestSuite.h @@ -1,49 +1,49 @@ -// -// NetCoreTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/NetCoreTestSuite.h#1 $ -// -// Definition of the NetCoreTestSuite 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 NetCoreTestSuite_INCLUDED -#define NetCoreTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class NetCoreTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // NetCoreTestSuite_INCLUDED +// +// NetCoreTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/NetCoreTestSuite.h#1 $ +// +// Definition of the NetCoreTestSuite 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 NetCoreTestSuite_INCLUDED +#define NetCoreTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class NetCoreTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // NetCoreTestSuite_INCLUDED diff --git a/Net/testsuite/src/NetTestSuite.cpp b/Net/testsuite/src/NetTestSuite.cpp index 2d8f1a9f6..c7bd64897 100644 --- a/Net/testsuite/src/NetTestSuite.cpp +++ b/Net/testsuite/src/NetTestSuite.cpp @@ -1,66 +1,66 @@ -// -// NetTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/NetTestSuite.cpp#1 $ -// -// 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 "NetTestSuite.h" -#include "NetCoreTestSuite.h" -#include "SocketsTestSuite.h" -#include "MessagesTestSuite.h" -#include "HTTPTestSuite.h" -#include "HTTPClientTestSuite.h" -#include "TCPServerTestSuite.h" -#include "HTTPServerTestSuite.h" -#include "HTMLTestSuite.h" -#include "ReactorTestSuite.h" -#include "FTPClientTestSuite.h" -#include "MailTestSuite.h" -#include "ICMPClientTestSuite.h" - - -CppUnit::Test* NetTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NetTestSuite"); - - pSuite->addTest(NetCoreTestSuite::suite()); - pSuite->addTest(SocketsTestSuite::suite()); - pSuite->addTest(MessagesTestSuite::suite()); - pSuite->addTest(HTTPTestSuite::suite()); - pSuite->addTest(HTTPClientTestSuite::suite()); - pSuite->addTest(TCPServerTestSuite::suite()); - pSuite->addTest(HTTPServerTestSuite::suite()); - pSuite->addTest(HTMLTestSuite::suite()); - pSuite->addTest(ReactorTestSuite::suite()); - pSuite->addTest(FTPClientTestSuite::suite()); - pSuite->addTest(MailTestSuite::suite()); - pSuite->addTest(ICMPClientTestSuite::suite()); - - return pSuite; -} +// +// NetTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/NetTestSuite.cpp#1 $ +// +// 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 "NetTestSuite.h" +#include "NetCoreTestSuite.h" +#include "SocketsTestSuite.h" +#include "MessagesTestSuite.h" +#include "HTTPTestSuite.h" +#include "HTTPClientTestSuite.h" +#include "TCPServerTestSuite.h" +#include "HTTPServerTestSuite.h" +#include "HTMLTestSuite.h" +#include "ReactorTestSuite.h" +#include "FTPClientTestSuite.h" +#include "MailTestSuite.h" +#include "ICMPClientTestSuite.h" + + +CppUnit::Test* NetTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NetTestSuite"); + + pSuite->addTest(NetCoreTestSuite::suite()); + pSuite->addTest(SocketsTestSuite::suite()); + pSuite->addTest(MessagesTestSuite::suite()); + pSuite->addTest(HTTPTestSuite::suite()); + pSuite->addTest(HTTPClientTestSuite::suite()); + pSuite->addTest(TCPServerTestSuite::suite()); + pSuite->addTest(HTTPServerTestSuite::suite()); + pSuite->addTest(HTMLTestSuite::suite()); + pSuite->addTest(ReactorTestSuite::suite()); + pSuite->addTest(FTPClientTestSuite::suite()); + pSuite->addTest(MailTestSuite::suite()); + pSuite->addTest(ICMPClientTestSuite::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/NetTestSuite.h b/Net/testsuite/src/NetTestSuite.h index 4fb19ab4e..c6ec58321 100644 --- a/Net/testsuite/src/NetTestSuite.h +++ b/Net/testsuite/src/NetTestSuite.h @@ -1,49 +1,49 @@ -// -// NetTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/NetTestSuite.h#1 $ -// -// Definition of the NetTestSuite 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 NetTestSuite_INCLUDED -#define NetTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class NetTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // NetTestSuite_INCLUDED +// +// NetTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/NetTestSuite.h#1 $ +// +// Definition of the NetTestSuite 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 NetTestSuite_INCLUDED +#define NetTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class NetTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // NetTestSuite_INCLUDED diff --git a/Net/testsuite/src/NetworkInterfaceTest.cpp b/Net/testsuite/src/NetworkInterfaceTest.cpp index 2c1e1b068..a7a243047 100644 --- a/Net/testsuite/src/NetworkInterfaceTest.cpp +++ b/Net/testsuite/src/NetworkInterfaceTest.cpp @@ -1,121 +1,121 @@ -// -// NetworkInterfaceTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/NetworkInterfaceTest.cpp#1 $ -// -// 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 "NetworkInterfaceTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/NetworkInterface.h" -#include - - -using Poco::Net::NetworkInterface; - - -NetworkInterfaceTest::NetworkInterfaceTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NetworkInterfaceTest::~NetworkInterfaceTest() -{ -} - - -void NetworkInterfaceTest::testList() -{ - NetworkInterface::NetworkInterfaceList list = NetworkInterface::list(); - assert (!list.empty()); - for (NetworkInterface::NetworkInterfaceList::const_iterator it = list.begin(); it != list.end(); ++it) - { - std::cout << "Name: " << it->name() << std::endl; - std::cout << "Address: " << it->address().toString() << std::endl; - std::cout << "Index: " << it->index() << std::endl; - } -} - - -void NetworkInterfaceTest::testForName() -{ - NetworkInterface::NetworkInterfaceList list = NetworkInterface::list(); - for (NetworkInterface::NetworkInterfaceList::const_iterator it = list.begin(); it != list.end(); ++it) - { - NetworkInterface ifc = NetworkInterface::forName(it->name()); - assert (ifc.name() == it->name()); - } -} - - -void NetworkInterfaceTest::testForAddress() -{ - NetworkInterface::NetworkInterfaceList list = NetworkInterface::list(); - for (NetworkInterface::NetworkInterfaceList::const_iterator it = list.begin(); it != list.end(); ++it) - { - NetworkInterface ifc = NetworkInterface::forAddress(it->address()); - assert (ifc.address() == it->address()); - } -} - - -void NetworkInterfaceTest::testForIndex() -{ -#if defined(POCO_HAVE_IPv6) - NetworkInterface::NetworkInterfaceList list = NetworkInterface::list(); - for (NetworkInterface::NetworkInterfaceList::const_iterator it = list.begin(); it != list.end(); ++it) - { - NetworkInterface ifc = NetworkInterface::forIndex(it->index()); - assert (ifc.index() == it->index()); - } -#endif -} - - -void NetworkInterfaceTest::setUp() -{ -} - - -void NetworkInterfaceTest::tearDown() -{ -} - - -CppUnit::Test* NetworkInterfaceTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NetworkInterfaceTest"); - - CppUnit_addTest(pSuite, NetworkInterfaceTest, testList); - CppUnit_addTest(pSuite, NetworkInterfaceTest, testForName); - CppUnit_addTest(pSuite, NetworkInterfaceTest, testForAddress); - CppUnit_addTest(pSuite, NetworkInterfaceTest, testForIndex); - - return pSuite; -} +// +// NetworkInterfaceTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/NetworkInterfaceTest.cpp#1 $ +// +// 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 "NetworkInterfaceTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/NetworkInterface.h" +#include + + +using Poco::Net::NetworkInterface; + + +NetworkInterfaceTest::NetworkInterfaceTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NetworkInterfaceTest::~NetworkInterfaceTest() +{ +} + + +void NetworkInterfaceTest::testList() +{ + NetworkInterface::NetworkInterfaceList list = NetworkInterface::list(); + assert (!list.empty()); + for (NetworkInterface::NetworkInterfaceList::const_iterator it = list.begin(); it != list.end(); ++it) + { + std::cout << "Name: " << it->name() << std::endl; + std::cout << "Address: " << it->address().toString() << std::endl; + std::cout << "Index: " << it->index() << std::endl; + } +} + + +void NetworkInterfaceTest::testForName() +{ + NetworkInterface::NetworkInterfaceList list = NetworkInterface::list(); + for (NetworkInterface::NetworkInterfaceList::const_iterator it = list.begin(); it != list.end(); ++it) + { + NetworkInterface ifc = NetworkInterface::forName(it->name()); + assert (ifc.name() == it->name()); + } +} + + +void NetworkInterfaceTest::testForAddress() +{ + NetworkInterface::NetworkInterfaceList list = NetworkInterface::list(); + for (NetworkInterface::NetworkInterfaceList::const_iterator it = list.begin(); it != list.end(); ++it) + { + NetworkInterface ifc = NetworkInterface::forAddress(it->address()); + assert (ifc.address() == it->address()); + } +} + + +void NetworkInterfaceTest::testForIndex() +{ +#if defined(POCO_HAVE_IPv6) + NetworkInterface::NetworkInterfaceList list = NetworkInterface::list(); + for (NetworkInterface::NetworkInterfaceList::const_iterator it = list.begin(); it != list.end(); ++it) + { + NetworkInterface ifc = NetworkInterface::forIndex(it->index()); + assert (ifc.index() == it->index()); + } +#endif +} + + +void NetworkInterfaceTest::setUp() +{ +} + + +void NetworkInterfaceTest::tearDown() +{ +} + + +CppUnit::Test* NetworkInterfaceTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NetworkInterfaceTest"); + + CppUnit_addTest(pSuite, NetworkInterfaceTest, testList); + CppUnit_addTest(pSuite, NetworkInterfaceTest, testForName); + CppUnit_addTest(pSuite, NetworkInterfaceTest, testForAddress); + CppUnit_addTest(pSuite, NetworkInterfaceTest, testForIndex); + + return pSuite; +} diff --git a/Net/testsuite/src/NetworkInterfaceTest.h b/Net/testsuite/src/NetworkInterfaceTest.h index 6d238950c..26d9ad568 100644 --- a/Net/testsuite/src/NetworkInterfaceTest.h +++ b/Net/testsuite/src/NetworkInterfaceTest.h @@ -1,63 +1,63 @@ -// -// NetworkInterfaceTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/NetworkInterfaceTest.h#1 $ -// -// Definition of the NetworkInterfaceTest 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 NetworkInterfaceTest_INCLUDED -#define NetworkInterfaceTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class NetworkInterfaceTest: public CppUnit::TestCase -{ -public: - NetworkInterfaceTest(const std::string& name); - ~NetworkInterfaceTest(); - - void testList(); - void testForName(); - void testForAddress(); - void testForIndex(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // NetworkInterfaceTest_INCLUDED +// +// NetworkInterfaceTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/NetworkInterfaceTest.h#1 $ +// +// Definition of the NetworkInterfaceTest 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 NetworkInterfaceTest_INCLUDED +#define NetworkInterfaceTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class NetworkInterfaceTest: public CppUnit::TestCase +{ +public: + NetworkInterfaceTest(const std::string& name); + ~NetworkInterfaceTest(); + + void testList(); + void testForName(); + void testForAddress(); + void testForIndex(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // NetworkInterfaceTest_INCLUDED diff --git a/Net/testsuite/src/POP3ClientSessionTest.cpp b/Net/testsuite/src/POP3ClientSessionTest.cpp index 574fc7b81..a90d95bc3 100644 --- a/Net/testsuite/src/POP3ClientSessionTest.cpp +++ b/Net/testsuite/src/POP3ClientSessionTest.cpp @@ -1,318 +1,318 @@ -// -// POP3ClientSessionTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/POP3ClientSessionTest.cpp#1 $ -// -// 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 "POP3ClientSessionTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "DialogServer.h" -#include "Poco/Net/POP3ClientSession.h" -#include "Poco/Net/MailMessage.h" -#include "Poco/Net/NetException.h" - - -using Poco::Net::POP3ClientSession; -using Poco::Net::MessageHeader; -using Poco::Net::MailMessage; -using Poco::Net::POP3Exception; - - -POP3ClientSessionTest::POP3ClientSessionTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -POP3ClientSessionTest::~POP3ClientSessionTest() -{ -} - - -void POP3ClientSessionTest::testLogin() -{ - DialogServer server; - server.addResponse("+OK POP3 Ready..."); - server.addResponse("+OK USER"); - server.addResponse("+OK PASS"); - server.addResponse("+OK QUIT"); - POP3ClientSession session("localhost", server.port()); - session.login("user", "secret"); - std::string cmd = server.popCommand(); - assert (cmd == "USER user"); - cmd = server.popCommand(); - assert (cmd == "PASS secret"); - session.close(); - cmd = server.popCommand(); - assert (cmd == "QUIT"); -} - - -void POP3ClientSessionTest::testLoginFail() -{ - DialogServer server; - server.addResponse("+OK POP3 Ready..."); - server.addResponse("+OK USER"); - server.addResponse("-ERR PASS"); - server.addResponse("+OK QUIT"); - POP3ClientSession session("localhost", server.port()); - try - { - session.login("user", "secret"); - fail("login failed - must throw"); - } - catch (POP3Exception&) - { - } - session.close(); -} - - -void POP3ClientSessionTest::testMessageCount() -{ - DialogServer server; - server.addResponse("+OK POP3 Ready..."); - server.addResponse("+OK USER"); - server.addResponse("+OK PASS"); - server.addResponse("+OK 42 12345"); - server.addResponse("+OK QUIT"); - POP3ClientSession session("localhost", server.port()); - session.login("user", "secret"); - server.clearCommands(); - int n = session.messageCount(); - std::string cmd = server.popCommand(); - assert (cmd == "STAT"); - assert (n == 42); - session.close(); -} - - -void POP3ClientSessionTest::testList() -{ - DialogServer server; - server.addResponse("+OK POP3 Ready..."); - server.addResponse("+OK USER"); - server.addResponse("+OK PASS"); - server.addResponse( - "+OK Here comes da list\r\n" - "1 1234\r\n" - "2 5678\r\n" - "3 987\r\n" - ".\r\n" - ); - server.addResponse("+OK QUIT"); - POP3ClientSession session("localhost", server.port()); - session.login("user", "secret"); - server.clearCommands(); - std::vector infos; - session.listMessages(infos); - std::string cmd = server.popCommand(); - assert (cmd == "LIST"); - assert (infos.size() == 3); - assert (infos[0].id == 1); - assert (infos[0].size == 1234); - assert (infos[1].id == 2); - assert (infos[1].size == 5678); - assert (infos[2].id == 3); - assert (infos[2].size == 987); - session.close(); -} - - -void POP3ClientSessionTest::testRetrieveMessage() -{ - DialogServer server; - server.addResponse("+OK POP3 Ready..."); - server.addResponse("+OK USER"); - server.addResponse("+OK PASS"); - server.addResponse( - "+OK Here comes the message\r\n" - "From: john.doe@no.where\r\n" - "To: jane.doe@no.where\r\n" - "Subject: test\r\n" - "\r\n" - "Hello Jane,\r\n" - "\r\n" - "blah blah blah...\r\n" - "....\r\n" - "\r\n" - "Yours, John\r\n" - ".\r\n" - ); - server.addResponse("+OK QUIT"); - POP3ClientSession session("localhost", server.port()); - session.login("user", "secret"); - server.clearCommands(); - MailMessage message; - session.retrieveMessage(1, message); - std::string cmd = server.popCommand(); - assert (cmd == "RETR 1"); - - assert (message.getContent() == - "Hello Jane,\r\n" - "\r\n" - "blah blah blah...\r\n" - "...\r\n" - "\r\n" - "Yours, John\r\n" - ); - - session.close(); -} - - -void POP3ClientSessionTest::testRetrieveHeader() -{ - DialogServer server; - server.addResponse("+OK POP3 Ready..."); - server.addResponse("+OK USER"); - server.addResponse("+OK PASS"); - server.addResponse( - "+OK Here comes the message\r\n" - "From: john.doe@no.where\r\n" - "To: jane.doe@no.where\r\n" - "Subject: test\r\n" - "\r\n" - "." - ); - server.addResponse("+OK QUIT"); - POP3ClientSession session("localhost", server.port()); - session.login("user", "secret"); - server.clearCommands(); - MessageHeader header; - session.retrieveHeader(1, header); - std::string cmd = server.popCommand(); - assert (cmd == "TOP 1 0"); - assert (header.get("From") == "john.doe@no.where"); - assert (header.get("To") == "jane.doe@no.where"); - assert (header.get("Subject") == "test"); - session.close(); -} - - -void POP3ClientSessionTest::testRetrieveMessages() -{ - DialogServer server; - server.addResponse("+OK POP3 Ready..."); - server.addResponse("+OK USER"); - server.addResponse("+OK PASS"); - server.addResponse( - "+OK Here comes the message\r\n" - "From: john.doe@no.where\r\n" - "To: jane.doe@no.where\r\n" - "Subject: test\r\n" - "\r\n" - "." - ); - server.addResponse( - "+OK Here comes the message\r\n" - "From: john.doe@no.where\r\n" - "To: jane.doe@no.where\r\n" - "Subject: test\r\n" - "\r\n" - "Hello Jane,\r\n" - "\r\n" - "blah blah blah...\r\n" - "....\r\n" - "\r\n" - "Yours, John\r\n" - "." - ); - server.addResponse("+OK QUIT"); - POP3ClientSession session("localhost", server.port()); - session.login("user", "secret"); - server.clearCommands(); - MessageHeader header; - session.retrieveHeader(1, header); - std::string cmd = server.popCommand(); - assert (cmd == "TOP 1 0"); - assert (header.get("From") == "john.doe@no.where"); - assert (header.get("To") == "jane.doe@no.where"); - assert (header.get("Subject") == "test"); - - MailMessage message; - session.retrieveMessage(2, message); - cmd = server.popCommand(); - assert (cmd == "RETR 2"); - - assert (message.getContent() == - "Hello Jane,\r\n" - "\r\n" - "blah blah blah...\r\n" - "...\r\n" - "\r\n" - "Yours, John\r\n" - ); - session.close(); -} - - -void POP3ClientSessionTest::testDeleteMessage() -{ - DialogServer server; - server.addResponse("+OK POP3 Ready..."); - server.addResponse("+OK USER"); - server.addResponse("+OK PASS"); - server.addResponse("+OK DELETED"); - server.addResponse("+OK QUIT"); - POP3ClientSession session("localhost", server.port()); - session.login("user", "secret"); - server.clearCommands(); - session.deleteMessage(42); - std::string cmd = server.popCommand(); - assert (cmd == "DELE 42"); - session.close(); -} - - -void POP3ClientSessionTest::setUp() -{ -} - - -void POP3ClientSessionTest::tearDown() -{ -} - - -CppUnit::Test* POP3ClientSessionTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("POP3ClientSessionTest"); - - CppUnit_addTest(pSuite, POP3ClientSessionTest, testLogin); - CppUnit_addTest(pSuite, POP3ClientSessionTest, testLoginFail); - CppUnit_addTest(pSuite, POP3ClientSessionTest, testMessageCount); - CppUnit_addTest(pSuite, POP3ClientSessionTest, testList); - CppUnit_addTest(pSuite, POP3ClientSessionTest, testRetrieveMessage); - CppUnit_addTest(pSuite, POP3ClientSessionTest, testRetrieveHeader); - CppUnit_addTest(pSuite, POP3ClientSessionTest, testRetrieveMessages); - CppUnit_addTest(pSuite, POP3ClientSessionTest, testDeleteMessage); - - return pSuite; -} +// +// POP3ClientSessionTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/POP3ClientSessionTest.cpp#1 $ +// +// 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 "POP3ClientSessionTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "DialogServer.h" +#include "Poco/Net/POP3ClientSession.h" +#include "Poco/Net/MailMessage.h" +#include "Poco/Net/NetException.h" + + +using Poco::Net::POP3ClientSession; +using Poco::Net::MessageHeader; +using Poco::Net::MailMessage; +using Poco::Net::POP3Exception; + + +POP3ClientSessionTest::POP3ClientSessionTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +POP3ClientSessionTest::~POP3ClientSessionTest() +{ +} + + +void POP3ClientSessionTest::testLogin() +{ + DialogServer server; + server.addResponse("+OK POP3 Ready..."); + server.addResponse("+OK USER"); + server.addResponse("+OK PASS"); + server.addResponse("+OK QUIT"); + POP3ClientSession session("localhost", server.port()); + session.login("user", "secret"); + std::string cmd = server.popCommand(); + assert (cmd == "USER user"); + cmd = server.popCommand(); + assert (cmd == "PASS secret"); + session.close(); + cmd = server.popCommand(); + assert (cmd == "QUIT"); +} + + +void POP3ClientSessionTest::testLoginFail() +{ + DialogServer server; + server.addResponse("+OK POP3 Ready..."); + server.addResponse("+OK USER"); + server.addResponse("-ERR PASS"); + server.addResponse("+OK QUIT"); + POP3ClientSession session("localhost", server.port()); + try + { + session.login("user", "secret"); + fail("login failed - must throw"); + } + catch (POP3Exception&) + { + } + session.close(); +} + + +void POP3ClientSessionTest::testMessageCount() +{ + DialogServer server; + server.addResponse("+OK POP3 Ready..."); + server.addResponse("+OK USER"); + server.addResponse("+OK PASS"); + server.addResponse("+OK 42 12345"); + server.addResponse("+OK QUIT"); + POP3ClientSession session("localhost", server.port()); + session.login("user", "secret"); + server.clearCommands(); + int n = session.messageCount(); + std::string cmd = server.popCommand(); + assert (cmd == "STAT"); + assert (n == 42); + session.close(); +} + + +void POP3ClientSessionTest::testList() +{ + DialogServer server; + server.addResponse("+OK POP3 Ready..."); + server.addResponse("+OK USER"); + server.addResponse("+OK PASS"); + server.addResponse( + "+OK Here comes da list\r\n" + "1 1234\r\n" + "2 5678\r\n" + "3 987\r\n" + ".\r\n" + ); + server.addResponse("+OK QUIT"); + POP3ClientSession session("localhost", server.port()); + session.login("user", "secret"); + server.clearCommands(); + std::vector infos; + session.listMessages(infos); + std::string cmd = server.popCommand(); + assert (cmd == "LIST"); + assert (infos.size() == 3); + assert (infos[0].id == 1); + assert (infos[0].size == 1234); + assert (infos[1].id == 2); + assert (infos[1].size == 5678); + assert (infos[2].id == 3); + assert (infos[2].size == 987); + session.close(); +} + + +void POP3ClientSessionTest::testRetrieveMessage() +{ + DialogServer server; + server.addResponse("+OK POP3 Ready..."); + server.addResponse("+OK USER"); + server.addResponse("+OK PASS"); + server.addResponse( + "+OK Here comes the message\r\n" + "From: john.doe@no.where\r\n" + "To: jane.doe@no.where\r\n" + "Subject: test\r\n" + "\r\n" + "Hello Jane,\r\n" + "\r\n" + "blah blah blah...\r\n" + "....\r\n" + "\r\n" + "Yours, John\r\n" + ".\r\n" + ); + server.addResponse("+OK QUIT"); + POP3ClientSession session("localhost", server.port()); + session.login("user", "secret"); + server.clearCommands(); + MailMessage message; + session.retrieveMessage(1, message); + std::string cmd = server.popCommand(); + assert (cmd == "RETR 1"); + + assert (message.getContent() == + "Hello Jane,\r\n" + "\r\n" + "blah blah blah...\r\n" + "...\r\n" + "\r\n" + "Yours, John\r\n" + ); + + session.close(); +} + + +void POP3ClientSessionTest::testRetrieveHeader() +{ + DialogServer server; + server.addResponse("+OK POP3 Ready..."); + server.addResponse("+OK USER"); + server.addResponse("+OK PASS"); + server.addResponse( + "+OK Here comes the message\r\n" + "From: john.doe@no.where\r\n" + "To: jane.doe@no.where\r\n" + "Subject: test\r\n" + "\r\n" + "." + ); + server.addResponse("+OK QUIT"); + POP3ClientSession session("localhost", server.port()); + session.login("user", "secret"); + server.clearCommands(); + MessageHeader header; + session.retrieveHeader(1, header); + std::string cmd = server.popCommand(); + assert (cmd == "TOP 1 0"); + assert (header.get("From") == "john.doe@no.where"); + assert (header.get("To") == "jane.doe@no.where"); + assert (header.get("Subject") == "test"); + session.close(); +} + + +void POP3ClientSessionTest::testRetrieveMessages() +{ + DialogServer server; + server.addResponse("+OK POP3 Ready..."); + server.addResponse("+OK USER"); + server.addResponse("+OK PASS"); + server.addResponse( + "+OK Here comes the message\r\n" + "From: john.doe@no.where\r\n" + "To: jane.doe@no.where\r\n" + "Subject: test\r\n" + "\r\n" + "." + ); + server.addResponse( + "+OK Here comes the message\r\n" + "From: john.doe@no.where\r\n" + "To: jane.doe@no.where\r\n" + "Subject: test\r\n" + "\r\n" + "Hello Jane,\r\n" + "\r\n" + "blah blah blah...\r\n" + "....\r\n" + "\r\n" + "Yours, John\r\n" + "." + ); + server.addResponse("+OK QUIT"); + POP3ClientSession session("localhost", server.port()); + session.login("user", "secret"); + server.clearCommands(); + MessageHeader header; + session.retrieveHeader(1, header); + std::string cmd = server.popCommand(); + assert (cmd == "TOP 1 0"); + assert (header.get("From") == "john.doe@no.where"); + assert (header.get("To") == "jane.doe@no.where"); + assert (header.get("Subject") == "test"); + + MailMessage message; + session.retrieveMessage(2, message); + cmd = server.popCommand(); + assert (cmd == "RETR 2"); + + assert (message.getContent() == + "Hello Jane,\r\n" + "\r\n" + "blah blah blah...\r\n" + "...\r\n" + "\r\n" + "Yours, John\r\n" + ); + session.close(); +} + + +void POP3ClientSessionTest::testDeleteMessage() +{ + DialogServer server; + server.addResponse("+OK POP3 Ready..."); + server.addResponse("+OK USER"); + server.addResponse("+OK PASS"); + server.addResponse("+OK DELETED"); + server.addResponse("+OK QUIT"); + POP3ClientSession session("localhost", server.port()); + session.login("user", "secret"); + server.clearCommands(); + session.deleteMessage(42); + std::string cmd = server.popCommand(); + assert (cmd == "DELE 42"); + session.close(); +} + + +void POP3ClientSessionTest::setUp() +{ +} + + +void POP3ClientSessionTest::tearDown() +{ +} + + +CppUnit::Test* POP3ClientSessionTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("POP3ClientSessionTest"); + + CppUnit_addTest(pSuite, POP3ClientSessionTest, testLogin); + CppUnit_addTest(pSuite, POP3ClientSessionTest, testLoginFail); + CppUnit_addTest(pSuite, POP3ClientSessionTest, testMessageCount); + CppUnit_addTest(pSuite, POP3ClientSessionTest, testList); + CppUnit_addTest(pSuite, POP3ClientSessionTest, testRetrieveMessage); + CppUnit_addTest(pSuite, POP3ClientSessionTest, testRetrieveHeader); + CppUnit_addTest(pSuite, POP3ClientSessionTest, testRetrieveMessages); + CppUnit_addTest(pSuite, POP3ClientSessionTest, testDeleteMessage); + + return pSuite; +} diff --git a/Net/testsuite/src/POP3ClientSessionTest.h b/Net/testsuite/src/POP3ClientSessionTest.h index 146abb41d..2693a46d1 100644 --- a/Net/testsuite/src/POP3ClientSessionTest.h +++ b/Net/testsuite/src/POP3ClientSessionTest.h @@ -1,67 +1,67 @@ -// -// POP3ClientSessionTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/POP3ClientSessionTest.h#1 $ -// -// Definition of the POP3ClientSessionTest 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 POP3ClientSessionTest_INCLUDED -#define POP3ClientSessionTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class POP3ClientSessionTest: public CppUnit::TestCase -{ -public: - POP3ClientSessionTest(const std::string& name); - ~POP3ClientSessionTest(); - - void testLogin(); - void testLoginFail(); - void testMessageCount(); - void testList(); - void testRetrieveMessage(); - void testRetrieveHeader(); - void testRetrieveMessages(); - void testDeleteMessage(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // POP3ClientSessionTest_INCLUDED +// +// POP3ClientSessionTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/POP3ClientSessionTest.h#1 $ +// +// Definition of the POP3ClientSessionTest 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 POP3ClientSessionTest_INCLUDED +#define POP3ClientSessionTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class POP3ClientSessionTest: public CppUnit::TestCase +{ +public: + POP3ClientSessionTest(const std::string& name); + ~POP3ClientSessionTest(); + + void testLogin(); + void testLoginFail(); + void testMessageCount(); + void testList(); + void testRetrieveMessage(); + void testRetrieveHeader(); + void testRetrieveMessages(); + void testDeleteMessage(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // POP3ClientSessionTest_INCLUDED diff --git a/Net/testsuite/src/QuotedPrintableTest.cpp b/Net/testsuite/src/QuotedPrintableTest.cpp index 53d9415e4..56c7611d2 100644 --- a/Net/testsuite/src/QuotedPrintableTest.cpp +++ b/Net/testsuite/src/QuotedPrintableTest.cpp @@ -1,122 +1,122 @@ -// -// QuotedPrintableTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/QuotedPrintableTest.cpp#1 $ -// -// 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 "QuotedPrintableTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/QuotedPrintableEncoder.h" -#include "Poco/Net/QuotedPrintableDecoder.h" -#include - - -using Poco::Net::QuotedPrintableEncoder; -using Poco::Net::QuotedPrintableDecoder; - - -QuotedPrintableTest::QuotedPrintableTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -QuotedPrintableTest::~QuotedPrintableTest() -{ -} - - -void QuotedPrintableTest::testEncode() -{ - std::ostringstream ostr; - QuotedPrintableEncoder encoder(ostr); - - encoder << - "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n" - "Proin id odio sit amet metus dignissim porttitor. \r\n" - "Aliquam nulla ipsum, faucibus non, aliquet quis, aliquet id, felis. Proin sodales molestie arcu.\r\n" - "\t\bSed suscipit, mi in facilisis feugiat, \t \r\n" - "\200\201\r\n"; - encoder.close(); - std::string txt = ostr.str(); - assert (txt == "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n" - "Proin id odio sit amet metus dignissim porttitor.=20\r\n" - "Aliquam nulla ipsum, faucibus non, aliquet quis, aliquet id, felis. Proin s=\r\n" - "odales molestie arcu.\r\n" - "\t=08Sed suscipit, mi in facilisis feugiat, \t =20\r\n" - "=80=81\r\n"); -} - - -void QuotedPrintableTest::testDecode() -{ - std::istringstream istr( - "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n" - "Proin id odio sit amet metus dignissim porttitor.=20\r\n" - "Aliquam nulla ipsum, faucibus non, aliquet quis, aliquet id, felis. Proin s=\r\n" - "odales molestie arcu.\r\n" - "\t=08Sed suscipit, mi in facilisis feugiat, \t =20\r\n" - "=80=81\r\n" - ); - QuotedPrintableDecoder decoder(istr); - std::string str; - int c = decoder.get(); - while (c != -1) - { - str += (char) c; - c = decoder.get(); - } - assert (str == "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n" - "Proin id odio sit amet metus dignissim porttitor. \r\n" - "Aliquam nulla ipsum, faucibus non, aliquet quis, aliquet id, felis. Proin sodales molestie arcu.\r\n" - "\t\bSed suscipit, mi in facilisis feugiat, \t \r\n" - "\200\201\r\n"); - -} - - -void QuotedPrintableTest::setUp() -{ -} - - -void QuotedPrintableTest::tearDown() -{ -} - - -CppUnit::Test* QuotedPrintableTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("QuotedPrintableTest"); - - CppUnit_addTest(pSuite, QuotedPrintableTest, testEncode); - CppUnit_addTest(pSuite, QuotedPrintableTest, testDecode); - - return pSuite; -} +// +// QuotedPrintableTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/QuotedPrintableTest.cpp#1 $ +// +// 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 "QuotedPrintableTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/QuotedPrintableEncoder.h" +#include "Poco/Net/QuotedPrintableDecoder.h" +#include + + +using Poco::Net::QuotedPrintableEncoder; +using Poco::Net::QuotedPrintableDecoder; + + +QuotedPrintableTest::QuotedPrintableTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +QuotedPrintableTest::~QuotedPrintableTest() +{ +} + + +void QuotedPrintableTest::testEncode() +{ + std::ostringstream ostr; + QuotedPrintableEncoder encoder(ostr); + + encoder << + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n" + "Proin id odio sit amet metus dignissim porttitor. \r\n" + "Aliquam nulla ipsum, faucibus non, aliquet quis, aliquet id, felis. Proin sodales molestie arcu.\r\n" + "\t\bSed suscipit, mi in facilisis feugiat, \t \r\n" + "\200\201\r\n"; + encoder.close(); + std::string txt = ostr.str(); + assert (txt == "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n" + "Proin id odio sit amet metus dignissim porttitor.=20\r\n" + "Aliquam nulla ipsum, faucibus non, aliquet quis, aliquet id, felis. Proin s=\r\n" + "odales molestie arcu.\r\n" + "\t=08Sed suscipit, mi in facilisis feugiat, \t =20\r\n" + "=80=81\r\n"); +} + + +void QuotedPrintableTest::testDecode() +{ + std::istringstream istr( + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n" + "Proin id odio sit amet metus dignissim porttitor.=20\r\n" + "Aliquam nulla ipsum, faucibus non, aliquet quis, aliquet id, felis. Proin s=\r\n" + "odales molestie arcu.\r\n" + "\t=08Sed suscipit, mi in facilisis feugiat, \t =20\r\n" + "=80=81\r\n" + ); + QuotedPrintableDecoder decoder(istr); + std::string str; + int c = decoder.get(); + while (c != -1) + { + str += (char) c; + c = decoder.get(); + } + assert (str == "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\r\n" + "Proin id odio sit amet metus dignissim porttitor. \r\n" + "Aliquam nulla ipsum, faucibus non, aliquet quis, aliquet id, felis. Proin sodales molestie arcu.\r\n" + "\t\bSed suscipit, mi in facilisis feugiat, \t \r\n" + "\200\201\r\n"); + +} + + +void QuotedPrintableTest::setUp() +{ +} + + +void QuotedPrintableTest::tearDown() +{ +} + + +CppUnit::Test* QuotedPrintableTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("QuotedPrintableTest"); + + CppUnit_addTest(pSuite, QuotedPrintableTest, testEncode); + CppUnit_addTest(pSuite, QuotedPrintableTest, testDecode); + + return pSuite; +} diff --git a/Net/testsuite/src/QuotedPrintableTest.h b/Net/testsuite/src/QuotedPrintableTest.h index d7ce2da41..92594018b 100644 --- a/Net/testsuite/src/QuotedPrintableTest.h +++ b/Net/testsuite/src/QuotedPrintableTest.h @@ -1,61 +1,61 @@ -// -// QuotedPrintableTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/QuotedPrintableTest.h#1 $ -// -// Definition of the QuotedPrintableTest 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 QuotedPrintableTest_INCLUDED -#define QuotedPrintableTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class QuotedPrintableTest: public CppUnit::TestCase -{ -public: - QuotedPrintableTest(const std::string& name); - ~QuotedPrintableTest(); - - void testEncode(); - void testDecode(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // QuotedPrintableTest_INCLUDED +// +// QuotedPrintableTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/QuotedPrintableTest.h#1 $ +// +// Definition of the QuotedPrintableTest 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 QuotedPrintableTest_INCLUDED +#define QuotedPrintableTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class QuotedPrintableTest: public CppUnit::TestCase +{ +public: + QuotedPrintableTest(const std::string& name); + ~QuotedPrintableTest(); + + void testEncode(); + void testDecode(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // QuotedPrintableTest_INCLUDED diff --git a/Net/testsuite/src/RawSocketTest.cpp b/Net/testsuite/src/RawSocketTest.cpp index 7c006776a..96cb2e0c0 100644 --- a/Net/testsuite/src/RawSocketTest.cpp +++ b/Net/testsuite/src/RawSocketTest.cpp @@ -1,127 +1,127 @@ -// -// RawSocketTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/RawSocketTest.cpp#1 $ -// -// 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 "RawSocketTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/RawSocket.h" -#include "Poco/Net/RawSocketImpl.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/Timespan.h" -#include "Poco/Stopwatch.h" - - -using Poco::Net::Socket; -using Poco::Net::RawSocket; -using Poco::Net::RawSocketImpl; -using Poco::Net::SocketAddress; -using Poco::Net::IPAddress; -using Poco::Timespan; -using Poco::Stopwatch; -using Poco::TimeoutException; -using Poco::InvalidArgumentException; -using Poco::IOException; - - -RawSocketTest::RawSocketTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -RawSocketTest::~RawSocketTest() -{ -} - - -void RawSocketTest::testEchoIPv4() -{ - SocketAddress sa("localhost", 0); - RawSocket rs(IPAddress::IPv4); - rs.connect(sa); - - int n = rs.sendBytes("hello", 5); - assert (5 == n); - - char buffer[256] = ""; - unsigned char* ptr = (unsigned char*) buffer; - - n = rs.receiveBytes(buffer, sizeof(buffer)); - int shift = ((buffer[0] & 0x0F) * 4); - ptr += shift; - - assert (5 == (n - shift)); - assert ("hello" == std::string((char*)ptr, 5)); - - rs.close(); -} - - -void RawSocketTest::testSendToReceiveFromIPv4() -{ - RawSocket rs(IPAddress::IPv4); - - int n = rs.sendTo("hello", 5, SocketAddress("localhost", 0)); - assert (n == 5); - - char buffer[256] = ""; - unsigned char* ptr = (unsigned char*) buffer; - SocketAddress sa; - n = rs.receiveFrom(buffer, sizeof(buffer), sa); - int shift = ((buffer[0] & 0x0F) * 4); - ptr += shift; - - assert ((n - shift) == 5); - assert ("hello" == std::string((char*)ptr, 5)); - rs.close(); -} - - -void RawSocketTest::setUp() -{ -} - - -void RawSocketTest::tearDown() -{ -} - - -CppUnit::Test* RawSocketTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RawSocketTest"); - - CppUnit_addTest(pSuite, RawSocketTest, testEchoIPv4); - CppUnit_addTest(pSuite, RawSocketTest, testSendToReceiveFromIPv4); - - return pSuite; -} +// +// RawSocketTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/RawSocketTest.cpp#1 $ +// +// 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 "RawSocketTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/RawSocket.h" +#include "Poco/Net/RawSocketImpl.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/Timespan.h" +#include "Poco/Stopwatch.h" + + +using Poco::Net::Socket; +using Poco::Net::RawSocket; +using Poco::Net::RawSocketImpl; +using Poco::Net::SocketAddress; +using Poco::Net::IPAddress; +using Poco::Timespan; +using Poco::Stopwatch; +using Poco::TimeoutException; +using Poco::InvalidArgumentException; +using Poco::IOException; + + +RawSocketTest::RawSocketTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +RawSocketTest::~RawSocketTest() +{ +} + + +void RawSocketTest::testEchoIPv4() +{ + SocketAddress sa("localhost", 0); + RawSocket rs(IPAddress::IPv4); + rs.connect(sa); + + int n = rs.sendBytes("hello", 5); + assert (5 == n); + + char buffer[256] = ""; + unsigned char* ptr = (unsigned char*) buffer; + + n = rs.receiveBytes(buffer, sizeof(buffer)); + int shift = ((buffer[0] & 0x0F) * 4); + ptr += shift; + + assert (5 == (n - shift)); + assert ("hello" == std::string((char*)ptr, 5)); + + rs.close(); +} + + +void RawSocketTest::testSendToReceiveFromIPv4() +{ + RawSocket rs(IPAddress::IPv4); + + int n = rs.sendTo("hello", 5, SocketAddress("localhost", 0)); + assert (n == 5); + + char buffer[256] = ""; + unsigned char* ptr = (unsigned char*) buffer; + SocketAddress sa; + n = rs.receiveFrom(buffer, sizeof(buffer), sa); + int shift = ((buffer[0] & 0x0F) * 4); + ptr += shift; + + assert ((n - shift) == 5); + assert ("hello" == std::string((char*)ptr, 5)); + rs.close(); +} + + +void RawSocketTest::setUp() +{ +} + + +void RawSocketTest::tearDown() +{ +} + + +CppUnit::Test* RawSocketTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RawSocketTest"); + + CppUnit_addTest(pSuite, RawSocketTest, testEchoIPv4); + CppUnit_addTest(pSuite, RawSocketTest, testSendToReceiveFromIPv4); + + return pSuite; +} diff --git a/Net/testsuite/src/RawSocketTest.h b/Net/testsuite/src/RawSocketTest.h index ad156edd8..26a04ef72 100644 --- a/Net/testsuite/src/RawSocketTest.h +++ b/Net/testsuite/src/RawSocketTest.h @@ -1,61 +1,61 @@ -// -// RawSocketTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/RawSocketTest.h#1 $ -// -// Definition of the RawSocketTest 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 RawSocketTest_INCLUDED -#define RawSocketTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class RawSocketTest: public CppUnit::TestCase -{ -public: - RawSocketTest(const std::string& name); - ~RawSocketTest(); - - void testEchoIPv4(); - void testSendToReceiveFromIPv4(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // RawSocketTest_INCLUDED +// +// RawSocketTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/RawSocketTest.h#1 $ +// +// Definition of the RawSocketTest 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 RawSocketTest_INCLUDED +#define RawSocketTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class RawSocketTest: public CppUnit::TestCase +{ +public: + RawSocketTest(const std::string& name); + ~RawSocketTest(); + + void testEchoIPv4(); + void testSendToReceiveFromIPv4(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // RawSocketTest_INCLUDED diff --git a/Net/testsuite/src/ReactorTestSuite.cpp b/Net/testsuite/src/ReactorTestSuite.cpp index b75416603..232eab1b7 100644 --- a/Net/testsuite/src/ReactorTestSuite.cpp +++ b/Net/testsuite/src/ReactorTestSuite.cpp @@ -1,44 +1,44 @@ -// -// ReactorTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/ReactorTestSuite.cpp#1 $ -// -// 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 "ReactorTestSuite.h" -#include "SocketReactorTest.h" - - -CppUnit::Test* ReactorTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ReactorTestSuite"); - - pSuite->addTest(SocketReactorTest::suite()); - - return pSuite; -} +// +// ReactorTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/ReactorTestSuite.cpp#1 $ +// +// 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 "ReactorTestSuite.h" +#include "SocketReactorTest.h" + + +CppUnit::Test* ReactorTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ReactorTestSuite"); + + pSuite->addTest(SocketReactorTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/ReactorTestSuite.h b/Net/testsuite/src/ReactorTestSuite.h index 1dc6c5659..d2d9d0234 100644 --- a/Net/testsuite/src/ReactorTestSuite.h +++ b/Net/testsuite/src/ReactorTestSuite.h @@ -1,49 +1,49 @@ -// -// ReactorTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/ReactorTestSuite.h#1 $ -// -// Definition of the ReactorTestSuite 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 ReactorTestSuite_INCLUDED -#define ReactorTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class ReactorTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // ReactorTestSuite_INCLUDED +// +// ReactorTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/ReactorTestSuite.h#1 $ +// +// Definition of the ReactorTestSuite 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 ReactorTestSuite_INCLUDED +#define ReactorTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class ReactorTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // ReactorTestSuite_INCLUDED diff --git a/Net/testsuite/src/SMTPClientSessionTest.cpp b/Net/testsuite/src/SMTPClientSessionTest.cpp index 0e2e18ff6..e0da145d4 100644 --- a/Net/testsuite/src/SMTPClientSessionTest.cpp +++ b/Net/testsuite/src/SMTPClientSessionTest.cpp @@ -1,216 +1,216 @@ -// -// SMTPClientSessionTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/SMTPClientSessionTest.cpp#1 $ -// -// 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 "SMTPClientSessionTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "DialogServer.h" -#include "Poco/Net/SMTPClientSession.h" -#include "Poco/Net/MailMessage.h" -#include "Poco/Net/MailRecipient.h" -#include "Poco/Net/NetException.h" - - -using Poco::Net::SMTPClientSession; -using Poco::Net::MailMessage; -using Poco::Net::MailRecipient; -using Poco::Net::SMTPException; - - -SMTPClientSessionTest::SMTPClientSessionTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SMTPClientSessionTest::~SMTPClientSessionTest() -{ -} - - -void SMTPClientSessionTest::testLoginEHLO() -{ - DialogServer server; - server.addResponse("220 localhost SMTP ready"); - server.addResponse("250 Hello localhost"); - server.addResponse("221 Bye"); - SMTPClientSession session("localhost", server.port()); - session.login("localhost"); - std::string cmd = server.popCommand(); - assert (cmd == "EHLO localhost"); - session.close(); - cmd = server.popCommand(); - assert (cmd == "QUIT"); -} - - -void SMTPClientSessionTest::testLoginHELO() -{ - DialogServer server; - server.addResponse("220 localhost SMTP ready"); - server.addResponse("500 EHLO not understood"); - server.addResponse("250 Hello localhost"); - server.addResponse("221 Bye"); - SMTPClientSession session("localhost", server.port()); - session.login("localhost"); - std::string cmd = server.popCommand(); - assert (cmd == "EHLO localhost"); - cmd = server.popCommand(); - assert (cmd == "HELO localhost"); - session.close(); - cmd = server.popCommand(); - assert (cmd == "QUIT"); -} - - -void SMTPClientSessionTest::testLoginFailed() -{ - DialogServer server; - server.addResponse("500 No SMTP service here"); - server.addResponse("221 Bye"); - SMTPClientSession session("localhost", server.port()); - try - { - session.login("localhost"); - fail("cannot login - must throw"); - } - catch (SMTPException&) - { - } - session.close(); -} - - -void SMTPClientSessionTest::testSend() -{ - DialogServer server; - server.addResponse("220 localhost SMTP ready"); - server.addResponse("250 Hello localhost"); - server.addResponse("250 OK"); - server.addResponse("250 OK"); - server.addResponse("354 Send data"); - server.addResponse("250 OK"); - server.addResponse("221 Bye"); - SMTPClientSession session("localhost", server.port()); - session.login("localhost"); - - MailMessage message; - message.setSender("john.doe@no.where"); - message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, "jane.doe@no.where", "Jane Doe")); - message.setSubject("Test Message"); - message.setContent("Hello\r\nblah blah\r\n\r\nJohn\r\n"); - server.clearCommands(); - session.sendMessage(message); - std::string cmd = server.popCommandWait(); - assert (cmd == "MAIL FROM: "); - cmd = server.popCommandWait(); - assert (cmd == "RCPT TO: "); - cmd = server.popCommandWait(); - assert (cmd == "DATA"); - cmd = server.popCommandWait(); - assert (cmd == "Content-Transfer-Encoding: quoted-printable"); - cmd = server.popCommandWait(); - assert (cmd == "Content-Type: text/plain"); - cmd = server.popCommandWait(); - assert (cmd.substr(0, 4) == "Date"); - cmd = server.popCommandWait(); - assert (cmd == "From: john.doe@no.where"); - cmd = server.popCommandWait(); - assert (cmd == "Subject: Test Message"); - cmd = server.popCommandWait(); - assert (cmd == "To: Jane Doe "); - cmd = server.popCommandWait(); - assert (cmd == "Hello"); - cmd = server.popCommandWait(); - assert (cmd == "blah blah"); - cmd = server.popCommandWait(); - assert (cmd == "John"); - cmd = server.popCommandWait(); - assert (cmd == "."); - - session.close(); -} - - -void SMTPClientSessionTest::testSendFailed() -{ - DialogServer server; - server.addResponse("220 localhost SMTP ready"); - server.addResponse("250 Hello localhost"); - server.addResponse("250 OK"); - server.addResponse("250 OK"); - server.addResponse("354 Send data"); - server.addResponse("500 Error"); - server.addResponse("221 Bye"); - SMTPClientSession session("localhost", server.port()); - session.login("localhost"); - - MailMessage message; - message.setSender("john.doe@no.where"); - message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, "jane.doe@no.where", "Jane Doe")); - message.setSubject("Test Message"); - message.setContent("Hello\r\nblah blah\r\n\r\nJohn\r\n"); - server.clearCommands(); - try - { - session.sendMessage(message); - fail("internal error - must throw"); - } - catch (SMTPException&) - { - } - - session.close(); -} - - -void SMTPClientSessionTest::setUp() -{ -} - - -void SMTPClientSessionTest::tearDown() -{ -} - - -CppUnit::Test* SMTPClientSessionTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SMTPClientSessionTest"); - - CppUnit_addTest(pSuite, SMTPClientSessionTest, testLoginEHLO); - CppUnit_addTest(pSuite, SMTPClientSessionTest, testLoginHELO); - CppUnit_addTest(pSuite, SMTPClientSessionTest, testLoginFailed); - CppUnit_addTest(pSuite, SMTPClientSessionTest, testSend); - CppUnit_addTest(pSuite, SMTPClientSessionTest, testSendFailed); - - return pSuite; -} +// +// SMTPClientSessionTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/SMTPClientSessionTest.cpp#1 $ +// +// 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 "SMTPClientSessionTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "DialogServer.h" +#include "Poco/Net/SMTPClientSession.h" +#include "Poco/Net/MailMessage.h" +#include "Poco/Net/MailRecipient.h" +#include "Poco/Net/NetException.h" + + +using Poco::Net::SMTPClientSession; +using Poco::Net::MailMessage; +using Poco::Net::MailRecipient; +using Poco::Net::SMTPException; + + +SMTPClientSessionTest::SMTPClientSessionTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SMTPClientSessionTest::~SMTPClientSessionTest() +{ +} + + +void SMTPClientSessionTest::testLoginEHLO() +{ + DialogServer server; + server.addResponse("220 localhost SMTP ready"); + server.addResponse("250 Hello localhost"); + server.addResponse("221 Bye"); + SMTPClientSession session("localhost", server.port()); + session.login("localhost"); + std::string cmd = server.popCommand(); + assert (cmd == "EHLO localhost"); + session.close(); + cmd = server.popCommand(); + assert (cmd == "QUIT"); +} + + +void SMTPClientSessionTest::testLoginHELO() +{ + DialogServer server; + server.addResponse("220 localhost SMTP ready"); + server.addResponse("500 EHLO not understood"); + server.addResponse("250 Hello localhost"); + server.addResponse("221 Bye"); + SMTPClientSession session("localhost", server.port()); + session.login("localhost"); + std::string cmd = server.popCommand(); + assert (cmd == "EHLO localhost"); + cmd = server.popCommand(); + assert (cmd == "HELO localhost"); + session.close(); + cmd = server.popCommand(); + assert (cmd == "QUIT"); +} + + +void SMTPClientSessionTest::testLoginFailed() +{ + DialogServer server; + server.addResponse("500 No SMTP service here"); + server.addResponse("221 Bye"); + SMTPClientSession session("localhost", server.port()); + try + { + session.login("localhost"); + fail("cannot login - must throw"); + } + catch (SMTPException&) + { + } + session.close(); +} + + +void SMTPClientSessionTest::testSend() +{ + DialogServer server; + server.addResponse("220 localhost SMTP ready"); + server.addResponse("250 Hello localhost"); + server.addResponse("250 OK"); + server.addResponse("250 OK"); + server.addResponse("354 Send data"); + server.addResponse("250 OK"); + server.addResponse("221 Bye"); + SMTPClientSession session("localhost", server.port()); + session.login("localhost"); + + MailMessage message; + message.setSender("john.doe@no.where"); + message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, "jane.doe@no.where", "Jane Doe")); + message.setSubject("Test Message"); + message.setContent("Hello\r\nblah blah\r\n\r\nJohn\r\n"); + server.clearCommands(); + session.sendMessage(message); + std::string cmd = server.popCommandWait(); + assert (cmd == "MAIL FROM: "); + cmd = server.popCommandWait(); + assert (cmd == "RCPT TO: "); + cmd = server.popCommandWait(); + assert (cmd == "DATA"); + cmd = server.popCommandWait(); + assert (cmd == "Content-Transfer-Encoding: quoted-printable"); + cmd = server.popCommandWait(); + assert (cmd == "Content-Type: text/plain"); + cmd = server.popCommandWait(); + assert (cmd.substr(0, 4) == "Date"); + cmd = server.popCommandWait(); + assert (cmd == "From: john.doe@no.where"); + cmd = server.popCommandWait(); + assert (cmd == "Subject: Test Message"); + cmd = server.popCommandWait(); + assert (cmd == "To: Jane Doe "); + cmd = server.popCommandWait(); + assert (cmd == "Hello"); + cmd = server.popCommandWait(); + assert (cmd == "blah blah"); + cmd = server.popCommandWait(); + assert (cmd == "John"); + cmd = server.popCommandWait(); + assert (cmd == "."); + + session.close(); +} + + +void SMTPClientSessionTest::testSendFailed() +{ + DialogServer server; + server.addResponse("220 localhost SMTP ready"); + server.addResponse("250 Hello localhost"); + server.addResponse("250 OK"); + server.addResponse("250 OK"); + server.addResponse("354 Send data"); + server.addResponse("500 Error"); + server.addResponse("221 Bye"); + SMTPClientSession session("localhost", server.port()); + session.login("localhost"); + + MailMessage message; + message.setSender("john.doe@no.where"); + message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, "jane.doe@no.where", "Jane Doe")); + message.setSubject("Test Message"); + message.setContent("Hello\r\nblah blah\r\n\r\nJohn\r\n"); + server.clearCommands(); + try + { + session.sendMessage(message); + fail("internal error - must throw"); + } + catch (SMTPException&) + { + } + + session.close(); +} + + +void SMTPClientSessionTest::setUp() +{ +} + + +void SMTPClientSessionTest::tearDown() +{ +} + + +CppUnit::Test* SMTPClientSessionTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SMTPClientSessionTest"); + + CppUnit_addTest(pSuite, SMTPClientSessionTest, testLoginEHLO); + CppUnit_addTest(pSuite, SMTPClientSessionTest, testLoginHELO); + CppUnit_addTest(pSuite, SMTPClientSessionTest, testLoginFailed); + CppUnit_addTest(pSuite, SMTPClientSessionTest, testSend); + CppUnit_addTest(pSuite, SMTPClientSessionTest, testSendFailed); + + return pSuite; +} diff --git a/Net/testsuite/src/SMTPClientSessionTest.h b/Net/testsuite/src/SMTPClientSessionTest.h index 989b5c542..865130825 100644 --- a/Net/testsuite/src/SMTPClientSessionTest.h +++ b/Net/testsuite/src/SMTPClientSessionTest.h @@ -1,64 +1,64 @@ -// -// SMTPClientSessionTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/SMTPClientSessionTest.h#1 $ -// -// Definition of the SMTPClientSessionTest 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 SMTPClientSessionTest_INCLUDED -#define SMTPClientSessionTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class SMTPClientSessionTest: public CppUnit::TestCase -{ -public: - SMTPClientSessionTest(const std::string& name); - ~SMTPClientSessionTest(); - - void testLoginEHLO(); - void testLoginHELO(); - void testLoginFailed(); - void testSend(); - void testSendFailed(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SMTPClientSessionTest_INCLUDED +// +// SMTPClientSessionTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/SMTPClientSessionTest.h#1 $ +// +// Definition of the SMTPClientSessionTest 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 SMTPClientSessionTest_INCLUDED +#define SMTPClientSessionTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class SMTPClientSessionTest: public CppUnit::TestCase +{ +public: + SMTPClientSessionTest(const std::string& name); + ~SMTPClientSessionTest(); + + void testLoginEHLO(); + void testLoginHELO(); + void testLoginFailed(); + void testSend(); + void testSendFailed(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SMTPClientSessionTest_INCLUDED diff --git a/Net/testsuite/src/SocketAddressTest.cpp b/Net/testsuite/src/SocketAddressTest.cpp index a11699611..11d9440c0 100644 --- a/Net/testsuite/src/SocketAddressTest.cpp +++ b/Net/testsuite/src/SocketAddressTest.cpp @@ -1,164 +1,164 @@ -// -// SocketAddressTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/SocketAddressTest.cpp#1 $ -// -// 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 "SocketAddressTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" - - -using Poco::Net::SocketAddress; -using Poco::Net::IPAddress; -using Poco::Net::InvalidAddressException; -using Poco::Net::HostNotFoundException; -using Poco::Net::ServiceNotFoundException; -using Poco::Net::NoAddressFoundException; -using Poco::InvalidArgumentException; - - -SocketAddressTest::SocketAddressTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SocketAddressTest::~SocketAddressTest() -{ -} - - -void SocketAddressTest::testSocketAddress() -{ - SocketAddress wild; - assert (wild.host().isWildcard()); - assert (wild.port() == 0); - - SocketAddress sa1("192.168.1.100", 100); - assert (sa1.host().toString() == "192.168.1.100"); - assert (sa1.port() == 100); - - SocketAddress sa2("192.168.1.100", "100"); - assert (sa2.host().toString() == "192.168.1.100"); - assert (sa2.port() == 100); - - SocketAddress sa3("192.168.1.100", "ftp"); - assert (sa3.host().toString() == "192.168.1.100"); - assert (sa3.port() == 21); - - try - { - SocketAddress sa3("192.168.1.100", "f00bar"); - fail("bad service name - must throw"); - } - catch (ServiceNotFoundException&) - { - } - - SocketAddress sa4("www.appinf.com", 80); - assert (sa4.host().toString() == "213.229.60.82"); - assert (sa4.port() == 80); - - try - { - SocketAddress sa5("192.168.2.260", 80); - fail("invalid address - must throw"); - } - catch (HostNotFoundException&) - { - } - catch (NoAddressFoundException&) - { - } - - try - { - SocketAddress sa6("192.168.2.120", "80000"); - fail("invalid port - must throw"); - } - catch (ServiceNotFoundException&) - { - } - - SocketAddress sa7("192.168.2.120:88"); - assert (sa7.host().toString() == "192.168.2.120"); - assert (sa7.port() == 88); - - SocketAddress sa8("[192.168.2.120]:88"); - assert (sa8.host().toString() == "192.168.2.120"); - assert (sa8.port() == 88); - - try - { - SocketAddress sa9("[192.168.2.260]"); - fail("invalid address - must throw"); - } - catch (InvalidArgumentException&) - { - } - - try - { - SocketAddress sa9("[192.168.2.260:88"); - fail("invalid address - must throw"); - } - catch (InvalidArgumentException&) - { - } -} - - -void SocketAddressTest::testSocketAddress6() -{ -#ifdef POCO_HAVE_IPv6 -#endif -} - - -void SocketAddressTest::setUp() -{ -} - - -void SocketAddressTest::tearDown() -{ -} - - -CppUnit::Test* SocketAddressTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketAddressTest"); - - CppUnit_addTest(pSuite, SocketAddressTest, testSocketAddress); - CppUnit_addTest(pSuite, SocketAddressTest, testSocketAddress6); - - return pSuite; -} +// +// SocketAddressTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/SocketAddressTest.cpp#1 $ +// +// 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 "SocketAddressTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" + + +using Poco::Net::SocketAddress; +using Poco::Net::IPAddress; +using Poco::Net::InvalidAddressException; +using Poco::Net::HostNotFoundException; +using Poco::Net::ServiceNotFoundException; +using Poco::Net::NoAddressFoundException; +using Poco::InvalidArgumentException; + + +SocketAddressTest::SocketAddressTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SocketAddressTest::~SocketAddressTest() +{ +} + + +void SocketAddressTest::testSocketAddress() +{ + SocketAddress wild; + assert (wild.host().isWildcard()); + assert (wild.port() == 0); + + SocketAddress sa1("192.168.1.100", 100); + assert (sa1.host().toString() == "192.168.1.100"); + assert (sa1.port() == 100); + + SocketAddress sa2("192.168.1.100", "100"); + assert (sa2.host().toString() == "192.168.1.100"); + assert (sa2.port() == 100); + + SocketAddress sa3("192.168.1.100", "ftp"); + assert (sa3.host().toString() == "192.168.1.100"); + assert (sa3.port() == 21); + + try + { + SocketAddress sa3("192.168.1.100", "f00bar"); + fail("bad service name - must throw"); + } + catch (ServiceNotFoundException&) + { + } + + SocketAddress sa4("www.appinf.com", 80); + assert (sa4.host().toString() == "213.229.60.82"); + assert (sa4.port() == 80); + + try + { + SocketAddress sa5("192.168.2.260", 80); + fail("invalid address - must throw"); + } + catch (HostNotFoundException&) + { + } + catch (NoAddressFoundException&) + { + } + + try + { + SocketAddress sa6("192.168.2.120", "80000"); + fail("invalid port - must throw"); + } + catch (ServiceNotFoundException&) + { + } + + SocketAddress sa7("192.168.2.120:88"); + assert (sa7.host().toString() == "192.168.2.120"); + assert (sa7.port() == 88); + + SocketAddress sa8("[192.168.2.120]:88"); + assert (sa8.host().toString() == "192.168.2.120"); + assert (sa8.port() == 88); + + try + { + SocketAddress sa9("[192.168.2.260]"); + fail("invalid address - must throw"); + } + catch (InvalidArgumentException&) + { + } + + try + { + SocketAddress sa9("[192.168.2.260:88"); + fail("invalid address - must throw"); + } + catch (InvalidArgumentException&) + { + } +} + + +void SocketAddressTest::testSocketAddress6() +{ +#ifdef POCO_HAVE_IPv6 +#endif +} + + +void SocketAddressTest::setUp() +{ +} + + +void SocketAddressTest::tearDown() +{ +} + + +CppUnit::Test* SocketAddressTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketAddressTest"); + + CppUnit_addTest(pSuite, SocketAddressTest, testSocketAddress); + CppUnit_addTest(pSuite, SocketAddressTest, testSocketAddress6); + + return pSuite; +} diff --git a/Net/testsuite/src/SocketAddressTest.h b/Net/testsuite/src/SocketAddressTest.h index 1f9a9e005..b0fbba23e 100644 --- a/Net/testsuite/src/SocketAddressTest.h +++ b/Net/testsuite/src/SocketAddressTest.h @@ -1,61 +1,61 @@ -// -// SocketAddressTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/SocketAddressTest.h#1 $ -// -// Definition of the SocketAddressTest 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 SocketAddressTest_INCLUDED -#define SocketAddressTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class SocketAddressTest: public CppUnit::TestCase -{ -public: - SocketAddressTest(const std::string& name); - ~SocketAddressTest(); - - void testSocketAddress(); - void testSocketAddress6(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SocketAddressTest_INCLUDED +// +// SocketAddressTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/SocketAddressTest.h#1 $ +// +// Definition of the SocketAddressTest 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 SocketAddressTest_INCLUDED +#define SocketAddressTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class SocketAddressTest: public CppUnit::TestCase +{ +public: + SocketAddressTest(const std::string& name); + ~SocketAddressTest(); + + void testSocketAddress(); + void testSocketAddress6(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SocketAddressTest_INCLUDED diff --git a/Net/testsuite/src/SocketReactorTest.cpp b/Net/testsuite/src/SocketReactorTest.cpp index b5257cffa..330b0404d 100644 --- a/Net/testsuite/src/SocketReactorTest.cpp +++ b/Net/testsuite/src/SocketReactorTest.cpp @@ -1,300 +1,300 @@ -// -// SocketReactorTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/SocketReactorTest.cpp#1 $ -// -// 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 "SocketReactorTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/SocketReactor.h" -#include "Poco/Net/SocketNotification.h" -#include "Poco/Net/SocketConnector.h" -#include "Poco/Net/SocketAcceptor.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Observer.h" -#include - - -using Poco::Net::SocketReactor; -using Poco::Net::SocketConnector; -using Poco::Net::SocketAcceptor; -using Poco::Net::StreamSocket; -using Poco::Net::ServerSocket; -using Poco::Net::SocketAddress; -using Poco::Net::SocketNotification; -using Poco::Net::ReadableNotification; -using Poco::Net::WritableNotification; -using Poco::Net::TimeoutNotification; -using Poco::Net::ShutdownNotification; -using Poco::Observer; - - -namespace -{ - class EchoServiceHandler - { - public: - EchoServiceHandler(StreamSocket& socket, SocketReactor& reactor): - _socket(socket), - _reactor(reactor) - { - _reactor.addEventHandler(_socket, Observer(*this, &EchoServiceHandler::onReadable)); - } - - ~EchoServiceHandler() - { - _reactor.removeEventHandler(_socket, Observer(*this, &EchoServiceHandler::onReadable)); - } - - void onReadable(ReadableNotification* pNf) - { - pNf->release(); - char buffer[8]; - int n = _socket.receiveBytes(buffer, sizeof(buffer)); - if (n > 0) - { - _socket.sendBytes(buffer, n); - } - else - { - _socket.shutdownSend(); - delete this; - } - } - - private: - StreamSocket _socket; - SocketReactor& _reactor; - }; - - class ClientServiceHandler - { - public: - ClientServiceHandler(StreamSocket& socket, SocketReactor& reactor): - _socket(socket), - _reactor(reactor) - { - _timeout = false; - _reactor.addEventHandler(_socket, Observer(*this, &ClientServiceHandler::onReadable)); - _reactor.addEventHandler(_socket, Observer(*this, &ClientServiceHandler::onWritable)); - _reactor.addEventHandler(_socket, Observer(*this, &ClientServiceHandler::onTimeout)); - } - - ~ClientServiceHandler() - { - } - - void onReadable(ReadableNotification* pNf) - { - pNf->release(); - char buffer[32]; - int n = _socket.receiveBytes(buffer, sizeof(buffer)); - if (n > 0) - { - _str.write(buffer, n); - } - else - { - _reactor.removeEventHandler(_socket, Observer(*this, &ClientServiceHandler::onReadable)); - _reactor.stop(); - _data = _str.str(); - delete this; - } - } - - void onWritable(WritableNotification* pNf) - { - pNf->release(); - _reactor.removeEventHandler(_socket, Observer(*this, &ClientServiceHandler::onWritable)); - std::string data(1024, 'x'); - _socket.sendBytes(data.data(), (int) data.length()); - _socket.shutdownSend(); - } - - void onTimeout(TimeoutNotification* pNf) - { - pNf->release(); - _timeout = true; - if (_closeOnTimeout) - { - _reactor.stop(); - delete this; - } - } - - static std::string data() - { - return _data; - } - - static bool timeout() - { - return _timeout; - } - - static bool getCloseOnTimeout() - { - return _closeOnTimeout; - } - - static void setCloseOnTimeout(bool flag) - { - _closeOnTimeout = flag; - } - - private: - StreamSocket _socket; - SocketReactor& _reactor; - std::stringstream _str; - static std::string _data; - static bool _timeout; - static bool _closeOnTimeout; - }; - - - std::string ClientServiceHandler::_data; - bool ClientServiceHandler::_timeout = false; - bool ClientServiceHandler::_closeOnTimeout = false; - - - class FailConnector: public SocketConnector - { - public: - FailConnector(SocketAddress& address, SocketReactor& reactor): - SocketConnector(address, reactor), - _failed(false), - _shutdown(false) - { - reactor.addEventHandler(socket(), Observer(*this, &FailConnector::onShutdown)); - } - - void onShutdown(ShutdownNotification* pNf) - { - pNf->release(); - _shutdown = true; - } - - void onError(int error) - { - _failed = true; - reactor()->stop(); - } - - bool failed() const - { - return _failed; - } - - bool shutdown() const - { - return _shutdown; - } - - private: - bool _failed; - bool _shutdown; - }; -} - - -SocketReactorTest::SocketReactorTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SocketReactorTest::~SocketReactorTest() -{ -} - - -void SocketReactorTest::testSocketReactor() -{ - SocketAddress ssa; - ServerSocket ss(ssa); - SocketReactor reactor; - SocketAcceptor acceptor(ss, reactor); - SocketAddress sa("localhost", ss.address().port()); - SocketConnector connector(sa, reactor); - reactor.run(); - std::string data(ClientServiceHandler::data()); - assert (data.size() == 1024); -} - - -void SocketReactorTest::testSocketConnectorFail() -{ - SocketReactor reactor; - SocketAddress sa("192.168.168.192", 12345); - FailConnector connector(sa, reactor); - assert (!connector.failed()); - assert (!connector.shutdown()); - reactor.run(); - assert (connector.failed()); - assert (connector.shutdown()); -} - - -void SocketReactorTest::testSocketConnectorTimeout() -{ - ClientServiceHandler::setCloseOnTimeout(true); - - SocketAddress ssa; - ServerSocket ss(ssa); - SocketReactor reactor; - SocketAddress sa("localhost", ss.address().port()); - SocketConnector connector(sa, reactor); - reactor.run(); - assert (ClientServiceHandler::timeout()); -} - - -void SocketReactorTest::setUp() -{ - ClientServiceHandler::setCloseOnTimeout(false); -} - - -void SocketReactorTest::tearDown() -{ -} - - -CppUnit::Test* SocketReactorTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketReactorTest"); - - CppUnit_addTest(pSuite, SocketReactorTest, testSocketReactor); - CppUnit_addTest(pSuite, SocketReactorTest, testSocketConnectorFail); - CppUnit_addTest(pSuite, SocketReactorTest, testSocketConnectorTimeout); - - return pSuite; -} +// +// SocketReactorTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/SocketReactorTest.cpp#1 $ +// +// 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 "SocketReactorTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/SocketReactor.h" +#include "Poco/Net/SocketNotification.h" +#include "Poco/Net/SocketConnector.h" +#include "Poco/Net/SocketAcceptor.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Observer.h" +#include + + +using Poco::Net::SocketReactor; +using Poco::Net::SocketConnector; +using Poco::Net::SocketAcceptor; +using Poco::Net::StreamSocket; +using Poco::Net::ServerSocket; +using Poco::Net::SocketAddress; +using Poco::Net::SocketNotification; +using Poco::Net::ReadableNotification; +using Poco::Net::WritableNotification; +using Poco::Net::TimeoutNotification; +using Poco::Net::ShutdownNotification; +using Poco::Observer; + + +namespace +{ + class EchoServiceHandler + { + public: + EchoServiceHandler(StreamSocket& socket, SocketReactor& reactor): + _socket(socket), + _reactor(reactor) + { + _reactor.addEventHandler(_socket, Observer(*this, &EchoServiceHandler::onReadable)); + } + + ~EchoServiceHandler() + { + _reactor.removeEventHandler(_socket, Observer(*this, &EchoServiceHandler::onReadable)); + } + + void onReadable(ReadableNotification* pNf) + { + pNf->release(); + char buffer[8]; + int n = _socket.receiveBytes(buffer, sizeof(buffer)); + if (n > 0) + { + _socket.sendBytes(buffer, n); + } + else + { + _socket.shutdownSend(); + delete this; + } + } + + private: + StreamSocket _socket; + SocketReactor& _reactor; + }; + + class ClientServiceHandler + { + public: + ClientServiceHandler(StreamSocket& socket, SocketReactor& reactor): + _socket(socket), + _reactor(reactor) + { + _timeout = false; + _reactor.addEventHandler(_socket, Observer(*this, &ClientServiceHandler::onReadable)); + _reactor.addEventHandler(_socket, Observer(*this, &ClientServiceHandler::onWritable)); + _reactor.addEventHandler(_socket, Observer(*this, &ClientServiceHandler::onTimeout)); + } + + ~ClientServiceHandler() + { + } + + void onReadable(ReadableNotification* pNf) + { + pNf->release(); + char buffer[32]; + int n = _socket.receiveBytes(buffer, sizeof(buffer)); + if (n > 0) + { + _str.write(buffer, n); + } + else + { + _reactor.removeEventHandler(_socket, Observer(*this, &ClientServiceHandler::onReadable)); + _reactor.stop(); + _data = _str.str(); + delete this; + } + } + + void onWritable(WritableNotification* pNf) + { + pNf->release(); + _reactor.removeEventHandler(_socket, Observer(*this, &ClientServiceHandler::onWritable)); + std::string data(1024, 'x'); + _socket.sendBytes(data.data(), (int) data.length()); + _socket.shutdownSend(); + } + + void onTimeout(TimeoutNotification* pNf) + { + pNf->release(); + _timeout = true; + if (_closeOnTimeout) + { + _reactor.stop(); + delete this; + } + } + + static std::string data() + { + return _data; + } + + static bool timeout() + { + return _timeout; + } + + static bool getCloseOnTimeout() + { + return _closeOnTimeout; + } + + static void setCloseOnTimeout(bool flag) + { + _closeOnTimeout = flag; + } + + private: + StreamSocket _socket; + SocketReactor& _reactor; + std::stringstream _str; + static std::string _data; + static bool _timeout; + static bool _closeOnTimeout; + }; + + + std::string ClientServiceHandler::_data; + bool ClientServiceHandler::_timeout = false; + bool ClientServiceHandler::_closeOnTimeout = false; + + + class FailConnector: public SocketConnector + { + public: + FailConnector(SocketAddress& address, SocketReactor& reactor): + SocketConnector(address, reactor), + _failed(false), + _shutdown(false) + { + reactor.addEventHandler(socket(), Observer(*this, &FailConnector::onShutdown)); + } + + void onShutdown(ShutdownNotification* pNf) + { + pNf->release(); + _shutdown = true; + } + + void onError(int error) + { + _failed = true; + reactor()->stop(); + } + + bool failed() const + { + return _failed; + } + + bool shutdown() const + { + return _shutdown; + } + + private: + bool _failed; + bool _shutdown; + }; +} + + +SocketReactorTest::SocketReactorTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SocketReactorTest::~SocketReactorTest() +{ +} + + +void SocketReactorTest::testSocketReactor() +{ + SocketAddress ssa; + ServerSocket ss(ssa); + SocketReactor reactor; + SocketAcceptor acceptor(ss, reactor); + SocketAddress sa("localhost", ss.address().port()); + SocketConnector connector(sa, reactor); + reactor.run(); + std::string data(ClientServiceHandler::data()); + assert (data.size() == 1024); +} + + +void SocketReactorTest::testSocketConnectorFail() +{ + SocketReactor reactor; + SocketAddress sa("192.168.168.192", 12345); + FailConnector connector(sa, reactor); + assert (!connector.failed()); + assert (!connector.shutdown()); + reactor.run(); + assert (connector.failed()); + assert (connector.shutdown()); +} + + +void SocketReactorTest::testSocketConnectorTimeout() +{ + ClientServiceHandler::setCloseOnTimeout(true); + + SocketAddress ssa; + ServerSocket ss(ssa); + SocketReactor reactor; + SocketAddress sa("localhost", ss.address().port()); + SocketConnector connector(sa, reactor); + reactor.run(); + assert (ClientServiceHandler::timeout()); +} + + +void SocketReactorTest::setUp() +{ + ClientServiceHandler::setCloseOnTimeout(false); +} + + +void SocketReactorTest::tearDown() +{ +} + + +CppUnit::Test* SocketReactorTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketReactorTest"); + + CppUnit_addTest(pSuite, SocketReactorTest, testSocketReactor); + CppUnit_addTest(pSuite, SocketReactorTest, testSocketConnectorFail); + CppUnit_addTest(pSuite, SocketReactorTest, testSocketConnectorTimeout); + + return pSuite; +} diff --git a/Net/testsuite/src/SocketReactorTest.h b/Net/testsuite/src/SocketReactorTest.h index 49c11503a..252ddfefc 100644 --- a/Net/testsuite/src/SocketReactorTest.h +++ b/Net/testsuite/src/SocketReactorTest.h @@ -1,62 +1,62 @@ -// -// SocketReactorTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/SocketReactorTest.h#1 $ -// -// Definition of the SocketReactorTest 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 SocketReactorTest_INCLUDED -#define SocketReactorTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class SocketReactorTest: public CppUnit::TestCase -{ -public: - SocketReactorTest(const std::string& name); - ~SocketReactorTest(); - - void testSocketReactor(); - void testSocketConnectorFail(); - void testSocketConnectorTimeout(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SocketReactorTest_INCLUDED +// +// SocketReactorTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/SocketReactorTest.h#1 $ +// +// Definition of the SocketReactorTest 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 SocketReactorTest_INCLUDED +#define SocketReactorTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class SocketReactorTest: public CppUnit::TestCase +{ +public: + SocketReactorTest(const std::string& name); + ~SocketReactorTest(); + + void testSocketReactor(); + void testSocketConnectorFail(); + void testSocketConnectorTimeout(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SocketReactorTest_INCLUDED diff --git a/Net/testsuite/src/SocketStreamTest.cpp b/Net/testsuite/src/SocketStreamTest.cpp index 89582ddf6..33cfc5dba 100644 --- a/Net/testsuite/src/SocketStreamTest.cpp +++ b/Net/testsuite/src/SocketStreamTest.cpp @@ -1,137 +1,137 @@ -// -// SocketStreamTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/SocketStreamTest.cpp#1 $ -// -// 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 "SocketStreamTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "EchoServer.h" -#include "Poco/Net/SocketStream.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/Timespan.h" -#include "Poco/Stopwatch.h" - - -using Poco::Net::Socket; -using Poco::Net::SocketStream; -using Poco::Net::StreamSocket; -using Poco::Net::ServerSocket; -using Poco::Net::SocketAddress; -using Poco::Net::ConnectionRefusedException; -using Poco::Timespan; -using Poco::Stopwatch; -using Poco::TimeoutException; -using Poco::InvalidArgumentException; - - -SocketStreamTest::SocketStreamTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SocketStreamTest::~SocketStreamTest() -{ -} - - -void SocketStreamTest::testStreamEcho() -{ - EchoServer echoServer; - StreamSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - SocketStream str(ss); - str << "hello"; - assert (str.good()); - str.flush(); - assert (str.good()); - ss.shutdownSend(); - - char buffer[5]; - str.read(buffer, sizeof(buffer)); - assert (str.good()); - assert (str.gcount() == 5); - assert (std::string(buffer, 5) == "hello"); - - ss.close(); -} - - -void SocketStreamTest::testEOF() -{ - StreamSocket ss; - SocketStream str(ss); - { - EchoServer echoServer; - - ss.connect(SocketAddress("localhost", echoServer.port())); - str << "hello"; - assert (str.good()); - str.flush(); - assert (str.good()); - ss.shutdownSend(); - - char buffer[5]; - str.read(buffer, sizeof(buffer)); - assert (str.good()); - assert (str.gcount() == 5); - assert (std::string(buffer, 5) == "hello"); - } - - int c = str.get(); - assert (c == -1); - assert (str.eof()); - - ss.close(); -} - - -void SocketStreamTest::setUp() -{ -} - - -void SocketStreamTest::tearDown() -{ -} - - -CppUnit::Test* SocketStreamTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketStreamTest"); - - CppUnit_addTest(pSuite, SocketStreamTest, testStreamEcho); - CppUnit_addTest(pSuite, SocketStreamTest, testEOF); - - return pSuite; -} +// +// SocketStreamTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/SocketStreamTest.cpp#1 $ +// +// 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 "SocketStreamTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "EchoServer.h" +#include "Poco/Net/SocketStream.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/Timespan.h" +#include "Poco/Stopwatch.h" + + +using Poco::Net::Socket; +using Poco::Net::SocketStream; +using Poco::Net::StreamSocket; +using Poco::Net::ServerSocket; +using Poco::Net::SocketAddress; +using Poco::Net::ConnectionRefusedException; +using Poco::Timespan; +using Poco::Stopwatch; +using Poco::TimeoutException; +using Poco::InvalidArgumentException; + + +SocketStreamTest::SocketStreamTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SocketStreamTest::~SocketStreamTest() +{ +} + + +void SocketStreamTest::testStreamEcho() +{ + EchoServer echoServer; + StreamSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + SocketStream str(ss); + str << "hello"; + assert (str.good()); + str.flush(); + assert (str.good()); + ss.shutdownSend(); + + char buffer[5]; + str.read(buffer, sizeof(buffer)); + assert (str.good()); + assert (str.gcount() == 5); + assert (std::string(buffer, 5) == "hello"); + + ss.close(); +} + + +void SocketStreamTest::testEOF() +{ + StreamSocket ss; + SocketStream str(ss); + { + EchoServer echoServer; + + ss.connect(SocketAddress("localhost", echoServer.port())); + str << "hello"; + assert (str.good()); + str.flush(); + assert (str.good()); + ss.shutdownSend(); + + char buffer[5]; + str.read(buffer, sizeof(buffer)); + assert (str.good()); + assert (str.gcount() == 5); + assert (std::string(buffer, 5) == "hello"); + } + + int c = str.get(); + assert (c == -1); + assert (str.eof()); + + ss.close(); +} + + +void SocketStreamTest::setUp() +{ +} + + +void SocketStreamTest::tearDown() +{ +} + + +CppUnit::Test* SocketStreamTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketStreamTest"); + + CppUnit_addTest(pSuite, SocketStreamTest, testStreamEcho); + CppUnit_addTest(pSuite, SocketStreamTest, testEOF); + + return pSuite; +} diff --git a/Net/testsuite/src/SocketStreamTest.h b/Net/testsuite/src/SocketStreamTest.h index c7ee799e5..9b0820e70 100644 --- a/Net/testsuite/src/SocketStreamTest.h +++ b/Net/testsuite/src/SocketStreamTest.h @@ -1,61 +1,61 @@ -// -// SocketStreamTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/SocketStreamTest.h#1 $ -// -// Definition of the SocketStreamTest 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 SocketStreamTest_INCLUDED -#define SocketStreamTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class SocketStreamTest: public CppUnit::TestCase -{ -public: - SocketStreamTest(const std::string& name); - ~SocketStreamTest(); - - void testStreamEcho(); - void testEOF(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SocketStreamTest_INCLUDED +// +// SocketStreamTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/SocketStreamTest.h#1 $ +// +// Definition of the SocketStreamTest 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 SocketStreamTest_INCLUDED +#define SocketStreamTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class SocketStreamTest: public CppUnit::TestCase +{ +public: + SocketStreamTest(const std::string& name); + ~SocketStreamTest(); + + void testStreamEcho(); + void testEOF(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SocketStreamTest_INCLUDED diff --git a/Net/testsuite/src/SocketTest.cpp b/Net/testsuite/src/SocketTest.cpp index 8f9d636b3..bcfabf342 100644 --- a/Net/testsuite/src/SocketTest.cpp +++ b/Net/testsuite/src/SocketTest.cpp @@ -1,457 +1,457 @@ -// -// SocketTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/SocketTest.cpp#1 $ -// -// 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 "SocketTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "EchoServer.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Net/NetException.h" -#include "Poco/Timespan.h" -#include "Poco/Stopwatch.h" -#include - - -using Poco::Net::Socket; -using Poco::Net::StreamSocket; -using Poco::Net::ServerSocket; -using Poco::Net::SocketAddress; -using Poco::Net::ConnectionRefusedException; -using Poco::Timespan; -using Poco::Stopwatch; -using Poco::TimeoutException; -using Poco::InvalidArgumentException; - - -SocketTest::SocketTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SocketTest::~SocketTest() -{ -} - - -void SocketTest::testEcho() -{ - EchoServer echoServer; - StreamSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - int n = ss.sendBytes("hello", 5); - assert (n == 5); - char buffer[256]; - n = ss.receiveBytes(buffer, sizeof(buffer)); - assert (n == 5); - assert (std::string(buffer, n) == "hello"); - ss.close(); -} - - -void SocketTest::testPoll() -{ - EchoServer echoServer; - StreamSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - Stopwatch sw; - sw.start(); - Timespan timeout(1000000); - assert (!ss.poll(timeout, Socket::SELECT_READ)); - assert (sw.elapsed() >= 900000); - sw.restart(); - assert (ss.poll(timeout, Socket::SELECT_WRITE)); - assert (sw.elapsed() < 100000); - ss.sendBytes("hello", 5); - char buffer[256]; - sw.restart(); - assert (ss.poll(timeout, Socket::SELECT_READ)); - assert (sw.elapsed() < 100000); - int n = ss.receiveBytes(buffer, sizeof(buffer)); - assert (n == 5); - assert (std::string(buffer, n) == "hello"); - ss.close(); -} - - -void SocketTest::testAvailable() -{ - EchoServer echoServer; - StreamSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - Timespan timeout(1000000); - ss.sendBytes("hello", 5); - char buffer[256]; - assert (ss.poll(timeout, Socket::SELECT_READ)); - int av = ss.available(); - assert (av > 0 && av <= 5); - int n = ss.receiveBytes(buffer, sizeof(buffer)); - assert (n == 5); - assert (std::string(buffer, n) == "hello"); - ss.close(); -} - - -void SocketTest::testConnect() -{ - ServerSocket serv; - serv.bind(SocketAddress()); - serv.listen(); - StreamSocket ss; - Timespan timeout(250000); - ss.connect(SocketAddress("localhost", serv.address().port()), timeout); -} - - -void SocketTest::testConnectRefused() -{ - ServerSocket serv; - serv.bind(SocketAddress()); - serv.listen(); - Poco::UInt16 port = serv.address().port(); - serv.close(); - StreamSocket ss; - Timespan timeout(250000); - try - { - ss.connect(SocketAddress("localhost", port)); - fail("connection refused - must throw"); - } - catch (ConnectionRefusedException&) - { - } -} - - -void SocketTest::testConnectRefusedNB() -{ - ServerSocket serv; - serv.bind(SocketAddress()); - serv.listen(); - Poco::UInt16 port = serv.address().port(); - serv.close(); - StreamSocket ss; - Timespan timeout(10000); - try - { - ss.connect(SocketAddress("localhost", port), timeout); - fail("connection refused - must throw"); - } - catch (TimeoutException&) - { - } - catch (ConnectionRefusedException&) - { - } -} - - -void SocketTest::testAddress() -{ - ServerSocket serv; - serv.bind(SocketAddress()); - serv.listen(); - StreamSocket ss; - ss.connect(SocketAddress("localhost", serv.address().port())); - StreamSocket css = serv.acceptConnection(); - assert (css.peerAddress().host() == ss.address().host()); - assert (css.peerAddress().port() == ss.address().port()); -} - - -void SocketTest::testAssign() -{ - ServerSocket serv; - StreamSocket ss1; - StreamSocket ss2; - - assert (ss1 != ss2); - StreamSocket ss3(ss1); - assert (ss1 == ss3); - ss3 = ss2; - assert (ss1 != ss3); - assert (ss2 == ss3); - - try - { - ss1 = serv; - fail("incompatible assignment - must throw"); - } - catch (InvalidArgumentException&) - { - } - - try - { - StreamSocket ss4(serv); - fail("incompatible assignment - must throw"); - } - catch (InvalidArgumentException&) - { - } - - try - { - serv = ss1; - fail("incompatible assignment - must throw"); - } - catch (InvalidArgumentException&) - { - } - - try - { - ServerSocket serv2(ss1); - fail("incompatible assignment - must throw"); - } - catch (InvalidArgumentException&) - { - } -} - - -void SocketTest::testTimeout() -{ - EchoServer echoServer; - StreamSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - - Timespan timeout0 = ss.getReceiveTimeout(); - Timespan timeout(250000); - ss.setReceiveTimeout(timeout); - Timespan timeout1 = ss.getReceiveTimeout(); - std::cout << "original receive timeout: " << timeout0.totalMicroseconds() << std::endl; - std::cout << "requested receive timeout: " << timeout.totalMicroseconds() << std::endl; - std::cout << "actual receive timeout: " << timeout1.totalMicroseconds() << std::endl; - - // some socket implementations adjust the timeout value - // assert (ss.getReceiveTimeout() == timeout); - Stopwatch sw; - try - { - char buffer[256]; - sw.start(); - ss.receiveBytes(buffer, sizeof(buffer)); - fail("nothing to receive - must timeout"); - } - catch (TimeoutException&) - { - } - assert (sw.elapsed() < 1000000); - - timeout0 = ss.getSendTimeout(); - ss.setSendTimeout(timeout); - timeout1 = ss.getSendTimeout(); - std::cout << "original send timeout: " << timeout0.totalMicroseconds() << std::endl; - std::cout << "requested send timeout: " << timeout.totalMicroseconds() << std::endl; - std::cout << "actual send timeout: " << timeout1.totalMicroseconds() << std::endl; - // assert (ss.getSendTimeout() == timeout); -} - - -void SocketTest::testBufferSize() -{ - EchoServer echoServer; - StreamSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - - int osz = ss.getSendBufferSize(); - int rsz = 32000; - ss.setSendBufferSize(rsz); - int asz = ss.getSendBufferSize(); - std::cout << "original send buffer size: " << osz << std::endl; - std::cout << "requested send buffer size: " << rsz << std::endl; - std::cout << "actual send buffer size: " << asz << std::endl; - - osz = ss.getReceiveBufferSize(); - ss.setReceiveBufferSize(rsz); - asz = ss.getReceiveBufferSize(); - std::cout << "original recv buffer size: " << osz << std::endl; - std::cout << "requested recv buffer size: " << rsz << std::endl; - std::cout << "actual recv buffer size: " << asz << std::endl; -} - - -void SocketTest::testOptions() -{ - EchoServer echoServer; - StreamSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - - ss.setLinger(true, 20); - bool f; - int t; - ss.getLinger(f, t); - assert (f && t == 20); - ss.setLinger(false, 0); - ss.getLinger(f, t); - assert (!f); - - ss.setNoDelay(true); - assert (ss.getNoDelay()); - ss.setNoDelay(false); - assert (!ss.getNoDelay()); - - ss.setKeepAlive(true); - assert (ss.getKeepAlive()); - ss.setKeepAlive(false); - assert (!ss.getKeepAlive()); - - ss.setOOBInline(true); - assert (ss.getOOBInline()); - ss.setOOBInline(false); - assert (!ss.getOOBInline()); -} - - -void SocketTest::testSelect() -{ - Timespan timeout(250000); - - EchoServer echoServer; - StreamSocket ss; - ss.connect(SocketAddress("localhost", echoServer.port())); - - Socket::SocketList readList; - Socket::SocketList writeList; - Socket::SocketList exceptList; - - readList.push_back(ss); - assert (Socket::select(readList, writeList, exceptList, timeout) == 0); - assert (readList.empty()); - assert (writeList.empty()); - assert (exceptList.empty()); - - ss.sendBytes("hello", 5); - - ss.poll(timeout, Socket::SELECT_READ); - - readList.push_back(ss); - writeList.push_back(ss); - assert (Socket::select(readList, writeList, exceptList, timeout) == 2); - assert (!readList.empty()); - assert (!writeList.empty()); - assert (exceptList.empty()); - - char buffer[256]; - int n = ss.receiveBytes(buffer, sizeof(buffer)); - assert (n == 5); - assert (std::string(buffer, n) == "hello"); - ss.close(); -} - - -void SocketTest::testSelect2() -{ - Timespan timeout(100000); - - EchoServer echoServer1; - EchoServer echoServer2; - StreamSocket ss1(SocketAddress("localhost", echoServer1.port())); - StreamSocket ss2(SocketAddress("localhost", echoServer2.port())); - - Socket::SocketList readList; - Socket::SocketList writeList; - Socket::SocketList exceptList; - - readList.push_back(ss1); - readList.push_back(ss2); - assert (Socket::select(readList, writeList, exceptList, timeout) == 0); - assert (readList.empty()); - assert (writeList.empty()); - assert (exceptList.empty()); - - ss1.sendBytes("hello", 5); - - ss1.poll(timeout, Socket::SELECT_READ); - - readList.push_back(ss1); - readList.push_back(ss2); - assert (Socket::select(readList, writeList, exceptList, timeout) == 1); - - assert (readList.size() == 1); - assert (readList[0] == ss1); - assert (writeList.empty()); - assert (exceptList.empty()); - - char buffer[256]; - int n = ss1.receiveBytes(buffer, sizeof(buffer)); - assert (n == 5); - - readList.clear(); - writeList.clear(); - exceptList.clear(); - writeList.push_back(ss1); - writeList.push_back(ss2); - assert (Socket::select(readList, writeList, exceptList, timeout) == 2); - assert (readList.empty()); - assert (writeList.size() == 2); - assert (writeList[0] == ss1); - assert (writeList[1] == ss2); - assert (exceptList.empty()); - - ss1.close(); - ss2.close(); -} - - -void SocketTest::setUp() -{ -} - - -void SocketTest::tearDown() -{ -} - - -CppUnit::Test* SocketTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketTest"); - - CppUnit_addTest(pSuite, SocketTest, testEcho); - CppUnit_addTest(pSuite, SocketTest, testPoll); - CppUnit_addTest(pSuite, SocketTest, testAvailable); - CppUnit_addTest(pSuite, SocketTest, testConnect); - CppUnit_addTest(pSuite, SocketTest, testConnectRefused); - CppUnit_addTest(pSuite, SocketTest, testConnectRefusedNB); - CppUnit_addTest(pSuite, SocketTest, testAddress); - CppUnit_addTest(pSuite, SocketTest, testAssign); - CppUnit_addTest(pSuite, SocketTest, testTimeout); - CppUnit_addTest(pSuite, SocketTest, testBufferSize); - CppUnit_addTest(pSuite, SocketTest, testOptions); - CppUnit_addTest(pSuite, SocketTest, testSelect); - CppUnit_addTest(pSuite, SocketTest, testSelect2); - - return pSuite; -} +// +// SocketTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/SocketTest.cpp#1 $ +// +// 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 "SocketTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "EchoServer.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Net/NetException.h" +#include "Poco/Timespan.h" +#include "Poco/Stopwatch.h" +#include + + +using Poco::Net::Socket; +using Poco::Net::StreamSocket; +using Poco::Net::ServerSocket; +using Poco::Net::SocketAddress; +using Poco::Net::ConnectionRefusedException; +using Poco::Timespan; +using Poco::Stopwatch; +using Poco::TimeoutException; +using Poco::InvalidArgumentException; + + +SocketTest::SocketTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SocketTest::~SocketTest() +{ +} + + +void SocketTest::testEcho() +{ + EchoServer echoServer; + StreamSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + int n = ss.sendBytes("hello", 5); + assert (n == 5); + char buffer[256]; + n = ss.receiveBytes(buffer, sizeof(buffer)); + assert (n == 5); + assert (std::string(buffer, n) == "hello"); + ss.close(); +} + + +void SocketTest::testPoll() +{ + EchoServer echoServer; + StreamSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + Stopwatch sw; + sw.start(); + Timespan timeout(1000000); + assert (!ss.poll(timeout, Socket::SELECT_READ)); + assert (sw.elapsed() >= 900000); + sw.restart(); + assert (ss.poll(timeout, Socket::SELECT_WRITE)); + assert (sw.elapsed() < 100000); + ss.sendBytes("hello", 5); + char buffer[256]; + sw.restart(); + assert (ss.poll(timeout, Socket::SELECT_READ)); + assert (sw.elapsed() < 100000); + int n = ss.receiveBytes(buffer, sizeof(buffer)); + assert (n == 5); + assert (std::string(buffer, n) == "hello"); + ss.close(); +} + + +void SocketTest::testAvailable() +{ + EchoServer echoServer; + StreamSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + Timespan timeout(1000000); + ss.sendBytes("hello", 5); + char buffer[256]; + assert (ss.poll(timeout, Socket::SELECT_READ)); + int av = ss.available(); + assert (av > 0 && av <= 5); + int n = ss.receiveBytes(buffer, sizeof(buffer)); + assert (n == 5); + assert (std::string(buffer, n) == "hello"); + ss.close(); +} + + +void SocketTest::testConnect() +{ + ServerSocket serv; + serv.bind(SocketAddress()); + serv.listen(); + StreamSocket ss; + Timespan timeout(250000); + ss.connect(SocketAddress("localhost", serv.address().port()), timeout); +} + + +void SocketTest::testConnectRefused() +{ + ServerSocket serv; + serv.bind(SocketAddress()); + serv.listen(); + Poco::UInt16 port = serv.address().port(); + serv.close(); + StreamSocket ss; + Timespan timeout(250000); + try + { + ss.connect(SocketAddress("localhost", port)); + fail("connection refused - must throw"); + } + catch (ConnectionRefusedException&) + { + } +} + + +void SocketTest::testConnectRefusedNB() +{ + ServerSocket serv; + serv.bind(SocketAddress()); + serv.listen(); + Poco::UInt16 port = serv.address().port(); + serv.close(); + StreamSocket ss; + Timespan timeout(10000); + try + { + ss.connect(SocketAddress("localhost", port), timeout); + fail("connection refused - must throw"); + } + catch (TimeoutException&) + { + } + catch (ConnectionRefusedException&) + { + } +} + + +void SocketTest::testAddress() +{ + ServerSocket serv; + serv.bind(SocketAddress()); + serv.listen(); + StreamSocket ss; + ss.connect(SocketAddress("localhost", serv.address().port())); + StreamSocket css = serv.acceptConnection(); + assert (css.peerAddress().host() == ss.address().host()); + assert (css.peerAddress().port() == ss.address().port()); +} + + +void SocketTest::testAssign() +{ + ServerSocket serv; + StreamSocket ss1; + StreamSocket ss2; + + assert (ss1 != ss2); + StreamSocket ss3(ss1); + assert (ss1 == ss3); + ss3 = ss2; + assert (ss1 != ss3); + assert (ss2 == ss3); + + try + { + ss1 = serv; + fail("incompatible assignment - must throw"); + } + catch (InvalidArgumentException&) + { + } + + try + { + StreamSocket ss4(serv); + fail("incompatible assignment - must throw"); + } + catch (InvalidArgumentException&) + { + } + + try + { + serv = ss1; + fail("incompatible assignment - must throw"); + } + catch (InvalidArgumentException&) + { + } + + try + { + ServerSocket serv2(ss1); + fail("incompatible assignment - must throw"); + } + catch (InvalidArgumentException&) + { + } +} + + +void SocketTest::testTimeout() +{ + EchoServer echoServer; + StreamSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + + Timespan timeout0 = ss.getReceiveTimeout(); + Timespan timeout(250000); + ss.setReceiveTimeout(timeout); + Timespan timeout1 = ss.getReceiveTimeout(); + std::cout << "original receive timeout: " << timeout0.totalMicroseconds() << std::endl; + std::cout << "requested receive timeout: " << timeout.totalMicroseconds() << std::endl; + std::cout << "actual receive timeout: " << timeout1.totalMicroseconds() << std::endl; + + // some socket implementations adjust the timeout value + // assert (ss.getReceiveTimeout() == timeout); + Stopwatch sw; + try + { + char buffer[256]; + sw.start(); + ss.receiveBytes(buffer, sizeof(buffer)); + fail("nothing to receive - must timeout"); + } + catch (TimeoutException&) + { + } + assert (sw.elapsed() < 1000000); + + timeout0 = ss.getSendTimeout(); + ss.setSendTimeout(timeout); + timeout1 = ss.getSendTimeout(); + std::cout << "original send timeout: " << timeout0.totalMicroseconds() << std::endl; + std::cout << "requested send timeout: " << timeout.totalMicroseconds() << std::endl; + std::cout << "actual send timeout: " << timeout1.totalMicroseconds() << std::endl; + // assert (ss.getSendTimeout() == timeout); +} + + +void SocketTest::testBufferSize() +{ + EchoServer echoServer; + StreamSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + + int osz = ss.getSendBufferSize(); + int rsz = 32000; + ss.setSendBufferSize(rsz); + int asz = ss.getSendBufferSize(); + std::cout << "original send buffer size: " << osz << std::endl; + std::cout << "requested send buffer size: " << rsz << std::endl; + std::cout << "actual send buffer size: " << asz << std::endl; + + osz = ss.getReceiveBufferSize(); + ss.setReceiveBufferSize(rsz); + asz = ss.getReceiveBufferSize(); + std::cout << "original recv buffer size: " << osz << std::endl; + std::cout << "requested recv buffer size: " << rsz << std::endl; + std::cout << "actual recv buffer size: " << asz << std::endl; +} + + +void SocketTest::testOptions() +{ + EchoServer echoServer; + StreamSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + + ss.setLinger(true, 20); + bool f; + int t; + ss.getLinger(f, t); + assert (f && t == 20); + ss.setLinger(false, 0); + ss.getLinger(f, t); + assert (!f); + + ss.setNoDelay(true); + assert (ss.getNoDelay()); + ss.setNoDelay(false); + assert (!ss.getNoDelay()); + + ss.setKeepAlive(true); + assert (ss.getKeepAlive()); + ss.setKeepAlive(false); + assert (!ss.getKeepAlive()); + + ss.setOOBInline(true); + assert (ss.getOOBInline()); + ss.setOOBInline(false); + assert (!ss.getOOBInline()); +} + + +void SocketTest::testSelect() +{ + Timespan timeout(250000); + + EchoServer echoServer; + StreamSocket ss; + ss.connect(SocketAddress("localhost", echoServer.port())); + + Socket::SocketList readList; + Socket::SocketList writeList; + Socket::SocketList exceptList; + + readList.push_back(ss); + assert (Socket::select(readList, writeList, exceptList, timeout) == 0); + assert (readList.empty()); + assert (writeList.empty()); + assert (exceptList.empty()); + + ss.sendBytes("hello", 5); + + ss.poll(timeout, Socket::SELECT_READ); + + readList.push_back(ss); + writeList.push_back(ss); + assert (Socket::select(readList, writeList, exceptList, timeout) == 2); + assert (!readList.empty()); + assert (!writeList.empty()); + assert (exceptList.empty()); + + char buffer[256]; + int n = ss.receiveBytes(buffer, sizeof(buffer)); + assert (n == 5); + assert (std::string(buffer, n) == "hello"); + ss.close(); +} + + +void SocketTest::testSelect2() +{ + Timespan timeout(100000); + + EchoServer echoServer1; + EchoServer echoServer2; + StreamSocket ss1(SocketAddress("localhost", echoServer1.port())); + StreamSocket ss2(SocketAddress("localhost", echoServer2.port())); + + Socket::SocketList readList; + Socket::SocketList writeList; + Socket::SocketList exceptList; + + readList.push_back(ss1); + readList.push_back(ss2); + assert (Socket::select(readList, writeList, exceptList, timeout) == 0); + assert (readList.empty()); + assert (writeList.empty()); + assert (exceptList.empty()); + + ss1.sendBytes("hello", 5); + + ss1.poll(timeout, Socket::SELECT_READ); + + readList.push_back(ss1); + readList.push_back(ss2); + assert (Socket::select(readList, writeList, exceptList, timeout) == 1); + + assert (readList.size() == 1); + assert (readList[0] == ss1); + assert (writeList.empty()); + assert (exceptList.empty()); + + char buffer[256]; + int n = ss1.receiveBytes(buffer, sizeof(buffer)); + assert (n == 5); + + readList.clear(); + writeList.clear(); + exceptList.clear(); + writeList.push_back(ss1); + writeList.push_back(ss2); + assert (Socket::select(readList, writeList, exceptList, timeout) == 2); + assert (readList.empty()); + assert (writeList.size() == 2); + assert (writeList[0] == ss1); + assert (writeList[1] == ss2); + assert (exceptList.empty()); + + ss1.close(); + ss2.close(); +} + + +void SocketTest::setUp() +{ +} + + +void SocketTest::tearDown() +{ +} + + +CppUnit::Test* SocketTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketTest"); + + CppUnit_addTest(pSuite, SocketTest, testEcho); + CppUnit_addTest(pSuite, SocketTest, testPoll); + CppUnit_addTest(pSuite, SocketTest, testAvailable); + CppUnit_addTest(pSuite, SocketTest, testConnect); + CppUnit_addTest(pSuite, SocketTest, testConnectRefused); + CppUnit_addTest(pSuite, SocketTest, testConnectRefusedNB); + CppUnit_addTest(pSuite, SocketTest, testAddress); + CppUnit_addTest(pSuite, SocketTest, testAssign); + CppUnit_addTest(pSuite, SocketTest, testTimeout); + CppUnit_addTest(pSuite, SocketTest, testBufferSize); + CppUnit_addTest(pSuite, SocketTest, testOptions); + CppUnit_addTest(pSuite, SocketTest, testSelect); + CppUnit_addTest(pSuite, SocketTest, testSelect2); + + return pSuite; +} diff --git a/Net/testsuite/src/SocketTest.h b/Net/testsuite/src/SocketTest.h index dfb5eef48..9093105a1 100644 --- a/Net/testsuite/src/SocketTest.h +++ b/Net/testsuite/src/SocketTest.h @@ -1,72 +1,72 @@ -// -// SocketTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/SocketTest.h#1 $ -// -// Definition of the SocketTest 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 SocketTest_INCLUDED -#define SocketTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class SocketTest: public CppUnit::TestCase -{ -public: - SocketTest(const std::string& name); - ~SocketTest(); - - void testEcho(); - void testPoll(); - void testAvailable(); - void testConnect(); - void testConnectRefused(); - void testConnectRefusedNB(); - void testAddress(); - void testAssign(); - void testTimeout(); - void testBufferSize(); - void testOptions(); - void testSelect(); - void testSelect2(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SocketTest_INCLUDED +// +// SocketTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/SocketTest.h#1 $ +// +// Definition of the SocketTest 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 SocketTest_INCLUDED +#define SocketTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class SocketTest: public CppUnit::TestCase +{ +public: + SocketTest(const std::string& name); + ~SocketTest(); + + void testEcho(); + void testPoll(); + void testAvailable(); + void testConnect(); + void testConnectRefused(); + void testConnectRefusedNB(); + void testAddress(); + void testAssign(); + void testTimeout(); + void testBufferSize(); + void testOptions(); + void testSelect(); + void testSelect2(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SocketTest_INCLUDED diff --git a/Net/testsuite/src/SocketsTestSuite.cpp b/Net/testsuite/src/SocketsTestSuite.cpp index 742d5086e..aae5fe64d 100644 --- a/Net/testsuite/src/SocketsTestSuite.cpp +++ b/Net/testsuite/src/SocketsTestSuite.cpp @@ -1,56 +1,56 @@ -// -// SocketsTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/SocketsTestSuite.cpp#1 $ -// -// 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 "SocketsTestSuite.h" -#include "SocketTest.h" -#include "SocketStreamTest.h" -#include "DatagramSocketTest.h" -#include "NetworkInterfaceTest.h" -#include "MulticastSocketTest.h" -#include "DialogSocketTest.h" -#include "RawSocketTest.h" - - -CppUnit::Test* SocketsTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketsTestSuite"); - - pSuite->addTest(SocketTest::suite()); - pSuite->addTest(SocketStreamTest::suite()); - pSuite->addTest(DatagramSocketTest::suite()); - pSuite->addTest(NetworkInterfaceTest::suite()); - pSuite->addTest(MulticastSocketTest::suite()); - pSuite->addTest(DialogSocketTest::suite()); - pSuite->addTest(RawSocketTest::suite()); - - return pSuite; -} +// +// SocketsTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/SocketsTestSuite.cpp#1 $ +// +// 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 "SocketsTestSuite.h" +#include "SocketTest.h" +#include "SocketStreamTest.h" +#include "DatagramSocketTest.h" +#include "NetworkInterfaceTest.h" +#include "MulticastSocketTest.h" +#include "DialogSocketTest.h" +#include "RawSocketTest.h" + + +CppUnit::Test* SocketsTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketsTestSuite"); + + pSuite->addTest(SocketTest::suite()); + pSuite->addTest(SocketStreamTest::suite()); + pSuite->addTest(DatagramSocketTest::suite()); + pSuite->addTest(NetworkInterfaceTest::suite()); + pSuite->addTest(MulticastSocketTest::suite()); + pSuite->addTest(DialogSocketTest::suite()); + pSuite->addTest(RawSocketTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/SocketsTestSuite.h b/Net/testsuite/src/SocketsTestSuite.h index 5b48c3ddc..c5da451b8 100644 --- a/Net/testsuite/src/SocketsTestSuite.h +++ b/Net/testsuite/src/SocketsTestSuite.h @@ -1,49 +1,49 @@ -// -// SocketsTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/SocketsTestSuite.h#1 $ -// -// Definition of the SocketsTestSuite 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 SocketsTestSuite_INCLUDED -#define SocketsTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class SocketsTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // SocketsTestSuite_INCLUDED +// +// SocketsTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/SocketsTestSuite.h#1 $ +// +// Definition of the SocketsTestSuite 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 SocketsTestSuite_INCLUDED +#define SocketsTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class SocketsTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // SocketsTestSuite_INCLUDED diff --git a/Net/testsuite/src/TCPServerTest.cpp b/Net/testsuite/src/TCPServerTest.cpp index cafa66c8e..f81646e84 100644 --- a/Net/testsuite/src/TCPServerTest.cpp +++ b/Net/testsuite/src/TCPServerTest.cpp @@ -1,276 +1,276 @@ -// -// TCPServerTest.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/TCPServerTest.cpp#1 $ -// -// 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 "TCPServerTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Net/TCPServer.h" -#include "Poco/Net/TCPServerConnection.h" -#include "Poco/Net/TCPServerConnectionFactory.h" -#include "Poco/Net/TCPServerParams.h" -#include "Poco/Net/StreamSocket.h" -#include "Poco/Net/ServerSocket.h" -#include "Poco/Thread.h" -#include - - -using Poco::Net::TCPServer; -using Poco::Net::TCPServerConnection; -using Poco::Net::TCPServerConnectionFactory; -using Poco::Net::TCPServerConnectionFactoryImpl; -using Poco::Net::TCPServerParams; -using Poco::Net::StreamSocket; -using Poco::Net::ServerSocket; -using Poco::Net::SocketAddress; -using Poco::Thread; - - -namespace -{ - class EchoConnection: public TCPServerConnection - { - public: - EchoConnection(const StreamSocket& s): TCPServerConnection(s) - { - } - - void run() - { - StreamSocket& ss = socket(); - try - { - char buffer[256]; - int n = ss.receiveBytes(buffer, sizeof(buffer)); - while (n > 0) - { - ss.sendBytes(buffer, n); - n = ss.receiveBytes(buffer, sizeof(buffer)); - } - } - catch (Poco::Exception& exc) - { - std::cerr << "EchoConnection: " << exc.displayText() << std::endl; - } - } - }; -} - - -TCPServerTest::TCPServerTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TCPServerTest::~TCPServerTest() -{ -} - - -void TCPServerTest::testOneConnection() -{ - ServerSocket svs(0); - TCPServer srv(new TCPServerConnectionFactoryImpl(), svs); - srv.start(); - assert (srv.currentConnections() == 0); - assert (srv.currentThreads() == 0); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 0); - - SocketAddress sa("localhost", svs.address().port()); - StreamSocket ss1(sa); - std::string data("hello, world"); - ss1.sendBytes(data.data(), (int) data.size()); - char buffer[256]; - int n = ss1.receiveBytes(buffer, sizeof(buffer)); - assert (n > 0); - assert (std::string(buffer, n) == data); - assert (srv.currentConnections() == 1); - assert (srv.currentThreads() == 1); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 1); - ss1.close(); - Thread::sleep(300); - assert (srv.currentConnections() == 0); -} - - -void TCPServerTest::testTwoConnections() -{ - ServerSocket svs(0); - TCPServer srv(new TCPServerConnectionFactoryImpl(), svs); - srv.start(); - assert (srv.currentConnections() == 0); - assert (srv.currentThreads() == 0); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 0); - - SocketAddress sa("localhost", svs.address().port()); - StreamSocket ss1(sa); - StreamSocket ss2(sa); - std::string data("hello, world"); - ss1.sendBytes(data.data(), (int) data.size()); - ss2.sendBytes(data.data(), (int) data.size()); - - char buffer[256]; - int n = ss1.receiveBytes(buffer, sizeof(buffer)); - assert (n > 0); - assert (std::string(buffer, n) == data); - - n = ss2.receiveBytes(buffer, sizeof(buffer)); - assert (n > 0); - assert (std::string(buffer, n) == data); - - assert (srv.currentConnections() == 2); - assert (srv.currentThreads() == 2); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 2); - ss1.close(); - Thread::sleep(300); - assert (srv.currentConnections() == 1); - assert (srv.currentThreads() == 1); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 2); - ss2.close(); - - Thread::sleep(300); - assert (srv.currentConnections() == 0); -} - - -void TCPServerTest::testMultiConnections() -{ - ServerSocket svs(0); - TCPServerParams* pParams = new TCPServerParams; - pParams->setMaxThreads(4); - pParams->setMaxQueued(4); - pParams->setThreadIdleTime(100); - TCPServer srv(new TCPServerConnectionFactoryImpl(), svs, pParams); - srv.start(); - assert (srv.currentConnections() == 0); - assert (srv.currentThreads() == 0); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 0); - - SocketAddress sa("localhost", svs.address().port()); - StreamSocket ss1(sa); - StreamSocket ss2(sa); - StreamSocket ss3(sa); - StreamSocket ss4(sa); - std::string data("hello, world"); - ss1.sendBytes(data.data(), (int) data.size()); - ss2.sendBytes(data.data(), (int) data.size()); - ss3.sendBytes(data.data(), (int) data.size()); - ss4.sendBytes(data.data(), (int) data.size()); - - char buffer[256]; - int n = ss1.receiveBytes(buffer, sizeof(buffer)); - assert (n > 0); - assert (std::string(buffer, n) == data); - - n = ss2.receiveBytes(buffer, sizeof(buffer)); - assert (n > 0); - assert (std::string(buffer, n) == data); - - n = ss3.receiveBytes(buffer, sizeof(buffer)); - assert (n > 0); - assert (std::string(buffer, n) == data); - - n = ss4.receiveBytes(buffer, sizeof(buffer)); - assert (n > 0); - assert (std::string(buffer, n) == data); - - assert (srv.currentConnections() == 4); - assert (srv.currentThreads() == 4); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 4); - - StreamSocket ss5(sa); - Thread::sleep(200); - assert (srv.queuedConnections() == 1); - StreamSocket ss6(sa); - Thread::sleep(200); - assert (srv.queuedConnections() == 2); - - ss1.close(); - Thread::sleep(300); - assert (srv.currentConnections() == 4); - assert (srv.currentThreads() == 4); - assert (srv.queuedConnections() == 1); - assert (srv.totalConnections() == 5); - - ss2.close(); - Thread::sleep(300); - assert (srv.currentConnections() == 4); - assert (srv.currentThreads() == 4); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 6); - - ss3.close(); - Thread::sleep(300); - assert (srv.currentConnections() == 3); - assert (srv.currentThreads() == 3); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 6); - - ss4.close(); - Thread::sleep(300); - assert (srv.currentConnections() == 2); - assert (srv.currentThreads() == 2); - assert (srv.queuedConnections() == 0); - assert (srv.totalConnections() == 6); - - ss5.close(); - ss6.close(); - Thread::sleep(300); - assert (srv.currentConnections() == 0);} - - -void TCPServerTest::setUp() -{ -} - - -void TCPServerTest::tearDown() -{ -} - - -CppUnit::Test* TCPServerTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TCPServerTest"); - - CppUnit_addTest(pSuite, TCPServerTest, testOneConnection); - CppUnit_addTest(pSuite, TCPServerTest, testTwoConnections); - CppUnit_addTest(pSuite, TCPServerTest, testMultiConnections); - - return pSuite; -} +// +// TCPServerTest.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/TCPServerTest.cpp#1 $ +// +// 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 "TCPServerTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Net/TCPServer.h" +#include "Poco/Net/TCPServerConnection.h" +#include "Poco/Net/TCPServerConnectionFactory.h" +#include "Poco/Net/TCPServerParams.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/Thread.h" +#include + + +using Poco::Net::TCPServer; +using Poco::Net::TCPServerConnection; +using Poco::Net::TCPServerConnectionFactory; +using Poco::Net::TCPServerConnectionFactoryImpl; +using Poco::Net::TCPServerParams; +using Poco::Net::StreamSocket; +using Poco::Net::ServerSocket; +using Poco::Net::SocketAddress; +using Poco::Thread; + + +namespace +{ + class EchoConnection: public TCPServerConnection + { + public: + EchoConnection(const StreamSocket& s): TCPServerConnection(s) + { + } + + void run() + { + StreamSocket& ss = socket(); + try + { + char buffer[256]; + int n = ss.receiveBytes(buffer, sizeof(buffer)); + while (n > 0) + { + ss.sendBytes(buffer, n); + n = ss.receiveBytes(buffer, sizeof(buffer)); + } + } + catch (Poco::Exception& exc) + { + std::cerr << "EchoConnection: " << exc.displayText() << std::endl; + } + } + }; +} + + +TCPServerTest::TCPServerTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TCPServerTest::~TCPServerTest() +{ +} + + +void TCPServerTest::testOneConnection() +{ + ServerSocket svs(0); + TCPServer srv(new TCPServerConnectionFactoryImpl(), svs); + srv.start(); + assert (srv.currentConnections() == 0); + assert (srv.currentThreads() == 0); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 0); + + SocketAddress sa("localhost", svs.address().port()); + StreamSocket ss1(sa); + std::string data("hello, world"); + ss1.sendBytes(data.data(), (int) data.size()); + char buffer[256]; + int n = ss1.receiveBytes(buffer, sizeof(buffer)); + assert (n > 0); + assert (std::string(buffer, n) == data); + assert (srv.currentConnections() == 1); + assert (srv.currentThreads() == 1); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 1); + ss1.close(); + Thread::sleep(300); + assert (srv.currentConnections() == 0); +} + + +void TCPServerTest::testTwoConnections() +{ + ServerSocket svs(0); + TCPServer srv(new TCPServerConnectionFactoryImpl(), svs); + srv.start(); + assert (srv.currentConnections() == 0); + assert (srv.currentThreads() == 0); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 0); + + SocketAddress sa("localhost", svs.address().port()); + StreamSocket ss1(sa); + StreamSocket ss2(sa); + std::string data("hello, world"); + ss1.sendBytes(data.data(), (int) data.size()); + ss2.sendBytes(data.data(), (int) data.size()); + + char buffer[256]; + int n = ss1.receiveBytes(buffer, sizeof(buffer)); + assert (n > 0); + assert (std::string(buffer, n) == data); + + n = ss2.receiveBytes(buffer, sizeof(buffer)); + assert (n > 0); + assert (std::string(buffer, n) == data); + + assert (srv.currentConnections() == 2); + assert (srv.currentThreads() == 2); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 2); + ss1.close(); + Thread::sleep(300); + assert (srv.currentConnections() == 1); + assert (srv.currentThreads() == 1); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 2); + ss2.close(); + + Thread::sleep(300); + assert (srv.currentConnections() == 0); +} + + +void TCPServerTest::testMultiConnections() +{ + ServerSocket svs(0); + TCPServerParams* pParams = new TCPServerParams; + pParams->setMaxThreads(4); + pParams->setMaxQueued(4); + pParams->setThreadIdleTime(100); + TCPServer srv(new TCPServerConnectionFactoryImpl(), svs, pParams); + srv.start(); + assert (srv.currentConnections() == 0); + assert (srv.currentThreads() == 0); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 0); + + SocketAddress sa("localhost", svs.address().port()); + StreamSocket ss1(sa); + StreamSocket ss2(sa); + StreamSocket ss3(sa); + StreamSocket ss4(sa); + std::string data("hello, world"); + ss1.sendBytes(data.data(), (int) data.size()); + ss2.sendBytes(data.data(), (int) data.size()); + ss3.sendBytes(data.data(), (int) data.size()); + ss4.sendBytes(data.data(), (int) data.size()); + + char buffer[256]; + int n = ss1.receiveBytes(buffer, sizeof(buffer)); + assert (n > 0); + assert (std::string(buffer, n) == data); + + n = ss2.receiveBytes(buffer, sizeof(buffer)); + assert (n > 0); + assert (std::string(buffer, n) == data); + + n = ss3.receiveBytes(buffer, sizeof(buffer)); + assert (n > 0); + assert (std::string(buffer, n) == data); + + n = ss4.receiveBytes(buffer, sizeof(buffer)); + assert (n > 0); + assert (std::string(buffer, n) == data); + + assert (srv.currentConnections() == 4); + assert (srv.currentThreads() == 4); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 4); + + StreamSocket ss5(sa); + Thread::sleep(200); + assert (srv.queuedConnections() == 1); + StreamSocket ss6(sa); + Thread::sleep(200); + assert (srv.queuedConnections() == 2); + + ss1.close(); + Thread::sleep(300); + assert (srv.currentConnections() == 4); + assert (srv.currentThreads() == 4); + assert (srv.queuedConnections() == 1); + assert (srv.totalConnections() == 5); + + ss2.close(); + Thread::sleep(300); + assert (srv.currentConnections() == 4); + assert (srv.currentThreads() == 4); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 6); + + ss3.close(); + Thread::sleep(300); + assert (srv.currentConnections() == 3); + assert (srv.currentThreads() == 3); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 6); + + ss4.close(); + Thread::sleep(300); + assert (srv.currentConnections() == 2); + assert (srv.currentThreads() == 2); + assert (srv.queuedConnections() == 0); + assert (srv.totalConnections() == 6); + + ss5.close(); + ss6.close(); + Thread::sleep(300); + assert (srv.currentConnections() == 0);} + + +void TCPServerTest::setUp() +{ +} + + +void TCPServerTest::tearDown() +{ +} + + +CppUnit::Test* TCPServerTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TCPServerTest"); + + CppUnit_addTest(pSuite, TCPServerTest, testOneConnection); + CppUnit_addTest(pSuite, TCPServerTest, testTwoConnections); + CppUnit_addTest(pSuite, TCPServerTest, testMultiConnections); + + return pSuite; +} diff --git a/Net/testsuite/src/TCPServerTest.h b/Net/testsuite/src/TCPServerTest.h index ad5747cfa..00d8d5bd5 100644 --- a/Net/testsuite/src/TCPServerTest.h +++ b/Net/testsuite/src/TCPServerTest.h @@ -1,62 +1,62 @@ -// -// TCPServerTest.h -// -// $Id: //poco/1.2/Net/testsuite/src/TCPServerTest.h#1 $ -// -// Definition of the TCPServerTest 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 TCPServerTest_INCLUDED -#define TCPServerTest_INCLUDED - - -#include "Poco/Net/Net.h" -#include "CppUnit/TestCase.h" - - -class TCPServerTest: public CppUnit::TestCase -{ -public: - TCPServerTest(const std::string& name); - ~TCPServerTest(); - - void testOneConnection(); - void testTwoConnections(); - void testMultiConnections(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TCPServerTest_INCLUDED +// +// TCPServerTest.h +// +// $Id: //poco/1.2/Net/testsuite/src/TCPServerTest.h#1 $ +// +// Definition of the TCPServerTest 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 TCPServerTest_INCLUDED +#define TCPServerTest_INCLUDED + + +#include "Poco/Net/Net.h" +#include "CppUnit/TestCase.h" + + +class TCPServerTest: public CppUnit::TestCase +{ +public: + TCPServerTest(const std::string& name); + ~TCPServerTest(); + + void testOneConnection(); + void testTwoConnections(); + void testMultiConnections(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TCPServerTest_INCLUDED diff --git a/Net/testsuite/src/TCPServerTestSuite.cpp b/Net/testsuite/src/TCPServerTestSuite.cpp index 1a80c2350..11cbc2ce4 100644 --- a/Net/testsuite/src/TCPServerTestSuite.cpp +++ b/Net/testsuite/src/TCPServerTestSuite.cpp @@ -1,44 +1,44 @@ -// -// TCPServerTestSuite.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/TCPServerTestSuite.cpp#1 $ -// -// 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 "TCPServerTestSuite.h" -#include "TCPServerTest.h" - - -CppUnit::Test* TCPServerTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TCPServerTestSuite"); - - pSuite->addTest(TCPServerTest::suite()); - - return pSuite; -} +// +// TCPServerTestSuite.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/TCPServerTestSuite.cpp#1 $ +// +// 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 "TCPServerTestSuite.h" +#include "TCPServerTest.h" + + +CppUnit::Test* TCPServerTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TCPServerTestSuite"); + + pSuite->addTest(TCPServerTest::suite()); + + return pSuite; +} diff --git a/Net/testsuite/src/TCPServerTestSuite.h b/Net/testsuite/src/TCPServerTestSuite.h index e5da11272..df2b212ab 100644 --- a/Net/testsuite/src/TCPServerTestSuite.h +++ b/Net/testsuite/src/TCPServerTestSuite.h @@ -1,49 +1,49 @@ -// -// TCPServerTestSuite.h -// -// $Id: //poco/1.2/Net/testsuite/src/TCPServerTestSuite.h#1 $ -// -// Definition of the TCPServerTestSuite 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 TCPServerTestSuite_INCLUDED -#define TCPServerTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class TCPServerTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // TCPServerTestSuite_INCLUDED +// +// TCPServerTestSuite.h +// +// $Id: //poco/1.2/Net/testsuite/src/TCPServerTestSuite.h#1 $ +// +// Definition of the TCPServerTestSuite 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 TCPServerTestSuite_INCLUDED +#define TCPServerTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class TCPServerTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // TCPServerTestSuite_INCLUDED diff --git a/Net/testsuite/src/UDPEchoServer.cpp b/Net/testsuite/src/UDPEchoServer.cpp index 310f40450..cf279b93d 100644 --- a/Net/testsuite/src/UDPEchoServer.cpp +++ b/Net/testsuite/src/UDPEchoServer.cpp @@ -1,105 +1,105 @@ -// -// UDPEchoServer.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/UDPEchoServer.cpp#1 $ -// -// 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 "UDPEchoServer.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Timespan.h" -#include - - -using Poco::Net::Socket; -using Poco::Net::DatagramSocket; -using Poco::Net::SocketAddress; -using Poco::Net::IPAddress; - - -UDPEchoServer::UDPEchoServer(): - _thread("UDPEchoServer"), - _stop(false) -{ - _socket.bind(SocketAddress(), true); - _thread.start(*this); - _ready.wait(); -} - - -UDPEchoServer::UDPEchoServer(const SocketAddress& sa): - _thread("UDPEchoServer"), - _stop(false) -{ - _socket.bind(sa, true); - _thread.start(*this); - _ready.wait(); -} - - -UDPEchoServer::~UDPEchoServer() -{ - _stop = true; - _thread.join(); -} - - -Poco::UInt16 UDPEchoServer::port() const -{ - return _socket.address().port(); -} - - -void UDPEchoServer::run() -{ - _ready.set(); - Poco::Timespan span(250000); - while (!_stop) - { - if (_socket.poll(span, Socket::SELECT_READ)) - { - try - { - char buffer[256]; - SocketAddress sender; - int n = _socket.receiveFrom(buffer, sizeof(buffer), sender); - _socket.sendTo(buffer, n, sender); - } - catch (Poco::Exception& exc) - { - std::cerr << "UDPEchoServer: " << exc.displayText() << std::endl; - } - } - } -} - - -SocketAddress UDPEchoServer::address() const -{ - return _socket.address(); -} +// +// UDPEchoServer.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/UDPEchoServer.cpp#1 $ +// +// 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 "UDPEchoServer.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Timespan.h" +#include + + +using Poco::Net::Socket; +using Poco::Net::DatagramSocket; +using Poco::Net::SocketAddress; +using Poco::Net::IPAddress; + + +UDPEchoServer::UDPEchoServer(): + _thread("UDPEchoServer"), + _stop(false) +{ + _socket.bind(SocketAddress(), true); + _thread.start(*this); + _ready.wait(); +} + + +UDPEchoServer::UDPEchoServer(const SocketAddress& sa): + _thread("UDPEchoServer"), + _stop(false) +{ + _socket.bind(sa, true); + _thread.start(*this); + _ready.wait(); +} + + +UDPEchoServer::~UDPEchoServer() +{ + _stop = true; + _thread.join(); +} + + +Poco::UInt16 UDPEchoServer::port() const +{ + return _socket.address().port(); +} + + +void UDPEchoServer::run() +{ + _ready.set(); + Poco::Timespan span(250000); + while (!_stop) + { + if (_socket.poll(span, Socket::SELECT_READ)) + { + try + { + char buffer[256]; + SocketAddress sender; + int n = _socket.receiveFrom(buffer, sizeof(buffer), sender); + _socket.sendTo(buffer, n, sender); + } + catch (Poco::Exception& exc) + { + std::cerr << "UDPEchoServer: " << exc.displayText() << std::endl; + } + } + } +} + + +SocketAddress UDPEchoServer::address() const +{ + return _socket.address(); +} diff --git a/Net/testsuite/src/UDPEchoServer.h b/Net/testsuite/src/UDPEchoServer.h index efaf110c0..0b9219267 100644 --- a/Net/testsuite/src/UDPEchoServer.h +++ b/Net/testsuite/src/UDPEchoServer.h @@ -1,78 +1,78 @@ -// -// UDPEchoServer.h -// -// $Id: //poco/1.2/Net/testsuite/src/UDPEchoServer.h#1 $ -// -// Definition of the UDPEchoServer 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 UDPEchoServer_INCLUDED -#define UDPEchoServer_INCLUDED - - -#include "Poco/Net/Net.h" -#include "Poco/Net/DatagramSocket.h" -#include "Poco/Net/SocketAddress.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" - - -class UDPEchoServer: public Poco::Runnable - /// A simple sequential UDP echo server. -{ -public: - UDPEchoServer(); - /// Creates the UDPEchoServer. - - UDPEchoServer(const Poco::Net::SocketAddress& sa); - /// Creates the UDPEchoServer and binds it to - /// the given address. - - ~UDPEchoServer(); - /// Destroys the UDPEchoServer. - - Poco::UInt16 port() const; - /// Returns the port the echo server is - /// listening on. - - Poco::Net::SocketAddress address() const; - /// Returns the address of the server. - - void run(); - /// Does the work. - -private: - Poco::Net::DatagramSocket _socket; - Poco::Thread _thread; - Poco::Event _ready; - bool _stop; -}; - - -#endif // UDPEchoServer_INCLUDED +// +// UDPEchoServer.h +// +// $Id: //poco/1.2/Net/testsuite/src/UDPEchoServer.h#1 $ +// +// Definition of the UDPEchoServer 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 UDPEchoServer_INCLUDED +#define UDPEchoServer_INCLUDED + + +#include "Poco/Net/Net.h" +#include "Poco/Net/DatagramSocket.h" +#include "Poco/Net/SocketAddress.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" + + +class UDPEchoServer: public Poco::Runnable + /// A simple sequential UDP echo server. +{ +public: + UDPEchoServer(); + /// Creates the UDPEchoServer. + + UDPEchoServer(const Poco::Net::SocketAddress& sa); + /// Creates the UDPEchoServer and binds it to + /// the given address. + + ~UDPEchoServer(); + /// Destroys the UDPEchoServer. + + Poco::UInt16 port() const; + /// Returns the port the echo server is + /// listening on. + + Poco::Net::SocketAddress address() const; + /// Returns the address of the server. + + void run(); + /// Does the work. + +private: + Poco::Net::DatagramSocket _socket; + Poco::Thread _thread; + Poco::Event _ready; + bool _stop; +}; + + +#endif // UDPEchoServer_INCLUDED diff --git a/Net/testsuite/src/WinDriver.cpp b/Net/testsuite/src/WinDriver.cpp index 6c7f2fd0c..782b38d96 100644 --- a/Net/testsuite/src/WinDriver.cpp +++ b/Net/testsuite/src/WinDriver.cpp @@ -1,50 +1,50 @@ -// -// WinDriver.cpp -// -// $Id: //poco/1.2/Net/testsuite/src/WinDriver.cpp#1 $ -// -// Windows test driver for Poco Net. -// -// 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 "WinTestRunner/WinTestRunner.h" -#include "NetTestSuite.h" - - -class TestDriver: public CppUnit::WinTestRunnerApp -{ - void TestMain() - { - CppUnit::WinTestRunner runner; - runner.addTest(NetTestSuite::suite()); - runner.run(); - } -}; - - -TestDriver theDriver; +// +// WinDriver.cpp +// +// $Id: //poco/1.2/Net/testsuite/src/WinDriver.cpp#1 $ +// +// Windows test driver for Poco Net. +// +// 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 "WinTestRunner/WinTestRunner.h" +#include "NetTestSuite.h" + + +class TestDriver: public CppUnit::WinTestRunnerApp +{ + void TestMain() + { + CppUnit::WinTestRunner runner; + runner.addTest(NetTestSuite::suite()); + runner.run(); + } +}; + + +TestDriver theDriver;