/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Neither the name of the KPD-Team, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Org.Mentalis.Network.ProxySocket {
///
/// Implements the SOCKS4[A] protocol.
///
internal sealed class Socks4Handler : SocksHandler {
///
/// Initializes a new instance of the SocksHandler class.
///
/// The socket connection with the proxy server.
/// The username to use when authenticating with the server.
/// server -or- user is null.
public Socks4Handler(Socket server, string user) : base(server, user) {}
///
/// Creates an array of bytes that has to be sent when the user wants to connect to a specific host/port combination.
///
/// The host to connect to.
/// The port to connect to.
/// An array of bytes that has to be sent when the user wants to connect to a specific host/port combination.
/// Resolving the host name will be done at server side. Do note that some SOCKS4 servers do not implement this functionality.
/// host is null.
/// port is invalid.
private byte[] GetHostPortBytes(string host, int port) {
if (host == null)
throw new ArgumentNullException();
if (port <= 0 || port > 65535)
throw new ArgumentException();
byte[] connect = new byte[10 + Username.Length + host.Length];
connect[0] = 4;
connect[1] = 1;
Array.Copy(PortToBytes(port), 0, connect, 2, 2);
connect[4] = connect[5] = connect[6] = 0;
connect[7] = 1;
Array.Copy(Encoding.ASCII.GetBytes(Username), 0, connect, 8, Username.Length);
connect[8 + Username.Length] = 0;
Array.Copy(Encoding.ASCII.GetBytes(host), 0, connect, 9 + Username.Length, host.Length);
connect[9 + Username.Length + host.Length] = 0;
return connect;
}
///
/// Creates an array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.
///
/// The IPEndPoint to connect to.
/// An array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.
/// remoteEP is null.
private byte[] GetEndPointBytes(IPEndPoint remoteEP) {
if (remoteEP == null)
throw new ArgumentNullException();
byte[] connect = new byte[9 + Username.Length];
connect[0] = 4;
connect[1] = 1;
Array.Copy(PortToBytes(remoteEP.Port), 0, connect, 2, 2);
Array.Copy(remoteEP.Address.GetAddressBytes(), 0, connect, 4, 4);
Array.Copy(Encoding.ASCII.GetBytes(Username), 0, connect, 8, Username.Length);
connect[8 + Username.Length] = 0;
return connect;
}
///
/// Starts negotiating with the SOCKS server.
///
/// The host to connect to.
/// The port to connect to.
/// host is null.
/// port is invalid.
/// The proxy rejected the request.
/// An operating system error occurs while accessing the Socket.
/// The Socket has been closed.
public override void Negotiate(string host, int port) {
Negotiate(GetHostPortBytes(host, port));
}
///
/// Starts negotiating with the SOCKS server.
///
/// The IPEndPoint to connect to.
/// remoteEP is null.
/// The proxy rejected the request.
/// An operating system error occurs while accessing the Socket.
/// The Socket has been closed.
public override void Negotiate(IPEndPoint remoteEP) {
Negotiate(GetEndPointBytes(remoteEP));
}
///
/// Starts negotiating with the SOCKS server.
///
/// The bytes to send when trying to authenticate.
/// connect is null.
/// connect is too small.
/// The proxy rejected the request.
/// An operating system error occurs while accessing the Socket.
/// The Socket has been closed.
private void Negotiate(byte[] connect) {
if (connect == null)
throw new ArgumentNullException();
if (connect.Length < 2)
throw new ArgumentException();
if (Server.Send(connect) < connect.Length)
throw new SocketException(10054);
byte[] buffer = ReadBytes(8);
if (buffer[1] != 90) {
Server.Close();
throw new ProxyException("Negotiation failed.");
}
}
///
/// Starts negotiating asynchronously with a SOCKS proxy server.
///
/// The remote server to connect to.
/// The remote port to connect to.
/// The method to call when the connection has been established.
/// The IPEndPoint of the SOCKS proxy server.
/// An IAsyncProxyResult that references the asynchronous connection.
public override IAsyncProxyResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
ProtocolComplete = callback;
Buffer = GetHostPortBytes(host, port);
Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
AsyncResult = new IAsyncProxyResult();
return AsyncResult;
}
///
/// Starts negotiating asynchronously with a SOCKS proxy server.
///
/// An IPEndPoint that represents the remote device.
/// The method to call when the connection has been established.
/// The IPEndPoint of the SOCKS proxy server.
/// An IAsyncProxyResult that references the asynchronous connection.
public override IAsyncProxyResult BeginNegotiate(IPEndPoint remoteEP, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
ProtocolComplete = callback;
Buffer = GetEndPointBytes(remoteEP);
Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
AsyncResult = new IAsyncProxyResult();
return AsyncResult;
}
///
/// Called when the Socket is connected to the remote proxy server.
///
/// Stores state information for this asynchronous operation as well as any user-defined data.
private void OnConnect(IAsyncResult ar) {
try {
Server.EndConnect(ar);
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
Server.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnSent), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
///
/// Called when the Socket has sent the handshake data.
///
/// Stores state information for this asynchronous operation as well as any user-defined data.
private void OnSent(IAsyncResult ar) {
try {
HandleEndSend(ar, Buffer.Length);
} catch (Exception e) {
ProtocolComplete(e);
return;
}
try {
Buffer = new byte[8];
Received = 0;
Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
} catch (Exception e) {
ProtocolComplete(e);
}
}
///
/// Called when the Socket has received a reply from the remote proxy server.
///
/// Stores state information for this asynchronous operation as well as any user-defined data.
private void OnReceive(IAsyncResult ar) {
try {
HandleEndReceive(ar);
if (Received == 8) {
if (Buffer[1] == 90)
ProtocolComplete(null);
else {
Server.Close();
ProtocolComplete(new ProxyException("Negotiation failed."));
}
} else {
Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
}
} catch (Exception e) {
ProtocolComplete(e);
}
}
}
}