17 #include "connectionsocks5proxy.h"
27 #if !defined( _WIN32 ) && !defined( _WIN32_WCE )
28 # include <netinet/in.h>
33 #elif defined( _WIN32_WCE )
34 # include <winsock2.h>
47 const std::string& server,
int port,
bool ip )
49 m_logInstance( logInstance ), m_s5state( S5StateDisconnected ), m_ip( ip )
60 const std::string& server,
int port,
bool ip )
62 m_logInstance( logInstance ), m_s5state( S5StateDisconnected ), m_ip( ip )
88 m_connection = connection;
93 if( m_connection && m_handler )
96 m_s5state = S5StateConnecting;
113 return m_connection->
recv( timeout );
121 return m_connection->
receive();
138 return m_connection->
send( data );
146 m_s5state = S5StateDisconnected;
164 const std::string& data )
175 if( !m_connection || !m_handler )
180 case S5StateConnecting:
181 if( data.length() != 2 || data[0] != 0x05 )
186 if( data[1] == 0x00 )
190 else if( data[1] == 0x02 && !m_proxyUser.empty() && !m_proxyPassword.empty() )
193 "authenticating to socks5 proxy as user " + m_proxyUser );
194 m_s5state = S5StateAuthenticating;
195 char* d =
new char[3 + m_proxyUser.length() + m_proxyPassword.length()];
198 d[pos++] = m_proxyUser.length();
199 strncpy( d + pos, m_proxyUser.c_str(), m_proxyUser.length() );
200 pos += m_proxyUser.length();
201 d[pos++] = m_proxyPassword.length();
202 strncpy( d + pos, m_proxyPassword.c_str(), m_proxyPassword.length() );
203 pos += m_proxyPassword.length();
205 if( !
send( std::string( d, pos ) ) )
212 else if( data[1] == (
char)0xFF && !m_proxyUser.empty() && !m_proxyPassword.empty() )
217 else if( data[1] == (
char)0xFF && ( m_proxyUser.empty() || m_proxyPassword.empty() ) )
228 case S5StateNegotiating:
229 if( data.length() >= 6 && data[0] == 0x05 )
231 if( data[1] == 0x00 )
234 m_s5state = S5StateConnected;
249 case S5StateAuthenticating:
250 if( data.length() == 2 && data[0] == 0x01 && data[1] == 0x00 )
260 case S5StateConnected:
268 void ConnectionSOCKS5Proxy::negotiate()
270 m_s5state = S5StateNegotiating;
271 char *d =
new char[m_ip ? 10 : 6 + m_server.length() + 1];
277 std::string
server = m_server;
282 int j = server.length();
284 for(
int k = 0; k < j && l < 4; ++k )
286 if( server[k] !=
'.' )
289 if( server[k] ==
'.' || k == j-1 )
291 d[pos++] = atoi( s.c_str() ) & 0x0FF;
304 server = (*(servers.begin())).first;
305 port = (*(servers.begin())).second;
309 d[pos++] = m_server.length();
310 strncpy( d + pos, m_server.c_str(), m_server.length() );
311 pos += m_server.length();
313 int nport = htons( port );
315 d[pos++] = nport >> 8;
318 std::ostringstream oss;
319 oss <<
"requesting socks5 proxy connection to " << server <<
":" << port;
323 if( !
send( std::string( d, pos ) ) )
335 std::string server = m_server;
342 server = (*(servers.begin())).first;
343 port = (*(servers.begin())).second;
347 "attempting to negotiate socks5 proxy connection" );
349 bool auth = !m_proxyUser.empty() && !m_proxyPassword.empty();
350 char *d =
new char[auth ? 4 : 3];
361 if( !
send( std::string( d, auth ? 4 : 3 ) ) )