xref: /trunk/main/sal/qa/osl/socket/sockethelper.cxx (revision cdf0e10c4e3984b49a9502b011690b615761d4a3)
1 /*************************************************************************
2  *
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * Copyright 2000, 2010 Oracle and/or its affiliates.
6  *
7  * OpenOffice.org - a multi-platform office productivity suite
8  *
9  * This file is part of OpenOffice.org.
10  *
11  * OpenOffice.org is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License version 3
13  * only, as published by the Free Software Foundation.
14  *
15  * OpenOffice.org is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Lesser General Public License version 3 for more details
19  * (a copy is included in the LICENSE file that accompanied this code).
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * version 3 along with OpenOffice.org.  If not, see
23  * <http://www.openoffice.org/license.html>
24  * for a copy of the LGPLv3 License.
25  *
26  ************************************************************************/
27 
28 
29 // MARKER(update_precomp.py): autogen include statement, do not remove
30 #include "precompiled_sal.hxx"
31 #include "sockethelper.hxx"
32 #include <testshl/simpleheader.hxx>
33 
34 //------------------------------------------------------------------------
35 // Ip version definition
36 //------------------------------------------------------------------------
37 #define IP_VER     4               /// currently only IPv4 is considered.
38 
39 //------------------------------------------------------------------------
40 // helper functions
41 //------------------------------------------------------------------------
42 
43 /** compare two OUString.
44 */
45 sal_Bool compareUString( const ::rtl::OUString & ustr1, const ::rtl::OUString & ustr2 )
46 {
47     sal_Bool bOk = ustr1.equalsIgnoreAsciiCase( ustr2 );
48 
49     return bOk;
50 }
51 
52 /** compare a OUString and an ASCII string.
53 */
54 sal_Bool compareUString( const ::rtl::OUString & ustr, const sal_Char *astr )
55 {
56     ::rtl::OUString ustr2 = rtl::OUString::createFromAscii( astr );
57     sal_Bool bOk = ustr.equalsIgnoreAsciiCase( ustr2 );
58 
59     return bOk;
60 }
61 
62 /** compare two socket address.
63 */
64 sal_Bool compareSocketAddr( const ::osl::SocketAddr & addr1 , const ::osl::SocketAddr & addr2  )
65 {
66     return ( ( sal_True == compareUString( addr1.getHostname( 0 ), addr2.getHostname( 0 ) ) ) && ( addr2.getPort( ) == addr2.getPort( ) ) );
67 }
68 
69 /*char * oustring2char( const ::rtl::OUString & str )
70 {
71     rtl::OString aString;
72     aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US );
73     t_print("oustring2char %s\n", aString.getStr( ) );
74     sal_Char * sStr = aString.getStr( );
75     return (char *)sStr;
76 }*/
77 
78 /** print a UNI_CODE String. And also print some comments of the string.
79 */
80 void printUString( const ::rtl::OUString & str, const char* msg)
81 {
82     t_print("#%s #printUString_u# ", msg );
83     rtl::OString aString;
84     aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US );
85     //char * sStr = aString.getStr( );
86     t_print("%s\n", aString.getStr( ) );
87 }
88 
89 /** get the local host name.
90     mindy: gethostbyname( "localhost" ), on Linux, it returns the hostname in /etc/hosts + domain name,
91     if no entry in /etc/hosts, it returns "localhost" + domain name
92 */
93 ::rtl::OUString getHost( void )
94 {
95     struct hostent *hptr;
96 
97     hptr = gethostbyname( "localhost" );
98     OSL_ENSURE( hptr != NULL, "#In getHostname function, error on gethostbyname()" );
99     ::rtl::OUString aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) hptr->h_name );
100 
101     return aUString;
102 }
103 
104 /** get the full host name of the current processor, such as "aegean.prc.sun.com" --mindyliu
105 */
106 ::rtl::OUString getThisHostname( void )
107 {
108     ::rtl::OUString aUString;
109 #ifdef WNT
110     struct hostent *hptr;
111     hptr = gethostbyname( "localhost" );
112     OSL_ENSURE( hptr != NULL, "#In getHostname function, error on gethostbyname()" );
113     rtl::OString sHostname(hptr->h_name);
114     aUString = ::rtl::OStringToOUString(sHostname, RTL_TEXTENCODING_ASCII_US);
115 #else
116     char hostname[255];
117     if (gethostname(hostname, 255) != 0) {
118         OSL_ENSURE( false, "#Error: gethostname failed."  );
119     }
120 
121     struct hostent *hptr;
122     //first search /ets/hosts, then search from dns
123     hptr = gethostbyname( hostname);
124     if ( hptr != NULL )
125     {
126     strcpy( hostname, hptr->h_name );
127     }
128 
129     t_print("hostname is %s \n", hostname );
130     rtl::OString sHostname( hostname );
131     aUString = ::rtl::OStringToOUString( sHostname, RTL_TEXTENCODING_ASCII_US );
132     aUString.getLength();
133 #endif
134     return aUString;
135 }
136 
137 /** get IP by name, search /etc/hosts first, then search from dns, fail return OUString("")
138 */
139 ::rtl::OUString getIPbyName( rtl::OString const& str_name )
140 {
141     ::rtl::OUString aUString;
142     struct hostent *hptr;
143     //first search /ets/hosts, then search from dns
144     hptr = gethostbyname( str_name.getStr());
145     if ( hptr != NULL )
146     {
147         struct in_addr ** addrptr;
148         addrptr = (struct in_addr **) hptr->h_addr_list ;
149         //if there are more than one IPs on the same machine, we select one
150         for (; *addrptr; addrptr++)
151         {
152             t_print("#Local IP Address: %s\n", inet_ntoa(**addrptr));
153             aUString = ::rtl::OUString::createFromAscii( (sal_Char *) (inet_ntoa(**addrptr)) );
154         }
155     }
156     return aUString;
157 }
158 
159 /** get local ethernet IP
160 */
161 ::rtl::OUString getLocalIP( )
162 {
163     char hostname[255];
164     gethostname(hostname, 255);
165 
166     return getIPbyName( hostname );
167 }
168 
169 /** construct error message
170 */
171 ::rtl::OUString outputError( const ::rtl::OUString & returnVal, const ::rtl::OUString & rightVal, const sal_Char * msg )
172 {
173     ::rtl::OUString aUString;
174     if ( returnVal.equals( rightVal ) )
175         return aUString;
176     aUString += ::rtl::OUString::createFromAscii(msg);
177     aUString += ::rtl::OUString::createFromAscii(": the returned value is '");
178     aUString += returnVal;
179     aUString += ::rtl::OUString::createFromAscii("', but the value should be '");
180     aUString += rightVal;
181     aUString += ::rtl::OUString::createFromAscii("'.");
182     return aUString;
183 }
184 
185 /** wait _nSec seconds.
186 */
187 void thread_sleep( sal_Int32 _nSec )
188 {
189     /// print statement in thread process must use fflush() to force display.
190     // printf("wait %d seconds. ", _nSec );
191     // fflush(stdout);
192 
193 #ifdef WNT               //Windows
194     Sleep( _nSec * 100 );
195 #endif
196 #if ( defined UNX ) || ( defined OS2 )   //Unix
197     usleep(_nSec * 100000);
198 #endif
199     // t_print("# done\n" );
200 }
201 
202 /** print Boolean value.
203 */
204 void printBool( sal_Bool bOk )
205 {
206     t_print("printBool " );
207     ( sal_True == bOk ) ? t_print("YES!" ): t_print("NO!");
208     t_print("\n");
209 }
210 
211 /** print content of a ByteSequence.
212 */
213 void printByteSequence_IP( const ::rtl::ByteSequence & bsByteSeq, sal_Int32 nLen )
214 {
215     t_print("ByteSequence is: " );
216     for ( int i = 0; i < nLen; i++ ){
217         if ( bsByteSeq[i] < 0 )
218             t_print("%d ",  256 + bsByteSeq[i] );
219         else
220             t_print("%d ",  bsByteSeq[i] );
221     }
222     t_print(" .\n" );
223 }
224 
225 /** convert an IP which is stored as a UString format to a ByteSequence array for later use.
226 */
227 ::rtl::ByteSequence UStringIPToByteSequence( ::rtl::OUString aUStr )
228 {
229 
230     rtl::OString aString = ::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US );
231     const sal_Char *pChar = aString.getStr( ) ;
232     sal_Char tmpBuffer[4];
233     sal_Int32 nCharCounter = 0;
234     ::rtl::ByteSequence bsByteSequence( IP_VER );
235     sal_Int32 nByteSeqCounter = 0;
236 
237     for ( int i = 0; i < aString.getLength( ) + 1 ; i++ )
238     {
239         if ( ( *pChar != '.' ) && ( i !=aString.getLength( ) ) )
240             tmpBuffer[nCharCounter++] = *pChar;
241         else
242         {
243             tmpBuffer[nCharCounter] = '\0';
244             nCharCounter = 0;
245             bsByteSequence[nByteSeqCounter++] = static_cast<sal_Int8>(atoi( tmpBuffer ));
246         }
247         pChar++;
248     }
249     return bsByteSequence;
250 }
251 
252 /** print a socket result name.
253 */
254 void printSocketResult( oslSocketResult eResult )
255 {
256     t_print("printSocketResult: " );
257     if (!eResult)
258     switch (eResult)
259     {
260         case osl_Socket_Ok:
261             t_print("client connected\n");
262             break;
263         case osl_Socket_Error:
264             t_print("got an error ... exiting\r\n\r\n" );
265             break;
266         case osl_Socket_TimedOut:
267             t_print("timeout\n");
268             break;
269         case osl_Socket_Interrupted:
270             t_print("interrupted\n");
271             break;
272         case osl_Socket_InProgress:
273             t_print("in progress\n");
274             break;
275     default:
276         t_print("unknown result\n");
277         break;
278     }
279 }
280 
281 /** if 4 parts of an IP addr are equal to specified values
282 */
283 sal_Bool ifIpv4is( const ::rtl::ByteSequence Ipaddr, sal_Int8 seq1, sal_Int8 seq2, sal_Int8 seq3, sal_Int8 seq4 )
284 {
285     if ( ( Ipaddr[0]  == seq1 ) && ( Ipaddr[1] == seq2 ) && ( Ipaddr[2] == seq3 ) && ( Ipaddr[3] == seq4 ) )
286         return sal_True;
287     return sal_False;
288 }
289 
290 /** if the IP or hostname is availble( alive )
291 */
292 /*sal_Bool ifAvailable( const char *  stringAddrOrHostName )
293 {
294     sal_Bool result;
295     int  p[2];
296     sal_Char buffer[2000];
297     char stringhost[20];
298     strcpy(stringhost, stringAddrOrHostName );
299 
300     result = sal_False;
301     if (pipe (p) == 0)
302     {
303     pid_t pid;
304     int nStatus;
305     pid = fork();
306     if (pid == 0)
307     {
308 #if ( defined LINUX )
309         char *argv[] =
310         {
311             "/bin/ping",
312             "-c", "3",
313             "-W", "3",
314             stringhost,
315             NULL
316         };
317 #endif
318 #if ( defined SOLARIS )
319         char *argv[] =
320             {
321                 "/usr/sbin/ping",
322                 stringhost,
323                 "3",
324                 NULL
325             };
326 #endif
327         close (p[0]);
328         dup2  (p[1], 1);
329         close (p[1]);
330 #if ( defined LINUX )
331         execv ("/bin/ping", argv);
332 #endif
333 #if ( defined SOLARIS )
334         execv ("/usr/sbin/ping", argv);
335 #endif
336         // arriving here means exec failed
337         _exit(-1);
338     }
339     else if (pid > 0)
340     {
341         sal_Int32 k = 0, n = 2000;
342         close (p[1]);
343         if ((k = read (p[0], buffer, n - 1)) > 0)
344         {
345             buffer[k] = 0;
346             if (buffer[k - 1] == '\n')
347             buffer[k - 1] = 0;
348 #if ( defined LINUX )
349             char strOK[] = "bytes from";
350 #endif
351 #if ( defined SOLARIS )
352             char strOK[] = "is alive";
353 #endif
354             if (strstr( buffer, strOK ) != NULL )
355                 result = sal_True;
356             t_print("buffer is %s\n", buffer );
357         }
358         close (p[0]);
359         waitpid (pid, &nStatus, 0);
360     }
361     else
362     {
363         close (p[0]);
364         close (p[1]);
365     }
366 
367     }
368     return result;
369 }*/
370 
371 sal_Bool ifAvailable( rtl::OUString const&  strAddrOrHostName )
372 {
373     ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
374     ::osl::SocketAddr aSocketAddr( strAddrOrHostName, 7 );
375 
376     if (! aSocketAddr.is())
377     {
378         aSocket.close();
379         return sal_False;
380     }
381 
382     aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True;
383 
384     TimeValue *pTimeout;
385     pTimeout  = ( TimeValue* )malloc( sizeof( TimeValue ) );
386     pTimeout->Seconds = 3;
387     pTimeout->Nanosec = 0;
388 
389     oslSocketResult aResult = aSocket.connect( aSocketAddr, pTimeout );
390     free( pTimeout );
391     aSocket.close();
392     if  ( aResult != osl_Socket_Ok )
393     {
394         t_print("Error: ");
395         printSocketResult(aResult);
396         t_print("\n");
397 
398         return sal_False;
399     }
400     return sal_True;
401 }
402