3 #include <sys/socket.h>
6 #include <sys/select.h>
8 #include "Exceptions.hpp"
11 static const char CRLF
[] = { 13, 10, 0 };
12 static const char IAC
[] = { 255, 0 };
14 Telnet::Telnet( int sock
)
23 TelnetPtr
Telnet::Create( int sock
)
25 TelnetPtr
ret( new Telnet( sock
) );
27 ret
->m_cmd
.reset( new TelnetCommand( ret
) );
36 // Read all that's waiting on the socket
43 FD_SET( m_sock
, &fd
);
47 select( m_sock
+ 1, &fd
, NULL
, NULL
, &tv
);
48 if( !FD_ISSET( m_sock
, &fd
) )
53 int size
= recv( m_sock
, tmpBuf
, BufSize
, 0 );
57 throw SessionErrorException
;
61 throw ConnectionTerminatedException
;
64 buf
.append( tmpBuf
, size
);
67 // Parse telnet commands
68 for( unsigned int i
=0; i
<buf
.size(); i
++ )
70 if( m_cmd
->ParsingCommand() || (unsigned char)buf
[i
] == 255 )
72 if( !m_cmd
->Parse( buf
[i
] ) )
74 throw SessionErrorException
;
83 return m_readBuf
.find( CRLF
) != std::string::npos
;
86 void Telnet::Write( const std::string
& msg
)
89 g_log
->Print( "> " + msg
);
93 for( unsigned int i
=0; i
<msg
.size(); i
++ )
97 if( (unsigned char)msg
[i
] == 255 )
104 unsigned int pos
= 0;
105 char *ptr
= (char*)buf
.c_str();
107 while( pos
!= buf
.size() )
109 int size
= send( m_sock
, ptr
, buf
.size() - pos
, 0 );
113 throw SessionErrorException
;
117 throw ConnectionTerminatedException
;
125 std::string
Telnet::GetBuf()
129 unsigned int pos
= m_readBuf
.find( CRLF
);
130 if( pos
== std::string::npos
)
132 throw SessionErrorException
;
135 ret
= m_readBuf
.substr( 0, pos
);
137 m_readBuf
.erase( 0, pos
+ 2 );
140 g_log
->Print( "< " + ret
);
146 void Telnet::EraseCharacter()
148 if( m_readBuf
.size() > 0 )
150 m_readBuf
.erase( m_readBuf
.end() - 1 );
154 void Telnet::EraseLine()
156 throw SessionErrorException
;