Line data Source code
1 : /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 : /*
3 : * This file is part of the LibreOffice project.
4 : *
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/.
8 : */
9 :
10 : #include <BufferedStreamSocket.hxx>
11 :
12 : #include <algorithm>
13 :
14 : #ifdef WIN32
15 : // LO vs WinAPI conflict
16 : #undef WB_LEFT
17 : #undef WB_RIGHT
18 :
19 : #include <winsock2.h>
20 : #else
21 : #include <sys/socket.h>
22 : #include <unistd.h>
23 : #endif
24 : using namespace sd;
25 : using namespace std;
26 : using namespace osl;
27 :
28 0 : BufferedStreamSocket::BufferedStreamSocket( const osl::StreamSocket &aSocket ):
29 : StreamSocket( aSocket ),
30 : aRet( 0 ),
31 : aRead( 0 ),
32 : aBuffer(),
33 : mSocket( 0 ),
34 0 : usingCSocket( false)
35 : {
36 0 : }
37 :
38 0 : BufferedStreamSocket::BufferedStreamSocket( int aSocket ):
39 : StreamSocket(),
40 : aRet( 0 ),
41 : aRead( 0 ),
42 : aBuffer(),
43 : mSocket( aSocket ),
44 0 : usingCSocket( true )
45 : {
46 0 : }
47 :
48 0 : void BufferedStreamSocket::getPeerAddr(osl::SocketAddr& rAddr)
49 : {
50 : assert ( !usingCSocket );
51 0 : StreamSocket::getPeerAddr( rAddr );
52 0 : }
53 :
54 0 : sal_Int32 BufferedStreamSocket::write( const void* pBuffer, sal_uInt32 n )
55 : {
56 0 : if ( !usingCSocket )
57 0 : return StreamSocket::write( pBuffer, n );
58 : else
59 0 : return ::send( mSocket, (const char *) pBuffer, (size_t) n, 0 );
60 : }
61 :
62 0 : sal_Int32 BufferedStreamSocket::readLine( OString& aLine )
63 : {
64 0 : while ( true )
65 : {
66 : // Process buffer first incase data already present.
67 0 : vector<char>::iterator aIt;
68 0 : if ( (aIt = find( aBuffer.begin(), aBuffer.end(), '\n' ))
69 0 : != aBuffer.end() )
70 : {
71 0 : sal_uInt64 aLocation = aIt - aBuffer.begin();
72 :
73 0 : aLine = OString( &(*aBuffer.begin()), aLocation );
74 :
75 0 : aBuffer.erase( aBuffer.begin(), aIt + 1 ); // Also delete the empty line
76 0 : aRead -= (aLocation + 1);
77 :
78 0 : return aLine.getLength() + 1;
79 : }
80 :
81 : // Then try and receive if nothing present
82 0 : aBuffer.resize( aRead + 100 );
83 0 : if ( !usingCSocket)
84 0 : aRet = StreamSocket::recv( &aBuffer[aRead], 100 );
85 : else
86 0 : aRet = ::recv( mSocket, &aBuffer[aRead], 100, 0 );
87 :
88 0 : if ( aRet == 0 )
89 : {
90 0 : return aRet;
91 : }
92 : // Prevent buffer from growing massively large.
93 0 : if ( aRead > MAX_LINE_LENGTH )
94 : {
95 0 : aBuffer.erase( aBuffer.begin(), aBuffer.end() );
96 0 : return 0;
97 : }
98 0 : aRead += aRet;
99 : }
100 :
101 :
102 : }
103 :
104 : /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|