bump product version to 5.0.4.1
[LibreOffice.git] / sal / qa / osl / socket / osl_StreamSocket.cxx
blob42b9b750e5882ff32665110f3f82c24588bb5352
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 /** test coder preface:
21 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform
22 if you are not including ws2_32.lib in makefile.mk, the including format will be like this:
24 .IF "$(OS)" == "WNT"
25 SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib
26 SHL1STDLIBS += ws2_32.lib
27 .ENDIF
29 likewise on Solaris platform.
30 .IF "$(OS)" != "WNT"
31 SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a
32 SHL1STDLIBS += -lsocket -ldl -lnsl
33 .ENDIF
35 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4
36 category.
38 3. some fragment of Socket source implementation are lack of comment so it is hard for testers
39 guess what the exact functionality or usage of a member. Hope the Socket section's comment
40 will be added.
42 4. following functions are declared but not implemented:
43 inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const;
46 #include <sal/types.h>
47 #include <cppunit/TestFixture.h>
48 #include <cppunit/extensions/HelperMacros.h>
49 #include <cppunit/plugin/TestPlugIn.h>
51 #include "sockethelper.hxx"
52 #include <osl/conditn.hxx>
54 using namespace osl;
56 using ::rtl::OUString;
57 using ::rtl::OString;
59 #define IP_PORT_MYPORT9 8897
60 #define IP_PORT_MYPORT10 18900
62 const char * pTestString1 = "test socket";
63 const char * pTestString2 = " Passed#OK";
65 // helper functions
67 // just used to test socket::close() when accepting
68 class AcceptorThread : public Thread
70 ::osl::AcceptorSocket asAcceptorSocket;
71 ::rtl::OUString aHostIP;
72 sal_Bool bOK;
73 protected:
74 void SAL_CALL run( )
76 ::osl::SocketAddr saLocalSocketAddr( aHostIP, IP_PORT_MYPORT9 );
77 ::osl::StreamSocket ssStreamConnection;
79 asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True);
80 sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
81 if ( sal_True != bOK1 )
83 t_print("# AcceptorSocket bind address failed.\n" ) ;
84 return;
86 sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
87 if ( sal_True != bOK2 )
89 t_print("# AcceptorSocket listen address failed.\n" ) ;
90 return;
93 asAcceptorSocket.enableNonBlockingMode( sal_False );
95 oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection );
96 if (eResult != osl_Socket_Ok )
98 bOK = sal_True;
99 t_print("AcceptorThread: acceptConnection failed! \n");
102 public:
103 AcceptorThread(::osl::AcceptorSocket & asSocket, ::rtl::OUString const& aBindIP )
104 : asAcceptorSocket( asSocket ), aHostIP( aBindIP )
106 bOK = sal_False;
109 sal_Bool isOK() { return bOK; }
111 ~AcceptorThread( )
113 if ( isRunning( ) )
115 asAcceptorSocket.shutdown();
116 t_print("# error: Acceptor thread not terminated.\n" );
121 /** Server Socket Thread, served as a temp little server to communicate with client.
123 class ServerSocketThread : public Thread
125 osl::Condition &m_aCondition;
126 protected:
127 oslThreadIdentifier m_id;
129 void SAL_CALL run( )
131 ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
132 ::osl::SocketAddr saLocalSocketAddr( rtl::OUString("127.0.0.1"), IP_PORT_MYPORT9 );
133 ::osl::StreamSocket ssStreamConnection;
135 //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket
136 asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True);
137 while ( schedule( ) == sal_True )
139 sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
140 if ( sal_True != bOK1 )
142 t_print("# ServerSocketThread: AcceptorSocket bind address failed.\n" ) ;
143 break;
145 sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
146 if ( sal_True != bOK2 )
148 t_print("# ServerSocketThread: AcceptorSocket listen address failed.\n" ) ;
149 break;
152 asAcceptorSocket.enableNonBlockingMode( sal_False );
153 m_aCondition.set();
155 oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection );
156 if (eResult != osl_Socket_Ok )
158 t_print("ServerSocketThread: acceptConnection failed! \n");
159 break;
161 sal_Int32 nReadNumber1 = ssStreamConnection.recv( pReadBuffer, 11 );
162 sal_Int32 nReadNumber2 = ssStreamConnection.recv( pReadBuffer + nReadNumber1, 11 );
163 pReadBuffer[nReadNumber1 + nReadNumber2] = '\0';
164 //t_print("# read buffer content: %s\n", pReadBuffer );
165 break;
167 ssStreamConnection.close();
168 asAcceptorSocket.close();
172 void SAL_CALL onTerminated( )
174 //t_print("# normally terminate this server thread %d!\n", m_id );
177 public:
178 // public to check if data transmition is OK
179 sal_Char pReadBuffer[30];
180 ServerSocketThread( osl::Condition &_aCond ):m_aCondition(_aCond)
182 m_aCondition.reset();
183 t_print("#init ServerSocketThread\n");
184 m_id = getIdentifier( );
185 //t_print("# successfully create this ServerSocketThread %d!\n", m_id );
188 ~ServerSocketThread( )
190 if ( isRunning( ) )
191 t_print("# error: ServerSocketThread has not terminated.\n" );
195 /** Client Socket Thread, served as a temp little client to communicate with server.
197 class ClientSocketThread : public Thread
199 protected:
200 osl::Condition &m_aCondition;
201 oslThreadIdentifier m_id;
202 ::osl::SocketAddr m_saTargetSocketAddr;
203 ::osl::ConnectorSocket m_csConnectorSocket;
205 void SAL_CALL run( )
207 TimeValue *pTimeout;
208 pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
209 pTimeout->Seconds = 5;
210 pTimeout->Nanosec = 0;
212 /// if the thread should terminate, schedule return false
213 //while ( schedule( ) == sal_True )
215 if ( osl::Condition::result_ok != m_aCondition.wait( pTimeout ) )
217 free( pTimeout );
218 return;
221 if ( osl_Socket_Ok == m_csConnectorSocket.connect( m_saTargetSocketAddr, pTimeout ))
223 m_csConnectorSocket.send( pTestString1, 11 ); // "test socket"
224 m_csConnectorSocket.send( pTestString2, 10);
226 else
227 t_print("# ClientSocketThread: connect failed! \n");
228 // terminate();
230 m_csConnectorSocket.close();
231 free( pTimeout );
234 void SAL_CALL onTerminated( )
236 //t_print("# normally terminate this thread %d!\n", m_id );
239 public:
240 ClientSocketThread( osl::Condition &_aCond ):
241 m_aCondition(_aCond),
242 m_saTargetSocketAddr( rtl::OUString("127.0.0.1"), IP_PORT_MYPORT9 ),
243 m_csConnectorSocket( )
245 m_id = getIdentifier( );
246 //t_print("# successfully create this client thread %d!\n", m_id );
249 ~ClientSocketThread( )
251 if ( isRunning( ) )
252 t_print("# error: client thread not terminated.\n" );
257 // Helper functions, to create buffers, check buffers
258 class ValueCheckProvider
260 bool m_bFoundFailure;
261 char *m_pBuffer;
262 sal_Int32 m_nBufferSize;
264 public:
265 ValueCheckProvider()
266 :m_bFoundFailure(false),
267 m_pBuffer(NULL),
268 m_nBufferSize(0)
272 bool isFailure() {return m_bFoundFailure;}
274 const char* getBuffer() {return m_pBuffer;}
275 char* getWriteBuffer() {return m_pBuffer;}
277 sal_Int32 getBufferSize() {return m_nBufferSize;}
279 bool checkValues(sal_Int32 _nLength, int _nValue)
281 m_bFoundFailure = false;
282 for(sal_Int32 i=0;i<_nLength;i++)
284 if (m_pBuffer[i] != _nValue)
286 m_bFoundFailure = true;
289 return m_bFoundFailure;
292 void createBuffer(sal_Int32 _nLength, int _nValue)
294 m_nBufferSize = _nLength;
295 m_pBuffer = (char*) malloc(m_nBufferSize);
296 if (m_pBuffer)
298 memset(m_pBuffer, _nValue, m_nBufferSize);
302 void freeBuffer()
304 if (m_pBuffer) free(m_pBuffer);
309 /** Client Socket Thread, served as a temp little client to communicate with server.
312 class ReadSocketThread : public Thread
314 ValueCheckProvider m_aValues;
315 int m_nValue;
316 osl::Condition &m_aCondition;
318 protected:
319 oslThreadIdentifier m_id;
321 void SAL_CALL run( )
323 ::osl::SocketAddr m_aTargetSocketAddr( rtl::OUString("127.0.0.1"), IP_PORT_MYPORT10 );
324 ::osl::ConnectorSocket m_aConnectorSocket;
326 if (! m_aTargetSocketAddr.is())
328 t_print("# SocketAddr was NOT created successfully!\n");
330 else
332 t_print("start ReadSocketThread\n");
334 TimeValue *pTimeout;
335 pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
336 pTimeout->Seconds = 5;
337 pTimeout->Nanosec = 0;
339 m_aCondition.wait();
341 t_print("connect()\n");
343 oslSocketResult eResult = m_aConnectorSocket.connect( m_aTargetSocketAddr, pTimeout );
344 if ( osl_Socket_Ok == eResult )
346 sal_Int32 nReadCount = m_aConnectorSocket.read( m_aValues.getWriteBuffer(), m_aValues.getBufferSize() );
347 m_aValues.checkValues(nReadCount, m_nValue);
349 else
351 t_print("# ReadSocketThread: connect failed! \n");
352 printSocketResult(eResult);
355 //remove this line for deadlock on solaris( margritte.germany )
356 m_aConnectorSocket.close();
357 free( pTimeout );
361 void SAL_CALL onTerminated( )
363 //t_print("# normally terminate this thread %d!\n", m_id );
366 public:
367 sal_Int32 getCount() {return m_aValues.getBufferSize();}
368 bool isOk() {return m_aValues.isFailure() == true ? false : true;}
370 ReadSocketThread(sal_Int32 _nBufferSize, int _nValue, osl::Condition &_aCond )
371 : m_nValue( _nValue ),
372 m_aCondition(_aCond)
374 t_print("#init ReadSocketThread\n");
375 m_id = getIdentifier( );
377 //t_print("# successfully create this client thread %d!\n", m_id );
378 m_aValues.createBuffer(_nBufferSize, 0);
381 ~ReadSocketThread( )
383 if ( isRunning( ) )
384 t_print("# error: client thread not terminated.\n" );
385 m_aValues.freeBuffer();
390 /** Server Socket Thread, write a file which is large
392 class WriteSocketThread : public Thread
394 ValueCheckProvider m_aValues;
395 osl::Condition &m_aCondition;
397 protected:
398 oslThreadIdentifier m_id;
400 void SAL_CALL run( )
402 t_print("start WriteSocketThread\n");
403 ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
404 ::osl::SocketAddr saLocalSocketAddr( rtl::OUString("127.0.0.1"), IP_PORT_MYPORT10 );
405 if (! saLocalSocketAddr.is())
407 t_print("LocalSocketAddr was NOT created successfully!\n");
410 ::osl::StreamSocket ssStreamConnection;
412 //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket
413 asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
415 /// if the thread should terminate, schedule return false
416 // while ( schedule( ) == sal_True )
417 // {
418 t_print("bind()\n");
419 sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
420 if ( sal_True != bOK1 )
422 t_print("# WriteSocketThread: AcceptorSocket bind address failed. \n" ) ;
424 else
426 t_print("listen()\n");
427 sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
428 if ( sal_True != bOK2 )
430 t_print("# WriteSocketThread: AcceptorSocket listen address failed. \n" ) ;
432 else
435 // blocking mode, if read/recv failed, block until success
436 asAcceptorSocket.enableNonBlockingMode( sal_False);
437 t_print("acceptConnection()\n");
438 m_aCondition.set();
440 oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection );
441 if (eResult != osl_Socket_Ok )
443 t_print("WriteSocketThread: acceptConnection failed! \n");
445 else
448 t_print("write()\n");
450 ssStreamConnection.write( m_aValues.getBuffer(), m_aValues.getBufferSize() );
451 t_print("done written.\n");
455 ssStreamConnection.close();
456 asAcceptorSocket.close();
459 void SAL_CALL onTerminated( )
461 //t_print("# normally terminate this server thread %d!\n", m_id );
464 public:
465 // public to check if data transmition is OK
466 WriteSocketThread(sal_Int32 _nBufferSize, int _nValue, osl::Condition &_aCond )
467 : m_aCondition(_aCond)
469 m_aCondition.reset();
471 t_print("#init WriteSocketThread\n");
472 m_id = getIdentifier( );
473 //t_print("# successfully create this server thread %d!\n", m_id );
475 m_aValues.createBuffer(_nBufferSize, _nValue);
478 ~WriteSocketThread( )
480 if ( isRunning( ) )
481 t_print("# error: server thread not terminated.\n" );
482 m_aValues.freeBuffer();
486 namespace osl_StreamSocket
489 /** testing the methods:
490 inline StreamSocket(oslAddrFamily Family = osl_Socket_FamilyInet,
491 oslProtocol Protocol = osl_Socket_ProtocolIp,
492 oslSocketType Type = osl_Socket_TypeStream);
494 inline StreamSocket( const StreamSocket & );
496 inline StreamSocket( oslSocket Socket , __sal_NoAcquire noacquire );
498 inline StreamSocket( oslSocket Socket );
501 class ctors : public CppUnit::TestFixture
503 public:
504 oslSocket sHandle;
505 // initialization
506 void setUp( )
508 sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
511 void tearDown( )
513 sHandle = NULL;
516 void ctors_none()
518 /// Socket constructor.
519 ::osl::StreamSocket ssSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
521 CPPUNIT_ASSERT_MESSAGE( "test for ctors_none constructor function: check if the stream socket was created successfully.",
522 osl_Socket_TypeStream == ssSocket.getType( ) );
525 void ctors_acquire()
527 /// Socket constructor.
528 ::osl::StreamSocket ssSocket( sHandle );
530 CPPUNIT_ASSERT_MESSAGE( "test for ctors_acquire constructor function: check if the socket was created successfully",
531 osl_Socket_TypeStream == ssSocket.getType( ) );
534 void ctors_no_acquire()
536 /// Socket constructor.
537 ::osl::StreamSocket ssSocket( sHandle, SAL_NO_ACQUIRE );
539 CPPUNIT_ASSERT_MESSAGE(" test for ctors_no_acquire constructor function: check if the socket was created successfully",
540 osl_Socket_TypeStream == ssSocket.getType( ) );
543 void ctors_copy_ctor()
545 /// Socket constructor.
546 ::osl::StreamSocket ssSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
547 /// Socket copy constructor.
548 ::osl::StreamSocket copySocket( ssSocket );
550 CPPUNIT_ASSERT_MESSAGE(" test for ctors_copy_ctor constructor function: create new Socket instance using copy constructor",
551 osl_Socket_TypeStream == copySocket.getType( ) );
554 CPPUNIT_TEST_SUITE( ctors );
555 CPPUNIT_TEST( ctors_none );
556 CPPUNIT_TEST( ctors_acquire );
557 CPPUNIT_TEST( ctors_no_acquire );
558 CPPUNIT_TEST( ctors_copy_ctor );
559 CPPUNIT_TEST_SUITE_END();
561 }; // class ctors
563 class send_recv: public CppUnit::TestFixture
565 public:
566 // initialization
567 void setUp( )
571 void tearDown( )
576 void send_recv1()
578 osl::Condition aCondition;
579 //client sent two strings, and server received, check the order and value
580 ServerSocketThread myServerThread( aCondition );
581 ClientSocketThread myClientThread( aCondition );
582 myServerThread.create( );
583 myClientThread.create( );
585 //wait until the thread terminate
586 myClientThread.join( );
587 myServerThread.join( );
588 sal_Char myStr[30] = "";
589 strcat( myStr, pTestString1 );
590 strcat( myStr, pTestString2 );
591 sal_Int32 nRes = strcmp( myServerThread.pReadBuffer, myStr );
592 CPPUNIT_ASSERT_MESSAGE(" test for send/recv with two threads: launch Server/Client threads, send data from client, check received data in Server thread.",
593 nRes == 0 );
596 // error when recv
597 void send_recv2()
599 ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
600 ::osl::SocketAddr saLocalSocketAddr( rtl::OUString("127.0.0.1"), IP_PORT_MYPORT9 );
601 ::osl::StreamSocket ssStreamConnection;
602 sal_Char pReadBuffer[30] = "";
604 osl::Condition aCondition;
605 aCondition.reset();
606 ClientSocketThread myClientThread( aCondition );
607 myClientThread.create( );
609 asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 );
611 asAcceptorSocket.bind( saLocalSocketAddr );
612 asAcceptorSocket.listen( 1 );
613 asAcceptorSocket.enableNonBlockingMode( sal_True );
614 aCondition.set();
616 asAcceptorSocket.acceptConnection( ssStreamConnection );
617 sal_Int32 nReadNumber = ssStreamConnection.recv( pReadBuffer, 11 );
619 myClientThread.join( ) ;
620 ssStreamConnection.close();
621 asAcceptorSocket.close();
622 CPPUNIT_ASSERT_MESSAGE(" test for send/recv, recv error!", nReadNumber == -1 );
625 // LLA: This is a helper function, which create 2 threads, a server and a client.
626 // the server writes the buffersize to the client.
628 void write_read(sal_Int32 _nBufferSize, int _nValue)
630 //client sent two strings, and server received, check the order and value
631 osl::Condition aCondition;
632 WriteSocketThread myServerThread(_nBufferSize, _nValue, aCondition);
633 ReadSocketThread myClientThread(_nBufferSize, _nValue, aCondition);
634 myServerThread.create( );
635 // thread_sleep( 1 );
636 myClientThread.create( );
638 //wait until the thread terminate
639 myClientThread.join( );
640 myServerThread.join( );
642 //Maximum Packet Size is ( ARPANET, MILNET = 1007 Ethernet (10Mb) = 1500
643 // Proteon PRONET = 2046), so here test read 4000 bytes
644 sal_Int32 nLength = myClientThread.getCount();
645 bool bIsOk = myClientThread.isOk(); // check if the values are right.
647 t_print("Length:=%d\n", (int) nLength);
648 t_print(" bIsOk:=%d\n", bIsOk);
650 CPPUNIT_ASSERT_MESSAGE(" test for write/read values with two threads: send data from server, check readed data in client.",
651 nLength == _nBufferSize && bIsOk == true);
654 // Tests with different values and sizes
655 void write_read_001()
657 write_read(50, 10);
659 void write_read_002()
661 write_read(1024, 20);
663 void write_read_003()
665 write_read(4000, 1);
667 void write_read_004()
669 write_read(8192, 3);
671 void write_read_005()
673 write_read(32768, 3);
676 CPPUNIT_TEST_SUITE( send_recv );
677 CPPUNIT_TEST( write_read_001 );
678 CPPUNIT_TEST( write_read_002 );
679 CPPUNIT_TEST( write_read_003 );
680 CPPUNIT_TEST( write_read_004 );
681 CPPUNIT_TEST( write_read_005 );
682 CPPUNIT_TEST( send_recv1 );
683 CPPUNIT_TEST( send_recv2 );
684 // CPPUNIT_TEST( write_read );
685 CPPUNIT_TEST_SUITE_END();
686 }; // class send_recv
688 class SendClientThread : public Thread
690 protected:
691 ::osl::SocketAddr m_saTargetSocketAddr;
692 ::osl::ConnectorSocket m_csConnectorSocket;
693 void SAL_CALL run( )
695 TimeValue *pTimeout;
696 pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
697 pTimeout->Seconds = 5;
698 pTimeout->Nanosec = 0;
700 if ( osl_Socket_Ok == m_csConnectorSocket.connect( m_saTargetSocketAddr, pTimeout ))
702 #if !SILENT_TEST
703 sal_Int32 nWrite1 =
704 #endif
705 m_csConnectorSocket.write( pTestString1, 11 ); // "test socket"
706 #if !SILENT_TEST
707 sal_Int32 nWrite2 =
708 #endif
709 m_csConnectorSocket.write( pTestString2, strlen( pTestString2 ) + 1 );
710 thread_sleep( 2 );
711 m_csConnectorSocket.write( pTestString2, strlen( pTestString2 ) + 1 );
712 t_print("nWrite1 is %d, nWrite2 is %d\n", (int) nWrite1, (int) nWrite2 );
713 //thread_sleep( 1 );
715 else
716 t_print("# SendClientThread: connect failed! \n");
718 m_csConnectorSocket.close();
719 free( pTimeout );
721 public:
722 SendClientThread( ):
723 m_saTargetSocketAddr( rtl::OUString("127.0.0.1"), IP_PORT_MYPORT9 ),
724 m_csConnectorSocket( )
726 //t_print("# successfully create this SendClientThread %d!\n", m_id );
729 ~SendClientThread( )
731 if ( isRunning( ) )
732 t_print("# error: SendClientThread has not terminated.\n" );
737 class shutdown: public CppUnit::TestFixture
739 public:
740 // initialization
741 void setUp( )
745 void tearDown( )
750 // similar to close_002
751 void shutdown_001()
753 #if defined(LINUX)
754 ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
755 AcceptorThread myAcceptorThread( asSocket, rtl::OUString("127.0.0.1") );
756 myAcceptorThread.create();
758 thread_sleep( 1 );
760 //when accepting, shutdown the socket, the thread will not block for accepting
761 asSocket.shutdown();
762 myAcceptorThread.join();
764 CPPUNIT_ASSERT_MESSAGE( "test for close when is accepting: the socket will quit accepting status.",
765 myAcceptorThread.isOK( ) == sal_True );
766 #endif
769 void shutdown_002()
771 ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
772 ::osl::SocketAddr saLocalSocketAddr( rtl::OUString("127.0.0.1"), IP_PORT_MYPORT9);
773 asSocket.setOption( osl_Socket_OptionReuseAddr, 1 );
774 CPPUNIT_ASSERT_MESSAGE("shutdown_002: bind fail", asSocket.bind( saLocalSocketAddr ) == sal_True);
775 CPPUNIT_ASSERT_MESSAGE("shutdown_002: listen fail", asSocket.listen( 1 ) == sal_True );
776 sal_Char pReadBuffer[40];
777 // osl::Condition aCondition;
778 SendClientThread mySendThread;
779 mySendThread.create();
781 asSocket.enableNonBlockingMode( sal_False );
782 ::osl::StreamSocket ssConnectionSocket;
783 oslSocketResult eResult = asSocket.acceptConnection( ssConnectionSocket );
784 CPPUNIT_ASSERT_MESSAGE("shutdown_002: acceptConnection fail", eResult == osl_Socket_Ok );
786 /* set socket option SO_LINGER 0, so close immediately */
787 linger aLingerSet;
788 sal_Int32 nBufferLen = sizeof( struct linger );
789 aLingerSet.l_onoff = 0;
790 aLingerSet.l_linger = 0;
792 ssConnectionSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, nBufferLen );
793 thread_sleep( 1 );
794 //sal_uInt32 nRecv1 = 0;
795 sal_Int32 nRead1 = ssConnectionSocket.read( pReadBuffer, 11 );
797 //shutdown read after client the first send complete
798 ssConnectionSocket.shutdown( osl_Socket_DirRead );
800 sal_Int32 nRead2 = ssConnectionSocket.read( pReadBuffer + nRead1, 12 );
801 sal_Int32 nRead3 = ssConnectionSocket.read( pReadBuffer + nRead1 + nRead2, 12 );
802 t_print("after read 2, nRead1 is %d, nRead2 is %d, nRead3 is %d \n", (int) nRead1, (int) nRead2, (int) nRead3 );
803 mySendThread.join();
805 ssConnectionSocket.close();
806 asSocket.close();
808 /* on Linux, if send is before shutdown(DirRead), can read, nRecv2 still > 0,
809 http://dbforums.com/arch/186/2002/12/586417
810 While on Solaris, after shutdown(DirRead), all read will return 0
812 #ifdef LINUX
813 CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not read(recv).",
814 nRead1 > 0 && nRead3 == 0 );
815 #else
816 CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not read(recv).",
817 nRead1 > 0 && nRead2 == 0 && nRead3 == 0 );
818 #endif
822 void shutdown_003()
824 ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
825 ::osl::SocketAddr saLocalSocketAddr( rtl::OUString("127.0.0.1"), IP_PORT_MYPORT9);
826 asSocket.setOption( osl_Socket_OptionReuseAddr, 1 );
827 CPPUNIT_ASSERT_MESSAGE("shutdown_002: bind fail", asSocket.bind( saLocalSocketAddr ) == sal_True);
828 CPPUNIT_ASSERT_MESSAGE("shutdown_002: listen fail", asSocket.listen( 1 ) == sal_True );
829 sal_Char pReadBuffer[40];
830 osl::Condition aCondition;
831 SendClientThread mySendThread;
832 mySendThread.create();
834 asSocket.enableNonBlockingMode( sal_False );
835 ::osl::StreamSocket ssConnectionSocket;
836 oslSocketResult eResult = asSocket.acceptConnection( ssConnectionSocket );
837 CPPUNIT_ASSERT_MESSAGE("shutdown_002: acceptConnection fail", eResult == osl_Socket_Ok );
839 thread_sleep( 1 );
840 //shutdown write after client the first send complete
841 ssConnectionSocket.shutdown( osl_Socket_DirWrite );
843 // recv should not shutdown
844 sal_Int32 nRead1 = ssConnectionSocket.read( pReadBuffer, 11 );
846 sal_Int32 nWrite = ssConnectionSocket.write( pReadBuffer, 11 );
847 // still can read
848 sal_Int32 nRead3 = ssConnectionSocket.read( pReadBuffer + nRead1 , 12 );
849 t_print("after read 2, nRead1 is %d, nWrite is %d, nRead3 is %d\n", (int) nRead1, (int) nWrite, (int) nRead3 );
850 mySendThread.join();
851 ssConnectionSocket.close();
852 asSocket.close();
854 CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not send(write).",
855 nRead1 > 0 && nWrite == 0 && nRead3 > 0);
859 CPPUNIT_TEST_SUITE( shutdown );
860 CPPUNIT_TEST( shutdown_001 );
861 CPPUNIT_TEST( shutdown_002 );
862 CPPUNIT_TEST( shutdown_003 );
863 CPPUNIT_TEST_SUITE_END();
864 }; // class shutdown
866 class isExceptionPending: public CppUnit::TestFixture
868 public:
869 void isExPending_001()
871 ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
872 TimeValue *pTimeout;
873 pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
874 pTimeout->Seconds = 3;
875 pTimeout->Nanosec = 0;
876 sal_Bool bOk = asSocket.isExceptionPending( pTimeout );
877 free( pTimeout );
879 CPPUNIT_ASSERT_MESSAGE( "test for isExceptionPending.",
880 bOk == sal_False );
883 /**tester's comments: lack of a case that return sal_True, do not know when it will return sal_True*/
885 CPPUNIT_TEST_SUITE( isExceptionPending );
886 CPPUNIT_TEST( isExPending_001 );
887 CPPUNIT_TEST_SUITE_END();
888 }; // class isExceptionPending
890 /** Client Socket Thread, served as a temp little client to communicate with server.
893 #define IP_PORT_TEST 8900
895 class ReadSocket2Thread : public Thread
897 osl::Condition &m_aCondition;
898 char* m_pBuffer;
899 sal_Int32 m_nBufferSize;
900 sal_Int32 m_nReadCount;
901 rtl::OString m_sAddr;
903 bool m_bOk;
905 void setFailed()
907 m_bOk = false;
910 protected:
911 oslThreadIdentifier m_id;
913 void read()
915 if (m_sAddr.getLength() == 0)
917 setFailed();
918 return;
921 // 10.16.66.252
922 ::osl::SocketAddr aSocketAddr( rtl::OUString::createFromAscii(m_sAddr.getStr()), IP_PORT_TEST );
923 ::osl::ConnectorSocket aSocket; // ( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
925 aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True;
927 m_aCondition.wait();
928 t_print("wait done\n");
930 TimeValue *pTimeout;
931 pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
932 pTimeout->Seconds = 20;
933 pTimeout->Nanosec = 0;
935 // blocking mode, if read/recv failed, block until success
936 t_print("enableNonBlockingMode(false)\n");
937 aSocket.enableNonBlockingMode( sal_False );
939 t_print("connect()\n");
940 oslSocketResult eResult = aSocket.connect( aSocketAddr, pTimeout );
941 if ( osl_Socket_Ok == eResult)
943 if (m_pBuffer)
945 t_print("read()\n");
946 m_nReadCount = aSocket.read( m_pBuffer, m_nBufferSize );
947 t_print("%d bytes received.\n", (int) m_nReadCount);
950 else
952 t_print("# ReadSocket2Thread: connect failed! \n");
953 printSocketResult(eResult);
954 setFailed();
957 //remove this line for deadlock on solaris( margritte.germany )
958 aSocket.close();
959 free( pTimeout );
962 void SAL_CALL run( )
964 read();
967 void SAL_CALL onTerminated( )
969 //t_print("# normally terminate this thread %d!\n", m_id );
972 public:
973 sal_Int32 getCount() { return m_nReadCount; }
974 bool isOk() { return m_nReadCount != 0; }
975 bool getFailed() { return m_bOk == false; }
977 ReadSocket2Thread(osl::Condition &_aCondition)
978 :m_aCondition(_aCondition),
979 m_nReadCount(0),
980 m_bOk( true )
982 m_aCondition.reset();
983 m_pBuffer = (char*) malloc(1024);
984 if (m_pBuffer)
986 m_nBufferSize = 1024;
989 m_id = getIdentifier( );
990 //t_print("# successfully create this client thread %d!\n", m_id );
993 void setAddr(rtl::OString const& _sAddr)
995 m_sAddr = _sAddr;
998 ~ReadSocket2Thread( )
1000 if ( isRunning( ) )
1001 t_print("# error: client thread not terminated.\n" );
1002 free(m_pBuffer);
1007 class justtest : public CppUnit::TestFixture
1009 void send_Acceptor(rtl::OString const& _sAddr, osl::Condition &)
1011 ::osl::AcceptorSocket aSocket; // ( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
1012 ::osl::SocketAddr aSocketAddr;
1014 if (! aSocketAddr.setPort(IP_PORT_TEST))
1016 t_print("# can not set port\n" );
1019 if (! aSocketAddr.setHostname(rtl::OUString::createFromAscii(_sAddr.getStr())))
1021 t_print("# can not set hostname/ip\n" );
1024 rtl::OUString aHostname = aSocketAddr.getHostname();
1025 aSocketAddr.getPort();
1027 //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket
1028 aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
1030 /// if the thread should terminate, schedule return false
1031 // while ( schedule( ) == sal_True )
1032 // {
1033 if (! aSocket.bind( aSocketAddr ))
1035 t_print("# can't bind.\n" );
1037 if (! aSocket.listen( ))
1039 t_print("# can't listen. \n" );
1042 // blocking mode, if read/recv failed, block until success
1043 aSocket.enableNonBlockingMode( sal_False);
1044 ::osl::StreamSocket ssStreamConnection;
1046 oslSocketResult eResult = aSocket.acceptConnection( ssStreamConnection );
1047 if (eResult != osl_Socket_Ok )
1049 t_print("WriteSocketThread: acceptConnection failed! \n");
1050 // break;
1052 char const * pBuffer = "Test String\n";
1053 sal_Int32 nBufferSize = strlen(pBuffer);
1054 ssStreamConnection.write( pBuffer, nBufferSize );
1055 // break;
1056 // }
1058 // ssStreamConnection.close();
1059 aSocket.close();
1062 void send_Connector(rtl::OString const& _sAddr, osl::Condition &/*_aCondition*/ )
1064 ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
1065 ::osl::SocketAddr aSocketAddr( rtl::OUString::createFromAscii(_sAddr.getStr()), IP_PORT_TEST );
1067 if (! aSocketAddr.is())
1069 t_print("is failed.\n");
1070 return;
1073 //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket
1074 aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True;
1076 oslSocketResult aResult = aSocket.connect( aSocketAddr );
1077 if ( aResult != osl_Socket_Ok )
1079 t_print("# send_Connector: connect failed. \n" );
1081 else
1083 // blocking mode, if read/recv failed, block until success
1084 // aSocket.enableNonBlockingMode( sal_False );
1086 // _aCondition.set();
1088 ::osl::StreamSocket ssStreamConnection(aSocket);
1090 char const * pBuffer = "GET / HTTP/1.0\015\012\015\012";
1091 sal_Int32 nBufferSize = strlen(pBuffer);
1092 ssStreamConnection.write( pBuffer, nBufferSize );
1094 char *pBufferPeek = (char*) malloc(1024);
1095 sal_Int32 nReadNumber = ssStreamConnection.recv( pBufferPeek, 1024, osl_Socket_MsgPeek);
1096 free(pBufferPeek);
1098 char *pBuffer2 = (char*) malloc(nReadNumber + 1);
1099 sal_Int32 nReadNumberReal = ssStreamConnection.read( pBuffer2, nReadNumber );
1100 pBuffer2[nReadNumberReal] = '\0';
1102 t_print("received: %s\n", pBuffer2);
1104 rtl::OUString suError = ssStreamConnection.getErrorAsString();
1105 free(pBuffer2);
1106 // ssStreamConnection.close();
1108 // ssStreamConnection.close();
1110 aSocket.shutdown(osl_Socket_DirReadWrite);
1111 aSocket.close();
1114 public:
1115 // LLA: send_Connector_2_margritte works, it send strings to echo server on margritte
1116 // but can not receive anything
1118 void send_Connector_2_margritte(rtl::OString const& _sAddr)
1120 ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
1121 ::osl::SocketAddr aSocketAddr( rtl::OUString::createFromAscii(_sAddr.getStr()), IP_PORT_TEST );
1123 //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket
1124 aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True;
1126 oslSocketResult aResult = aSocket.connect( aSocketAddr );
1127 if ( aResult != osl_Socket_Ok )
1129 t_print("# connect failed. \n" );
1131 else
1133 // blocking mode, if read/recv failed, block until success
1134 aSocket.enableNonBlockingMode( sal_False );
1136 ::osl::StreamSocket ssStreamConnection(aSocket);
1138 char const * pBuffer = "Test String\n";
1139 sal_Int32 nBufferSize = strlen(pBuffer);
1140 ssStreamConnection.write( pBuffer, nBufferSize );
1142 char const * pBuffer3 = "quit\n";
1143 nBufferSize = strlen(pBuffer3);
1144 ssStreamConnection.write( pBuffer3, nBufferSize );
1146 ssStreamConnection.close();
1148 aSocket.close();
1151 void send_recv_2_margritte()
1153 rtl::OString sAddr;
1154 sAddr = "margritte.germany.sun.com";
1155 if ( ifAvailable(rtl::OUString::createFromAscii(sAddr.getStr())) == sal_True )
1157 t_print("found %s!\n", sAddr.getStr());
1159 send_Connector_2_margritte(sAddr);
1162 void send_recv()
1164 rtl::OString sAddr;
1165 // if ( ifAvailable(rtl::OUString("margritte.germany")) == sal_True )
1166 // {
1167 // t_print("margritte is alive ! \n");
1168 // sAddr = "margritte.germany";
1169 // }
1171 sAddr = "margritte.germany.sun.com";
1172 if ( ifAvailable(rtl::OUString::createFromAscii(sAddr.getStr())) == sal_True )
1174 t_print("found %s!\n", sAddr.getStr());
1176 // else
1177 // {
1178 // if ( ifAvailable(rtl::OUString("192.168.7.2")) == sal_True )
1179 // {
1180 // sAddr = "192.168.7.2";
1181 // t_print("moon found ! \n");
1182 // }
1183 // else
1184 // {
1185 // if ( ifAvailable(rtl::OUString("moon.linux.bogus")) == sal_True )
1186 // {
1187 // sAddr = "moon.linux.bogus";
1188 // t_print("moon found ! \n");
1189 // }
1190 // else
1191 // {
1192 // if ( ifAvailable(rtl::OUString("moon")) == sal_True )
1193 // {
1194 // sAddr = "moon";
1195 // t_print("moon found ! \n");
1196 // }
1197 // }
1198 // }
1199 // }
1201 // if ( ifAvailable(rtl::OUString("10.16.64.196")) == sal_False )
1202 // {
1203 // t_print("ip 10.16.64.196 is not alive! \n");
1204 // return;
1205 // }
1207 osl::Condition aCondition;
1208 ReadSocket2Thread myReadThread(aCondition);
1209 myReadThread.setAddr(sAddr);
1210 // myReadThread.create();
1212 thread_sleep( 2 );
1213 if (! myReadThread.getFailed())
1215 // send_Acceptor(sAddr, aCondition);
1216 send_Connector(sAddr, aCondition);
1218 thread_sleep( 2 );
1219 if (myReadThread.isRunning())
1221 myReadThread.join();
1223 // termAndJoinThread(&myReadThread);
1225 // statistics
1226 #if !SILENT_TEST
1227 sal_uInt32 nLength =
1228 #endif
1229 myReadThread.getCount();
1231 #if !SILENT_TEST
1232 bool bIsOk =
1233 #endif
1234 myReadThread.isOk(); // check if the values are right.
1236 t_print("Length:=%d\n", (int) nLength);
1237 t_print(" bIsOk:=%d\n", bIsOk);
1239 else
1241 t_print("ERROR: No echo Server on %s found.\n", sAddr.getStr());
1245 void getPage(rtl::OString const& _sAddr);
1246 void test_getPage()
1248 // rtl::OString sPage("lla-1.germany.sun.com");
1249 // getPage(sPage);
1251 rtl::OString sPage("lla-1");
1252 getPage(sPage);
1255 CPPUNIT_TEST_SUITE( justtest );
1256 CPPUNIT_TEST( send_recv );
1257 CPPUNIT_TEST( test_getPage );
1258 CPPUNIT_TEST_SUITE_END();
1259 }; // class isExceptionPending
1261 void justtest::getPage(rtl::OString const& _sAddr)
1263 rtl::OUString suAddr = rtl::OUString::createFromAscii(_sAddr.getStr());
1264 ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
1265 ::osl::SocketAddr aSocketAddr( suAddr, 80 );
1268 // some checks
1269 aSocketAddr.getPort();
1270 oslSocketResult aResult;
1271 rtl::ByteSequence aSeq = aSocketAddr.getAddr(&aResult);
1272 if (aResult != osl_Socket_Ok)
1274 t_print("problem with getAddr: ");
1275 printSocketResult(aResult);
1278 rtl::OUString sStr = aSocketAddr.getHostname(&aResult);
1279 if (aResult != osl_Socket_Ok)
1281 t_print("problem with hostname: ");
1282 printSocketResult(aResult);
1286 oslSocketResult aResult;
1288 // SocketAddr::resolveHostname(suAddr, aSocketAddr);
1289 // if (! aSocketAddr.is())
1290 // {
1291 // t_print("Can't resolve Hostname.\n");
1292 // return;
1293 // }
1294 // rtl::OUString sStr = aSocketAddr.getHostname(&aResult);
1295 // if (aResult != osl_Socket_Ok)
1296 // {
1297 // t_print("problem with hostname: ");
1298 // printSocketResult(aResult);
1300 // }
1302 if (! aSocketAddr.is())
1304 t_print("SocketAddr::is() failed.\n");
1305 return;
1308 //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket
1309 aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True;
1311 aResult = aSocket.connect( aSocketAddr );
1312 if ( aResult != osl_Socket_Ok )
1314 t_print("# send_Connector: connect failed. \n" );
1316 else
1318 // blocking mode, if read/recv failed, block until success
1319 // aSocket.enableNonBlockingMode( sal_False );
1321 // _aCondition.set();
1323 ::osl::StreamSocket ssStreamConnection(aSocket);
1325 char const * pBuffer = "GET / HTTP/1.0\015\012\015\012";
1326 sal_Int32 nBufferSize = strlen(pBuffer);
1327 ssStreamConnection.write( pBuffer, nBufferSize );
1329 char *pBufferPeek = (char*) malloc(1024);
1330 sal_Int32 nReadNumber = 1;
1331 while ( nReadNumber != 0)
1333 nReadNumber = ssStreamConnection.recv( pBufferPeek, 1024, osl_Socket_MsgPeek);
1334 if (nReadNumber > 0)
1336 char *pBuffer2 = (char*) malloc(nReadNumber + 1);
1337 sal_Int32 nReadNumberReal = ssStreamConnection.read( pBuffer2, nReadNumber );
1338 pBuffer2[nReadNumberReal] = '\0';
1339 t_print("%s", pBuffer2);
1340 free(pBuffer2);
1343 free(pBufferPeek);
1345 rtl::OUString suError = ssStreamConnection.getErrorAsString();
1347 aSocket.shutdown(osl_Socket_DirReadWrite);
1348 aSocket.close();
1351 CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::ctors);
1352 CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::send_recv);
1353 // CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::shutdown);
1354 CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::isExceptionPending);
1356 // CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::justtest);
1358 } // namespace osl_StreamSocket
1360 // this macro creates an empty function, which will called by the RegisterAllFunctions()
1361 // to let the user the possibility to also register some functions by hand.
1362 CPPUNIT_PLUGIN_IMPLEMENT();
1364 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */