static void Main(string[] args) { // create a new ProxySocket ProxySocket s = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // set the proxy settings s.ProxyEndPoint = new IPEndPoint(IPAddress.Parse("10.0.0.5"), 1080); s.ProxyUser = "******"; s.ProxyPass = "******"; s.ProxyType = ProxyTypes.Socks5; // if you set this to ProxyTypes.None, // the ProxySocket will act as a normal Socket // connect to the remote server // (note that the proxy server will resolve the domain name for us) s.Connect("www.mentalis.org", 80); // send an HTTP request s.Send(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\nHost: www.mentalis.org\r\n\r\n")); // read the HTTP reply int recv = 0; byte [] buffer = new byte[1024]; recv = s.Receive(buffer); while (recv > 0) { Console.Write(Encoding.ASCII.GetString(buffer, 0, recv)); recv = s.Receive(buffer); } // wait until the user presses enter Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }
protected override Org.Mentalis.Network.ProxySocket.ProxySocket GetSocket() { if (socket == null) { socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.ProxyType = ProxyTypes.None; //socket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.SendTimeout, 3000); } return socket; }
protected override ProxySocket GetSocket() { if (socket == null) { socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.ProxyType = (ProxyTypes)(int)proxy.ProxyType; socket.ProxyEndPoint = QQPort.GetEndPoint(this.proxy.ProxyHost, this.proxy.ProxyPort); //socket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.SendTimeout, 3000); } return socket; }
public void Process() { var localEndPoint = (IPEndPoint)client.LocalEndPoint; var remoteEndPoint = (IPEndPoint)client.RemoteEndPoint; var connection = connectionTracker[new Connection(ProtocolType.Tcp, localEndPoint, remoteEndPoint)].Mirror; if (connection != null) { var initialEndPoint = connection.Source; var requestedEndPoint = connection.Destination; var tcpConnection = connectionTracker.GetTCPConnection(initialEndPoint, requestedEndPoint); var logMessage = string.Format("{0}[{1}] {2} {{0}} connection to {3}", tcpConnection != null ? tcpConnection.ProcessName : "unknown", tcpConnection != null ? tcpConnection.PID : 0, initialEndPoint, requestedEndPoint); try { var proxy = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); configureProxySocket(proxy, requestedEndPoint); debug.Log(1, logMessage + " via {1}", "requested", proxy.ProxyEndPoint); proxy.Connect(requestedEndPoint); SocketPump.Pump(client, proxy); proxy.Close(); debug.Log(1, logMessage, "closing"); } catch (Exception ex) { debug.Log(1, logMessage + ": {1}", "failed", ex.Message); } connectionTracker.QueueForCleanUp(connection); } else { var tcpConnection = connectionTracker.GetTCPConnection(remoteEndPoint, localEndPoint); debug.Log(1, "{0}[{1}] {2} has no mapping", tcpConnection != null ? tcpConnection.ProcessName : "unknown", tcpConnection != null ? tcpConnection.PID : 0, remoteEndPoint); client.Send(Encoding.ASCII.GetBytes("No mapping\r\n")); } client.Close(); }
/// <summary> /// Closes the connection /// </summary> public override void Close() { if (!this.IsDisposed) { try { this.Send(EndStream); } catch { } finally { if (this.tlsProceedEvent != null) { this.tlsProceedEvent.Set(); this.tlsProceedEvent = null; } if (this.networkStream != null) { this.networkStream.Dispose(); this.networkStream = null; } if (this.socket != null) { this.socket.Close(); this.socket = null; } if (this.inputBuffer != null) { this.inputBuffer.Dispose(); this.inputBuffer = null; } if (this.parser != null) { this.parser.Dispose(); this.parser = null; } } base.Close(); } }
protected override void ProcessQuery(string Query) { HeaderFields = ParseQuery(Query); if (HeaderFields == null || !HeaderFields.ContainsKey("Host")) { SendBadRequest(); return; } int Port; string Host; int Ret; if (HttpRequestType.ToUpper().Equals("CONNECT")) { //HTTPS Ret = RequestedPath.IndexOf(":"); if (Ret >= 0) { Host = RequestedPath.Substring(0, Ret); if (RequestedPath.Length > Ret + 1) Port = int.Parse(RequestedPath.Substring(Ret + 1)); else Port = 443; } else { Host = RequestedPath; Port = 443; } } else { //Normal HTTP Ret = ((string)HeaderFields["Host"]).IndexOf(":"); if (Ret > 0) { Host = ((string)HeaderFields["Host"]).Substring(0, Ret); Port = int.Parse(((string)HeaderFields["Host"]).Substring(Ret + 1)); } else { Host = (string)HeaderFields["Host"]; Port = 80; } if (HttpRequestType.ToUpper().Equals("POST")) { int index = Query.IndexOf("\r\n\r\n"); m_HttpPost = Query.Substring(index + 4); } } try { DestinationSocket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ((ProxySocket)DestinationSocket).ProxyEndPoint = new IPEndPoint(Config.SocksAddress, Config.SocksPort); ((ProxySocket)DestinationSocket).ProxyUser = Config.Username; ((ProxySocket)DestinationSocket).ProxyPass = Config.Password; ((ProxySocket)DestinationSocket).ProxyType = Config.ProxyType; if (HeaderFields.ContainsKey("Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive")) ((ProxySocket)DestinationSocket).SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); ((ProxySocket)DestinationSocket).BeginConnect(Host, Port, new AsyncCallback(this.OnProxyConnected), DestinationSocket); } catch { SendBadRequest(); return; } }
private SocksHttpWebResponse InternalGetResponse() { var response = new StringBuilder(); using (var _socksConnection = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { var proxyUri = Proxy.GetProxy(RequestUri); var ipAddress = GetProxyIpAddress(proxyUri); _socksConnection.ProxyEndPoint = new IPEndPoint(ipAddress, proxyUri.Port); _socksConnection.ProxyType = ProxyTypes.Socks5; // open connection _socksConnection.Connect(RequestUri.Host, 80); // send an HTTP request _socksConnection.Send(_correctEncoding.GetBytes(RequestMessage)); // read the HTTP reply var buffer = new byte[1024]; var bytesReceived = _socksConnection.Receive(buffer); while (bytesReceived > 0) { string chunk = _correctEncoding.GetString(buffer, 0, bytesReceived); string encString = EncodingHelper.GetEncodingFromChunk(chunk); if (!string.IsNullOrEmpty(encString)) { try { _correctEncoding = Encoding.GetEncoding(encString); } catch { //TODO: do something here } } response.Append(chunk); bytesReceived = _socksConnection.Receive(buffer); } } return new SocksHttpWebResponse(response.ToString(),_correctEncoding); }
static void Main(string[] args) { { // create a new ProxySocket ProxySocket s = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // set the proxy settings //s.ProxyEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9150); //s.ProxyUser = "******"; //s.ProxyPass = "******"; s.ProxyType = ProxyTypes.None; // if you set this to ProxyTypes.None, // the ProxySocket will act as a normal Socket // http://www.whatsmyip.org/ //<!-- Please DO NOT use our site to power an IP bot, script or other automated IP-lookup software! - for humans only! --> //<h1>Your IP Address is <span id="ip">169.120.138.139</span></h1> // connect to the remote server // (note that the proxy server will resolve the domain name for us) s.Connect("torguard.net", 80); // send an HTTP request s.Send(Encoding.ASCII.GetBytes("GET /whats-my-ip.php HTTP/1.0\r\nHost: torguard.net\r\n\r\n")); // read the HTTP reply int recv = 0; byte[] buffer = new byte[8096]; recv = s.Receive(buffer); while (recv > 0) { Console.Write(Encoding.ASCII.GetString(buffer, 0, recv)); recv = s.Receive(buffer); } } { // create a new ProxySocket ProxySocket s = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // set the proxy settings s.ProxyEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9150); //s.ProxyUser = "******"; //s.ProxyPass = "******"; s.ProxyType = ProxyTypes.Socks5; // if you set this to ProxyTypes.None, // the ProxySocket will act as a normal Socket // http://www.whatsmyip.org/ //<!-- Please DO NOT use our site to power an IP bot, script or other automated IP-lookup software! - for humans only! --> //<h1>Your IP Address is <span id="ip">169.120.138.139</span></h1> // connect to the remote server // (note that the proxy server will resolve the domain name for us) s.Connect("torguard.net", 80); // send an HTTP request s.Send(Encoding.ASCII.GetBytes("GET /whats-my-ip.php HTTP/1.0\r\nHost: torguard.net\r\n\r\n")); // read the HTTP reply int recv = 0; byte[] buffer = new byte[1024]; recv = s.Receive(buffer); while (recv > 0) { Console.Write(Encoding.ASCII.GetString(buffer, 0, recv)); recv = s.Receive(buffer); } } // wait until the user presses enter Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }
private void StopListening() { if (socketListener != null) { try { socketListener.Close(); } catch (Exception ex) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, GetType().ToString() + " Error: " + ex.Message); } socketListener = null; } }
/// <summary> /// Connect to the target through ConnectivitySettins. /// </summary> /// <exception cref="InvalidOperationException">Socket already connected.</exception> public override void Connect() { if (socket != null && Connected) { Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "Connect() called, but already a socket available.", GetType().Name); // If you have to fail, fail noisily and as soon as possible. throw new InvalidOperationException("Socket already connected."); } try { // Create a socket socket = GetPreparedSocket((ConnectivitySettings.LocalHost == string.Empty) ? IPAddress.Any : IPAddress.Parse(ConnectivitySettings.LocalHost), ConnectivitySettings.LocalPort); IPAddress hostIP = null; if (ConnectivitySettings.EndPoints != null && ConnectivitySettings.EndPoints.Length > 0) { int port = ConnectivitySettings.EndPoints[0].Port; IPAddress[] addresses = new IPAddress[ConnectivitySettings.EndPoints.Length]; for (int i = 0; i < addresses.Length; i++) { addresses[i] = ConnectivitySettings.EndPoints[i].Address; } ((ProxySocket)socket).BeginConnect(addresses, port, new AsyncCallback(EndConnectCallback), socket); } else if (IPAddress.TryParse(ConnectivitySettings.Host, out hostIP)) { // start connecting ((ProxySocket)socket).BeginConnect(new System.Net.IPEndPoint(IPAddress.Parse(ConnectivitySettings.Host), ConnectivitySettings.Port), new AsyncCallback(EndConnectCallback), socket); } else { ((ProxySocket)socket).BeginConnect(ConnectivitySettings.Host, ConnectivitySettings.Port, new AsyncCallback(EndConnectCallback), socket); } } catch (Exception e) { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Connecting exception: " + e.ToString(), GetType().Name); OnConnectingException(e); // re-throw the exception since the exception is thrown while in a blocking call throw; //RethrowToPreserveStackDetails (without e) } }
/// <summary> /// Opens the connection to the XMPP server. /// </summary> private void Connect() { try { if (this.ConnectionString.ResolveHostName) { base.ResolveHostName(); } IPAddress hostadd = Dns.GetHostEntry(this.HostName).AddressList[0]; IPEndPoint hostEndPoint = new IPEndPoint(hostadd, this.ConnectionString.PortNumber); this.socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (this.ConnectionString.UseProxy) { IPAddress proxyadd = Dns.GetHostEntry(this.ConnectionString.ProxyServer).AddressList[0]; IPEndPoint proxyEndPoint = new IPEndPoint(proxyadd, this.ConnectionString.ProxyPortNumber); switch (this.ConnectionString.ProxyType) { case "SOCKS4": this.socket.ProxyType = ProxyTypes.Socks4; break; case "SOCKS5": this.socket.ProxyType = ProxyTypes.Socks5; break; default: this.socket.ProxyType = ProxyTypes.None; break; } this.socket.ProxyEndPoint = proxyEndPoint; this.socket.ProxyUser = this.ConnectionString.ProxyUserName; if (!String.IsNullOrWhiteSpace(this.ConnectionString.ProxyPassword)) { this.socket.ProxyPass = this.ConnectionString.ProxyPassword; } } // Disables the Nagle algorithm for send coalescing. this.socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); // Make the socket to connect to the Server this.socket.Connect(hostEndPoint); // Create the Stream Instance this.networkStream = new NetworkStream(this.socket, false); } catch (Exception ex) { throw new XmppException(String.Format("Unable to connect to XMPP server {0}", this.ConnectionString.HostName), ex); } }
public virtual ProxySocket GetPreparedSocket(IPAddress address, int port) { //Creates the Socket for sending data over TCP. ProxySocket proxySocket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // incorporate the connection settings like proxy's // Note: ProxyType is in MSNPSharp namespace, ProxyTypes in ProxySocket namespace. if (ConnectivitySettings.ProxyType == ProxyType.None) { proxySocket.ProxyType = ProxyTypes.None; } else { // set the proxy type switch (ConnectivitySettings.ProxyType) { case ProxyType.Socks4: proxySocket.ProxyType = ProxyTypes.Socks4; break; case ProxyType.Socks5: proxySocket.ProxyType = ProxyTypes.Socks5; break; case ProxyType.Http: proxySocket.ProxyType = ProxyTypes.Http; break; } proxySocket.ProxyUser = ConnectivitySettings.ProxyUsername; proxySocket.ProxyPass = ConnectivitySettings.ProxyPassword; // resolve the proxy host if (proxyEndPoint == null) { bool worked = false; int retries = 0; Exception exp = null; //we retry a few times, because dns resolve failure is quite common do { try { System.Net.IPAddress ipAddress = Network.DnsResolve(ConnectivitySettings.ProxyHost); // assign to the connection object so other sockets can make use of it quickly proxyEndPoint = new IPEndPoint(ipAddress, ConnectivitySettings.ProxyPort); worked = true; } catch (Exception e) { retries++; exp = e; } } while (!worked && retries < 3); if (!worked) throw new ConnectivityException("DNS Resolve for the proxy server failed: " + ConnectivitySettings.ProxyHost + " failed.", exp); } proxySocket.ProxyEndPoint = proxyEndPoint; } //Send operations will timeout of confirmation is not received within 3000 milliseconds. proxySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 3000); //Socket will linger for 2 seconds after close is called. LingerOption lingerOption = new LingerOption(true, 2); proxySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption); try { proxySocket.Bind(new IPEndPoint(address, port)); } catch (SocketException ex) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "An error occured while trying to bind to a local address, error code: " + ex.ErrorCode + "."); } return proxySocket; }
/// <summary>同步发送数据 /// </summary> /// <param name="socket">The socket.</param> /// <param name="outPacket">The out packet.</param> protected virtual void SendData(ProxySocket socket, OutPacket outPacket) { try { ByteBuffer sendBuf = new ByteBuffer(); FillBytebuf(outPacket, sendBuf); socket.Send(sendBuf.ToByteArray(), 0, sendBuf.Length, SocketFlags.None); outPacket.DateTime = DateTime.Now; if (outPacket.NeedAck()) { outPacket.TimeOut = Utils.Util.GetTimeMillis(DateTime.Now) + QQGlobal.QQ_TIMEOUT_SEND; policy.PushResend(outPacket, this.Name); } } catch (Exception e) { policy.OnNetworkError(e); } }
private SocksHttpWebResponse InternalGetResponse() { MemoryStream data = null; string header = string.Empty; using (var _socksConnection = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { var proxyUri = Proxy.GetProxy(RequestUri); var ipAddress = GetProxyIpAddress(proxyUri); _socksConnection.ProxyEndPoint = new IPEndPoint(ipAddress, proxyUri.Port); _socksConnection.ProxyType = ProxyTypes.Socks5; // open connection _socksConnection.Connect(RequestUri.Host, 80); // send an HTTP request _socksConnection.Send(Encoding.UTF8.GetBytes(RequestMessage)); // read the HTTP reply var buffer = new byte[1024 * 4]; int bytesReceived = 0; bool headerDone = false; while ((bytesReceived = _socksConnection.Receive(buffer)) > 0) { if (!headerDone) { var headPart = Encoding.UTF8.GetString(buffer, 0, bytesReceived > 1024 ? 1024 : bytesReceived); var indexOfFirstBlankLine = headPart.IndexOf("\r\n\r\n"); if (indexOfFirstBlankLine > 0) { headPart = headPart.Substring(0, indexOfFirstBlankLine); header += headPart; headerDone = true; var headerPartLength = Encoding.UTF8.GetByteCount(headPart) + 4; // 0123456789 // ---- if (headerPartLength < bytesReceived) { data = new MemoryStream(); data.Write(buffer, headerPartLength, bytesReceived - headerPartLength); } } else { header += headPart; } } else { if (data == null) { data = new MemoryStream(); } data.Write(buffer, 0, bytesReceived); } } if (data != null) { data.Position = 0; } } return new SocksHttpWebResponse(data, header); }
/// <summary>异步发送数据 /// </summary> /// <param name="socket">The socket.</param> /// <param name="outPacket">The out packet.</param> protected virtual void BeginSendData(ProxySocket socket, OutPacket outPacket) { try { ByteBuffer sendBuf = new ByteBuffer(); FillBytebuf(outPacket, sendBuf); socket.BeginSend(sendBuf.ToByteArray(), 0, sendBuf.Length, SocketFlags.None, new AsyncCallback(EndSendData), outPacket); } catch (Exception e) { policy.OnNetworkError(e); } }
protected virtual void BeginDataReceive(ProxySocket socket) { if (this.socket == null || !this.socket.Connected) { return; } receiveBuf.Initialize(); socket.BeginReceive(receiveBuf, 0, receiveBuf.Length, SocketFlags.None, new AsyncCallback(EndDataReceive), socket); }
/// <summary> /// 连接到服务器 /// </summary> public bool Connect() { if (socket != null && socket.Connected) { return true; } int retry = 0; Connect: try { socket = GetSocket(); socket.Connect(epServer); BeginDataReceive(this.socket); return true; } catch (Exception e) { retry++; if (retry < 3) { goto Connect; } policy.OnConnectServerError(e); return false; } }
public HttpHandler(ProxySocket server, string user, string pass) : base(server, user) { m_Password = pass; }
/// <summary> /// Starts listening at the specified port in the connectivity settings. /// </summary> public void Listen(IPAddress address, int port) { ProxySocket socket = Processor.GetPreparedSocket(address, port); // Begin waiting for the incoming connection socket.Listen(1); // set this value so we know whether to send a handshake message or not later in the process isListener = true; socketListener = socket; SetupTimer(); socket.BeginAccept(new AsyncCallback(EndAcceptCallback), socket); }
/// <summary> /// 关闭连接 /// </summary> public void Close() { if (socket != null && socket.Connected) { ((IDisposable)socket).Dispose(); this.socket = null; } }
public override void Disconnect() { // clean up the socket properly if (socket != null) { ProxySocket pSocket = socket; socket = null; try { if (IsSocketConnected(pSocket)) { pSocket.Shutdown(SocketShutdown.Both); } } catch (Exception) { } finally { pSocket.Close(); } // We don't need to call OnDisconnect here since EndReceiveCallback will be call automatically later on. (This is not valid if disconnected remotelly) // We need to call OnDisconnect after EndReceiveCallback if disconnected locally. // We call Disconnect() when OnDisconnected event fired. } }
private static void ConfigureSocksProxy(ProxySocket proxySocket, IPEndPoint requestedEndPoint) { // TODO: Make this configurable proxySocket.ProxyType = ProxyTypes.Socks5; proxySocket.ProxyEndPoint = new IPEndPoint(IPAddress.Loopback, requestedEndPoint.Port == 443 ? 8000 : 1080); }