4 #include <sys/socket.h>
5 #include <sys/select.h>
13 #include "Exceptions.hpp"
16 static const char CRLF
[] = { 13, 10, 0 };
17 static const char IAC
[] = { 255, 0 };
19 Telnet::Telnet( int sock
)
28 TelnetPtr
Telnet::Create( int sock
)
30 TelnetPtr
ret( new Telnet( sock
) );
32 ret
->m_cmd
.reset( new TelnetCommand( ret
) );
41 // Read all that's waiting on the socket
48 FD_SET( m_sock
, &fd
);
52 select( m_sock
+ 1, &fd
, NULL
, NULL
, &tv
);
53 if( !FD_ISSET( m_sock
, &fd
) )
58 int size
= recv( m_sock
, tmpBuf
, BufSize
, 0 );
62 throw SessionErrorException
;
66 throw ConnectionTerminatedException
;
69 buf
.append( tmpBuf
, size
);
72 // Parse telnet commands
73 for( unsigned int i
=0; i
<buf
.size(); i
++ )
75 if( m_cmd
->ParsingCommand() || (unsigned char)buf
[i
] == 255 )
77 if( !m_cmd
->Parse( buf
[i
] ) )
79 throw SessionErrorException
;
88 return m_readBuf
.find( CRLF
) != std::string::npos
;
91 void Telnet::Write( const std::string
& msg
)
94 g_log
->Print( "> " + msg
);
98 for( unsigned int i
=0; i
<msg
.size(); i
++ )
102 if( (unsigned char)msg
[i
] == 255 )
109 unsigned int pos
= 0;
110 char *ptr
= (char*)buf
.c_str();
112 while( pos
!= buf
.size() )
114 int size
= send( m_sock
, ptr
, buf
.size() - pos
, 0 );
118 throw SessionErrorException
;
122 throw ConnectionTerminatedException
;
130 std::string
Telnet::GetBuf()
134 unsigned int pos
= m_readBuf
.find( CRLF
);
135 if( pos
== std::string::npos
)
137 throw SessionErrorException
;
140 ret
= m_readBuf
.substr( 0, pos
);
142 m_readBuf
.erase( 0, pos
+ 2 );
145 g_log
->Print( "< " + ret
);
151 void Telnet::EraseCharacter()
153 if( m_readBuf
.size() > 0 )
155 m_readBuf
.erase( m_readBuf
.end() - 1 );
159 void Telnet::EraseLine()
161 throw SessionErrorException
;