Store username in Session.
[dftpd.git] / Telnet.cpp
blobf2d00280737cb052c4af308353ad20d4ae9240f9
1 #include <sys/types.h>
2 #include <sys/socket.h>
3 #include <string.h>
4 #include <errno.h>
5 #include "Telnet.hpp"
6 #include "Exceptions.hpp"
8 const char CRLF[] = { 13, 10, 0 };
10 Telnet::Telnet( int sock )
11 : m_sock( sock )
15 Telnet::~Telnet()
19 bool Telnet::Read()
21 std::string buf;
23 // Read all that's waiting on the socket
24 for(;;)
26 char tmpBuf[1024];
27 int size = recv( m_sock, tmpBuf, 1024, 0 );
29 if( size == -1 )
31 if( errno == EAGAIN )
33 // No error, just nothing to be read from socket
34 break;
37 throw strerror( errno );
39 else if( size == 0 )
41 throw ConnectionTerminatedException;
44 buf.append( tmpBuf, size );
47 // Parse according to telnet protocol
49 for( unsigned int i=0; i<buf.size(); i++ )
54 // temporary
55 m_readBuf.append( buf );
57 return m_readBuf.find( CRLF ) != std::string::npos;
60 void Telnet::Write( const std::string& msg )
62 std::string buf( msg );
63 buf.append( CRLF );
65 unsigned int pos = 0;
66 char *ptr = (char*)buf.c_str();
68 while( pos != buf.size() )
70 int size = send( m_sock, ptr, buf.size() - pos, 0 );
72 if( size == -1 )
74 throw strerror( errno );
76 else if( size == 0 )
78 throw ConnectionTerminatedException;
81 pos += size;
82 ptr += size;
86 std::string Telnet::GetBuf()
88 std::string ret;
90 unsigned int pos = m_readBuf.find( CRLF );
91 if( pos == std::string::npos )
93 throw "Trying to get telnet buffer when buffer not ready";
96 ret = m_readBuf.substr( 0, pos );
98 m_readBuf.erase( 0, pos + 2 );
100 return ret;