public ConnectionState(int instanceId, ProxyState proxyState, CommunicationState commState, string proxyType) { this.InstanceId = instanceId; this.ProxyState = proxyState; this.CommState = commState; this.ProxyType = proxyType; }
public void Run() { ProxyState proxyState = ProxyState.Initial; Int32 bytesRead; byte[] readBuffer = new byte[1024]; StringBuilder stringBuilder = new StringBuilder(); while (true) { logger.Log("Local: Reading"); bytesRead = stream.Read(readBuffer, 0, readBuffer.Length); if (bytesRead <= 0) { break; } stringBuilder.Append(Encoding.UTF8.GetString(readBuffer, 0, bytesRead)); int offset = 0; do { switch (proxyState) { case ProxyState.Initial: if (readBuffer[offset] == SocksProxy.ProxyVersion4) { offset++; proxyState = ProxyState.Version4; } else if (readBuffer[offset] == SocksProxy.ProxyVersion5) { offset++; proxyState = ProxyState.Version5; } else { throw new FormatException(String.Format("Expected Proxy Version 4 or 5, but got {0}", readBuffer[offset])); } break; case ProxyState.Version4: throw new NotImplementedException(); case ProxyState.Version5: throw new NotImplementedException(); default: throw new InvalidOperationException(String.Format("Unrecognized Proxy State '{0}' ({1})", proxyState, (int)proxyState)); } }while (offset < bytesRead); } while ((proxyState != ProxyState.Done) && stream.DataAvailable) { ; } }
private void HandleP00Login(C00PacketLogin packet) { Connect(); ProxyConnection.SendPacket(new S03Compression(256)); ProxyConnection.CompressionThreshold = 256; ProxyConnection.SendPacket(new S02LoginSuccessful(NormalizeUuid(parent.Token.PlayerID), parent.Token.PlayerName)); proxyState = ProxyState.Established; }
public ProxyServer() { state = ProxyState.None; serverSockets = new List <Socket>(); ipEndPoint = "127.0.0.1"; port = 8080; limit = 200; }
private static void SendToHTTPServer(IAsyncResult ar) { ProxyState back = (ProxyState)ar.AsyncState; int rec = back.incomingClient.EndRead(ar); //Push this content to the server back.ourSocket.Send(buffSend.Take(rec).ToArray()); back.incomingClient.BeginRead(buffSend, 0, buffSend.Length, new AsyncCallback(SendToHTTPServer), back); }
public ProxyState GetState() { RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", false); ProxyState result = GetRegistryState(registry); registry?.Close(); return(result); }
private void TransitionState(ProxyState nextState) { switch (nextState) { default: case ProxyState.Default: targetReticle.SetActive(true); EnableHandInteraction(activeHand); proxyManager.deleteProxyScene(); copyTo.SetActive(false); SetHandGlow(Color.white, leftHandGlow); SetHandGlow(Color.white, rightHandGlow); SetHandGlow(0, leftHandGlow); SetHandGlow(0, rightHandGlow); break; case ProxyState.Grabbed: targetReticle.SetActive(false); if (proxyManager.castGaze()) { // Prepare proxy (really tiny right now) originalProxyScale = copyTo.transform.localScale; originalProxyPosition = copyTo.transform.localPosition; copyTo.transform.localScale = Vector3.zero; copyTo.SetActive(true); // Reset and prepare glows SetHandGlow(0, leftHandGlow); SetHandGlow(0, rightHandGlow); SetHandGlow(Color.cyan); SetHandGlow(1); DisableHandInteraction(activeHand); // Debug.Log("Yea proxy"); } else { // Debug.Log("No proxy"); nextState = ProxyState.Default; // Force quit the gesture recognition } break; case ProxyState.Flipped: //copyTo.SetActive(true); // Now we grow and glow instead copyTo.transform.localScale = originalProxyScale; SetHandGlow(0); break; } // Debug.Log(nextState + ": " + (activeHand == leftHand ? "left" : "right")); curState = nextState; }
private void AddProxyState(object proxy, Action <object> init) { var state = new ProxyState { ConnectionId = string.Empty, InitialisationRoutine = init, InitLock = new object() }; m_ProxyState[proxy] = state; }
static void Receiver(IAsyncResult state) { //Console.WriteLine("Got into func"); ProxyState back = (ProxyState)state.AsyncState; int rec = back.ourSocket.EndReceive(state); //Console.WriteLine("Received from our socket: " + ASCIIEncoding.ASCII.GetString(buffReceive,0, rec)); back.incomingClient.Write(buffReceive, 0, rec); back.ourSocket.BeginReceive(buffReceive, 0, buffReceive.Length, SocketFlags.None, new AsyncCallback(Receiver), back); }
public void Start() { server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var endPoint = new IPEndPoint(IPAddress.Parse(ipEndPoint), port); server.Bind(endPoint); server.Listen(limit); server.BeginAccept(AcceptClient, null); state = ProxyState.Running; Console.WriteLine("Proxy Started"); }
private static void SendToHTTPServer(IAsyncResult ar) { try { ProxyState back = (ProxyState)ar.AsyncState; int rec = back.incomingClient.EndRead(ar); //Push this content to the server back.ourSocket.Send(back.SendBuffer.Take(rec).ToArray()); back.incomingClient.BeginRead(back.SendBuffer, 0, back.SendBuffer.Length, new AsyncCallback(SendToHTTPServer), back); } catch (Exception e) { Console.WriteLine("Exc. when sending to server: " + e.ToString()); } }
static void Receiver(IAsyncResult state) { try { ProxyState back = (ProxyState)state.AsyncState; int rec = back.ourSocket.EndReceive(state); //Set up the back and forth connections back.incomingClient.Write(back.ReceiveBuffer, 0, rec); back.ourSocket.BeginReceive(back.ReceiveBuffer, 0, back.ReceiveBuffer.Length, SocketFlags.None, new AsyncCallback(Receiver), back); } catch (Exception e) { Console.WriteLine("Exc. when receiving from client: " + e.ToString()); } }
public void Stop() { KillAllPendingSockets(); if (server.Connected) { server.Shutdown(SocketShutdown.Both); } server.Close(); server.Dispose(); state = ProxyState.Stopped; Console.WriteLine("Proxy Stopped"); Console.ReadLine(); }
public void SetConnectionState(int instanceId, ProxyState state) { lock (LockObj) { if(ConnectionInfo.ContainsKey(instanceId)) { ConnectionInfo[instanceId] = state; } else { ConnectionInfo.Add(instanceId, state); } } }
public static List <Proxy> GetByState(ProxyState proxyState) { EmptyParamContract.Validate(proxyState); List <Proxy> filtered = new List <Proxy>(); foreach (Proxy proxy in Proxies) { if (proxy.ProxyState == proxyState) { filtered.Add(proxy); } } return(filtered); }
private void Callback(object state) { ProxyState proxyState = ChangeContextMenuStripItemsByProxyState(); if (proxyState != _proxySwitcher.RequiredProxyState) { _proxySwitcher.Switch(_proxySwitcher.RequiredProxyState); ChangeContextMenuStripItemsByProxyState(); } if (_stopwatch.IsRunning && _stopwatch.Elapsed >= TimeSpan.FromMinutes(1)) { _timer?.Dispose(); _timer = null; _stopwatch.Stop(); } }
public void SetProxyViewSource() { ProxyState state = _proxySwitcher.GetState(); if (state == ProxyState.Enabled) { _buttonContent.Text = "Proxy Enabled"; _buttonContent.ButtonText = "Disable"; _buttonContent.TextColor = ButtonContent.BrushChartreuse; _buttonContent.ButtonTextColor = ButtonContent.BrushCrimson; } else if (state == ProxyState.Disabled) { _buttonContent.Text = "Proxy Disabled"; _buttonContent.ButtonText = "Enable"; _buttonContent.TextColor = ButtonContent.BrushCrimson; _buttonContent.ButtonTextColor = ButtonContent.BrushChartreuse; } }
public override async Task InvokeAsync(ClientActionContext context) { ProxyState proxyState = context.Proxy.State; if (context.Proxy == null) { throw new InvalidOperationException("Proxy object is not assigned."); } if (context.Proxy.State == ProxyState.Closed) { throw new ProxyClosedException("Proxy object is already closed."); } await Next(context).ConfigureAwait(false); if (proxyState == ProxyState.Ready) { (context.Proxy as IPipelineCallback)?.ChangeState(ProxyState.Open); } }
private ProxyState ChangeContextMenuStripItemsByProxyState() { ProxyState state = _proxySwitcher.GetState(); if (state == ProxyState.Disabled) { _notifyIcon.ContextMenuStrip.Items[0].Text = "Enable proxy"; _notifyIcon.Icon = ProxyBoss.Properties.Resources.AppIconDisabled; } else if (state == ProxyState.Enabled) { _notifyIcon.ContextMenuStrip.Items[0].Text = "Disable proxy"; _notifyIcon.Icon = ProxyBoss.Properties.Resources.AppIconEnabled; } if (_timer == null) { CreateTimer(); } return(state); }
public void Switch(ProxyState state) { RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); //ProxyState result = GetRegistryState(registry); switch (state) { case ProxyState.Disabled: Disable(registry); break; case ProxyState.Enabled: Enable(registry); break; } registry?.Close(); bool settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); bool refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); _proxyState = state; }
/// <summary> /// Gets the URL for the specified service by using WS-Inspection. /// </summary> /// <param name="host">Address and optionally port of the host server.</param> /// <param name="serviceName">Service name to find URL for.</param> /// <param name="user">The user to be authenticated.</param> /// <param name="password">The password of the user.</param> /// <returns>A URL that references the specified service.</returns> static public Uri GetServiceUrl(string host, string serviceName, string user, string password) { Uri serviceUrl = null; HttpWebResponse response = null; CookieContainer cks = new CookieContainer(); // Build a credential from the user name and password. NetworkCredential myCred = new NetworkCredential(user, password); // Parse the host string to see if it is a complete uri. Uri tempUri; try { if (host.StartsWith(Uri.UriSchemeHttp) || host.StartsWith(Uri.UriSchemeHttps)) { tempUri = new Uri(host.TrimEnd(new char[] { '/' }) + WSInspectionDocument); } else { tempUri = new Uri(Uri.UriSchemeHttp + Uri.SchemeDelimiter + host.TrimEnd(new char[] { '/' }) + WSInspectionDocument); } } catch { tempUri = new Uri(Uri.UriSchemeHttp + Uri.SchemeDelimiter + host.TrimEnd(new char[] { '/' }) + WSInspectionDocument); } // Create the web request. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tempUri); bool retry = true; proxyRetry: request.Credentials = myCred; request.Timeout = 15 * 1000; request.CookieContainer = cks; request.Proxy = ProxyState.GetProxyState(request.RequestUri); try { // Get the response from the web server. response = request.GetResponse() as HttpWebResponse; // Mono has a bug where it doesn't set the cookies in the cookie jar. if (response != null) { cks.Add(response.Cookies); } //cks.Add(response.Cookies); } catch (WebException we) { IsTrustFailure(host, we); if ((we.Status == WebExceptionStatus.Timeout) || (we.Status == WebExceptionStatus.NameResolutionFailure)) { throw we; } else { response = we.Response as HttpWebResponse; if (response != null) { // Mono has a bug where it doesn't set the cookies in the cookie jar. cks.Add(response.Cookies); if (response.StatusCode == HttpStatusCode.Unauthorized && retry == true) { // This should be a free call we must be behind iChain. request = (HttpWebRequest)WebRequest.Create(response.ResponseUri); retry = false; goto proxyRetry; } } response = null; } } // Make sure that there was an answer. if (response != null) { try { // Get the stream associated with the response. Stream receiveStream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); try { XmlDocument document = new XmlDocument(); document.Load(readStream); //Create an XmlNamespaceManager for resolving namespaces. XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); nsmgr.AddNamespace("wsil", document.DocumentElement.NamespaceURI); // Search for the named service element. XmlNode serviceNode = document.DocumentElement.SelectSingleNode(WSIL_ServiceTag + "[" + WSIL_NameTag + "='" + "Domain Service" + "']", nsmgr); if (serviceNode != null) { // Get the description node. XmlElement description = serviceNode[WSIL_DescriptionTag]; if (description != null) { // Get the uri location. string uriString = description.GetAttribute(WSIL_LocationAttrTag); if (uriString != null) { // Fix up the URI if it is relative. if (!uriString.ToLower().StartsWith(Uri.UriSchemeHttp)) { Uri respUri = response.ResponseUri; UriBuilder urb = new UriBuilder(respUri.Scheme, respUri.Host, respUri.Port, uriString.TrimStart(new char[] { '/' })); serviceUrl = urb.Uri; // Check to see if we need to use ssl. // Make the request and see if we get redirected 302; // Create the web request. request = (HttpWebRequest)WebRequest.Create(serviceUrl); request.CookieContainer = cks; request.Proxy = ProxyState.GetProxyState(request.RequestUri); response.Close(); try { response = request.GetResponse() as HttpWebResponse; serviceUrl = response.ResponseUri; } catch (WebException wex) { IsTrustFailure(host, wex); response = wex.Response as HttpWebResponse; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized) { if (response.Headers.Get("Simias-Error") != null) { // This is expected because this service requires authentication. serviceUrl = response.ResponseUri; } } } } } else { serviceUrl = new Uri(uriString); } } } } } finally { readStream.Close(); } } finally { if (response != null) { response.Close(); } } } return(serviceUrl); }
void IPipelineCallback.ChangeState(ProxyState newState) { State = newState; }
private static void StartAcceptingClient(IAsyncResult ar) { var tcpClient = server.EndAcceptTcpClient(ar); server.BeginAcceptTcpClient(new AsyncCallback(StartAcceptingClient), null); // Read the data stream from the client. NetworkStream stream = tcpClient.GetStream(); byte[] buffer = new byte[256]; Console.WriteLine("====== GOT A NEW TCP CLIENT ====== " + tcpClient.Client.RemoteEndPoint.ToString()); int read = stream.Read(buffer, 0, 1); MemoryStream saved = new MemoryStream(); saved.Write(buffer, 0, read); bool isValid = false; while (read > 0) { read = stream.Read(buffer, 0, 1); saved.Write(buffer, 0, read); //Check if the last four bytes were a double \r\n. var aBytes = saved.ToArray(); int len = aBytes.Length; if (aBytes.Length >= 4 && aBytes[len - 1] == '\n' && aBytes[len - 2] == '\r' && aBytes[len - 3] == '\n' && aBytes[len - 4] == '\r') { isValid = true; break; } } Console.WriteLine("End of receive."); string originalRequest = Encoding.ASCII.GetString(saved.ToArray()); byte[] origBytes = saved.ToArray(); saved.Close(); Console.WriteLine(originalRequest); if (!isValid) { Console.WriteLine("This wasn't a valid request"); return; } //Find the hoster and do our own request. string host = originalRequest.Split(new char[] { '\n' }).First(line => line.StartsWith("Host:")); host = host.Substring(5).Trim(); //Cut of rest. Console.WriteLine("The host is: " + host); //Do our own request. try { Socket sProxy = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sProxy.Connect(host, 80); sProxy.Send(origBytes); //Now route everything between the tcpclient and this socket... //create the state object var state = new ProxyState() { ourSocket = sProxy, incomingClient = stream }; sProxy.BeginReceive(state.ReceiveBuffer, 0, state.ReceiveBuffer.Length, SocketFlags.None, new AsyncCallback(Receiver), state); stream.BeginRead(state.SendBuffer, 0, state.SendBuffer.Length, new AsyncCallback(SendToHTTPServer), state); } catch (Exception) { Console.WriteLine("Exception while doing our own request"); } }
private void StopProxy() { this.ProxyState = ProxyState.stopped; ProxyStateChanged(); }
public static void Main(string[] args) { TcpListener server = null; try { // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("0.0.0.0"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); Console.WriteLine("Server started on " + server.LocalEndpoint.ToString()); while (true) { Thread.Sleep(10); // Create a TCP socket. TcpClient tcpClient = server.AcceptTcpClient(); // Read the data stream from the client. NetworkStream stream = tcpClient.GetStream(); byte[] buffer = new byte[256]; Console.WriteLine("Start receiving content"); int read = stream.Read(buffer, 0, buffer.Length); MemoryStream saved = new MemoryStream(); saved.Write(buffer, 0, read); while (read > 0) { read = stream.Read(buffer, 0, buffer.Length); saved.Write(buffer, 0, read); //Check if the last four bytes were a double \r\n. var aBytes = saved.ToArray(); int len = aBytes.Length; if (aBytes.Length >= 4 && aBytes[len - 1] == '\n' && aBytes[len - 2] == '\r' && aBytes[len - 3] == '\n' && aBytes[len - 4] == '\r') { break; } } Console.WriteLine("End of receive."); string originalRequest = Encoding.ASCII.GetString(saved.ToArray()); byte[] origBytes = saved.ToArray(); Console.WriteLine(originalRequest); //Find the hoster and do our own request. string host = originalRequest.Split(new char[] { '\n' }).First(line => line.StartsWith("Host:")); host = host.Substring(5).Trim(); //Cut of rest. Console.WriteLine("The host is: " + host); //Do our own request. try { Socket sProxy = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sProxy.Connect(host, 80); sProxy.Send(origBytes); //Now route everything between the tcpclient and this socket... //create the state object var state = new ProxyState() { ourSocket = sProxy, incomingClient = stream }; sProxy.BeginReceive(buffReceive, 0, buffReceive.Length, SocketFlags.None, new AsyncCallback(Receiver), state); stream.BeginRead(buffSend, 0, buffSend.Length, new AsyncCallback(SendToHTTPServer), state); } catch (Exception) { Console.WriteLine("Exception while doing our own request"); } } } catch (Exception) { Console.WriteLine("Setting up the server failed"); } }
private void StartProxy() { this.ProxyState = ProxyState.running; ProxyStateChanged(); }
private void HandleP00Handshake(C00PacketHandshake packet) { proxyState = (ProxyState)packet.nextState; }
public void ChangeState(IProxy proxy, ProxyState state) { State = state; (proxy as IPipelineCallback)?.ChangeState(state); }
public ProxySwitcher() { _proxyState = GetState(); }