internal byte[] TakeEntity() { byte[] bytes; if (this.iEntityBodyOffset < 0) { throw new InvalidDataException("Request Entity Body Offset must not be negative"); } long num = this.m_requestData.Length - this.iEntityBodyOffset; long num2 = this._calculateExpectedEntityTransferSize(); if (num > num2) { //KProxyApplication.Log.LogFormat("HTTP Pipelining Client detected; excess data on client socket for session #{0}.", new object[] { this.m_session.id }); try { bytes = new byte[num - num2]; this.m_requestData.Position = this.iEntityBodyOffset + num2; this.m_requestData.Read(bytes, 0, bytes.Length); } catch (OutOfMemoryException exception) { KProxyApplication.ReportException(exception, "HTTP Request Pipeline Too Large"); bytes = Encoding.ASCII.GetBytes("Kavprot Proxy: Out of memory"); this.m_session.PoisonClientPipe(); return(new byte[0]); } this.pipeClient.putBackSomeBytes(bytes); num = num2; } if ((num != num2) && (num < num2)) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, true, string.Format("Content-Length mismatch: Request Header indicated {0:N0} bytes, but client sent {1:N0} bytes.", num2, num)); } try { bytes = new byte[num]; this.m_requestData.Position = this.iEntityBodyOffset; this.m_requestData.Read(bytes, 0, bytes.Length); } catch (OutOfMemoryException exception2) { KProxyApplication.ReportException(exception2, "HTTP Request Too Large"); bytes = Encoding.ASCII.GetBytes("Kavprot Proxy: Out of memory"); this.m_session.PoisonClientPipe(); } this._freeRequestData(); return(bytes); }
private void _NotifyThreadExecute(object objThreadState) { PrefChangeEventArgs e = (PrefChangeEventArgs)objThreadState; string prefName = e.PrefName; List <EventHandler <PrefChangeEventArgs> > list = null; try { GetReaderLock(this._RWLockWatchers); try { foreach (PrefWatcher watcher in this._listWatchers) { if (prefName.StartsWith(watcher.sPrefixToWatch, StringComparison.Ordinal)) { if (list == null) { list = new List <EventHandler <PrefChangeEventArgs> >(); } list.Add(watcher.fnToNotify); } } } finally { FreeReaderLock(this._RWLockWatchers); } if (list != null) { foreach (EventHandler <PrefChangeEventArgs> handler in list) { try { handler(this, e); } catch (Exception exception) { KProxyApplication.ReportException(exception); } } } } catch (Exception exception2) { KProxyApplication.ReportException(exception2); } }
internal static bool exportRootToDesktop() { try { byte[] bytes = getRootCertBytes(); if (bytes != null) { File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ASRoot.cer", bytes); return(true); } } catch (Exception exception) { KProxyApplication.ReportException(exception); return(false); } return(false); }
internal byte[] TakeEntity() { byte[] bytes; try { bytes = new byte[this.m_responseData.Length - this.iEntityBodyOffset]; this.m_responseData.Position = this.iEntityBodyOffset; this.m_responseData.Read(bytes, 0, bytes.Length); } catch (OutOfMemoryException exception) { KProxyApplication.ReportException(exception, "HTTP Response Too Large"); bytes = Encoding.ASCII.GetBytes("Kavprot Proxy: Out of memory"); this.m_session.PoisonServerPipe(); } this.FreeResponseDataBuffer(); return(bytes); }
private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e) { try { DNSResolver.ClearCache(); //KProxyApplication.Log.LogString("NetworkAddressChanged."); if (this.oAutoProxy != null) { this.oAutoProxy.iAutoProxySuccessCount = 0; } if ((KPCONFIG.bForwardToGateway && (this.piPrior != null)) && this.piPrior.bUseManualProxies) { this._DetermineGatewayIPEndPoints(); } } catch (Exception exception) { KProxyApplication.ReportException(exception); } }
private void RunTunnel() { if (KProxyApplication.oProxy != null) { try { IPEndPoint ipepForwardHTTPS = null; if (this._mySession.oFlags["x-overrideGateway"] != null) { if (string.Equals("DIRECT", this._mySession.oFlags["x-overrideGateway"], StringComparison.OrdinalIgnoreCase)) { this._mySession.bypassGateway = true; } else { ipepForwardHTTPS = Utilities.IPEndPointFromHostPortString(this._mySession.oFlags["x-overrideGateway"]); } } else if (!this._mySession.bypassGateway) { int tickCount = Environment.TickCount; ipepForwardHTTPS = KProxyApplication.oProxy.FindGatewayForOrigin("https", this._mySession.oFlags["x-overrideHost"] ?? this._mySession.PathAndQuery); this._mySession.Timers.GatewayDeterminationTime = Environment.TickCount - tickCount; } if (ipepForwardHTTPS != null) { this.TunnelToGateway(ipepForwardHTTPS); } else { this.TunnelDirectly(); } } catch (Exception exception) { KProxyApplication.ReportException(exception, "Uncaught Exception in Tunnel; Session #" + this._mySession.id.ToString()); } } }
internal ServerPipe DequeuePipe(string sPoolKey, int iPID, int HackiForSession) { Queue <ServerPipe> queue; ServerPipe pipe; Queue <ServerPipe> queue2; if (!KPCONFIG.bReuseServerSockets) { return(null); } lock (this.thePool) { if ((((iPID == 0) || !this.thePool.TryGetValue(string.Format("PID{0}*{1}", iPID, sPoolKey), out queue)) || (queue.Count < 1)) && (!this.thePool.TryGetValue(sPoolKey, out queue) || (queue.Count < 1))) { return(null); } } Monitor.Enter(queue2 = queue); try { if (queue.Count == 0) { return(null); } pipe = queue.Dequeue(); } catch (Exception exception) { KProxyApplication.ReportException(exception); return(null); } finally { Monitor.Exit(queue2); } return(pipe); }
internal bool ReadRequest() { if (this.m_requestData != null) { KProxyApplication.ReportException(new InvalidOperationException("ReadRequest called after requestData was null'd.")); return(false); } if (this.pipeClient == null) { KProxyApplication.ReportException(new InvalidOperationException("ReadRequest called after pipeClient was null'd.")); return(false); } this.m_requestData = new MemoryStream(0x1000); this.pipeClient.IncrementUse(0); this.m_session.SetBitFlag(SessionFlags.ClientPipeReused, this.pipeClient.iUseCount > 1); this.pipeClient.setReceiveTimeout(); int iMaxByteCount = 0; bool flag = false; bool flag2 = false; byte[] arrBuffer = new byte[_cbClientReadBuffer]; do { try { iMaxByteCount = this.pipeClient.Receive(arrBuffer); } catch (Exception exception) { KProxyApplication.DebugSpew("ReadRequest Failure: " + exception.Message); flag = true; } if (iMaxByteCount <= 0) { flag2 = true; KProxyApplication.DebugSpew("ReadRequest read 0 bytes!!!!!"); } else { if (KPCONFIG.bDebugSpew) { KProxyApplication.DebugSpew("READ FROM: " + this.pipeClient.ToString() + ":\n" + Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount)); } if (this.m_requestData.Length == 0L) { this.m_session.Timers.ClientBeginRequest = DateTime.Now; int index = 0; while ((index < iMaxByteCount) && ((arrBuffer[index] == 13) || (arrBuffer[index] == 10))) { index++; } this.m_requestData.Write(arrBuffer, index, iMaxByteCount - index); } else { this.m_requestData.Write(arrBuffer, 0, iMaxByteCount); } } }while ((!flag2 && !flag) && !this.isRequestComplete()); arrBuffer = null; if (flag || (this.m_requestData.Length == 0L)) { if ((this.pipeClient.iUseCount < 2) || (this.pipeClient.bIsSecured && (this.pipeClient.iUseCount < 3))) { //KProxyApplication.Log.LogFormat("[Kavprot Proxy] Failed to read {0} request from ({1}) new client socket, port {2}.", new object[] { this.pipeClient.bIsSecured ? "HTTPS" : "HTTP", this.m_session.oFlags["X-ProcessInfo"], this.m_session.oFlags["X-CLIENTPORT"] }); } this._freeRequestData(); return(false); } if ((this.m_headers == null) || (this.m_session.state >= SessionStates.Done)) { this._freeRequestData(); return(false); } if ("CONNECT" == this.m_headers.HTTPMethod) { this.m_session.isTunnel = true; this.m_sHostFromURI = this.m_session.PathAndQuery; } if (this.m_sHostFromURI != null) { if (this.m_headers.Exists("Host") && !Utilities.areOriginsEquivalent(this.m_sHostFromURI, this.m_headers["Host"], (this.m_session.isTunnel || this.m_session.isHTTPS) ? 0x1bb : (this.m_session.isFTP ? 0x15 : 80))) { this.m_session.oFlags["X-Original-Host"] = this.m_headers["Host"]; this.m_headers["Host"] = this.m_sHostFromURI; } else if (!this.m_headers.Exists("Host")) { if (this.m_headers.HTTPVersion.Equals("HTTP/1.1", StringComparison.OrdinalIgnoreCase)) { this.m_session.oFlags["X-Original-Host"] = string.Empty; } this.m_headers["Host"] = this.m_sHostFromURI; } this.m_sHostFromURI = null; } if (!this.m_headers.Exists("Host")) { this._freeRequestData(); return(false); } return(true); }
internal bool Start(int iPort, bool bAllowRemote) { if (KPCONFIG.bIsViewOnly) { return(false); } bool flag = false; try { flag = (bAllowRemote && KPCONFIG.bEnableIPv6) && Socket.OSSupportsIPv6; } catch (Exception exception) { KProxyApplication.DoNotifyUser(string.Concat(new object[] { "A Microsoft .NET configuration file (listed below) is corrupt and contains invalid data. You can often correct this error by installing updates from WindowsUpdate and/or reinstalling the .NET Framework.\n\n", exception.Message, "\nSource: ", exception.Source, "\n", exception.StackTrace, "\n\n", exception.InnerException, "\nKProxy v", Application.ProductVersion, (8 == IntPtr.Size) ? " (x64) " : " (x86) ", " [.NET ", Environment.Version, " on ", Environment.OSVersion.VersionString, "] " }), ".NET Configuration Error", MessageBoxIcon.Hand); this.oAcceptor = null; return(false); } try { if (flag) { this.oAcceptor = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); if (Environment.OSVersion.Version.Major > 5) { this.oAcceptor.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation | SocketOptionName.KeepAlive, 0); } } else { this.oAcceptor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } if (KPCONFIG.ForceExclusivePort) { this.oAcceptor.ExclusiveAddressUse = true; } if (bAllowRemote) { if (flag) { this.oAcceptor.Bind(new IPEndPoint(IPAddress.IPv6Any, iPort)); } else { this.oAcceptor.Bind(new IPEndPoint(IPAddress.Any, iPort)); } } else { this.oAcceptor.Bind(new IPEndPoint(IPAddress.Loopback, iPort)); } this.oAcceptor.Listen(50); } catch (SocketException exception2) { string str = string.Empty; string sTitle = "KProxy Cannot Listen"; switch (exception2.ErrorCode) { case 0x273f: case 0x2741: if (flag) { str = "\nThis often means that you've enabled IPv6 support inside Tools > Kavprot Proxy Options, but your computer has IPv6 disabled."; } break; case 0x2740: case 0x271d: str = "\nThis is usually due to another service running on this port. Run NETSTAT -A at a command prompt.\nIf you don't want to stop using the other program, simply change the port used by KProxy.\nClick Tools > KProxy Options > Connections, select a new port, and restart KProxy."; sTitle = "Kavprot Proxy Port in Use"; break; } this.oAcceptor = null; KProxyApplication.DoNotifyUser(string.Format("Unable to bind to port [Localhost:{0}]. ErrorCode: {1}.\n{2}\n\n{3}\n\n{4}", new object[] { KPCONFIG.ListenPort, exception2.ErrorCode, str, exception2.ToString(), string.Concat(new object[] { "KProxy v", Application.ProductVersion, " [.NET ", Environment.Version, " on ", Environment.OSVersion.VersionString, "]" }) }), sTitle, MessageBoxIcon.Hand); return(false); } catch (Exception exception3) { this.oAcceptor = null; KProxyApplication.ReportException(exception3); return(false); } try { this.oAcceptor.BeginAccept(new AsyncCallback(this.AcceptConnection), null); } catch (Exception exception4) { this.oAcceptor = null; //KProxyApplication.Log.LogFormat("Kavprot Proxy BeginAccept() Exception: {0}", new object[] { exception4.Message }); return(false); } return(true); }
internal bool ReadResponse() { int iMaxByteCount = 0; bool flag = false; bool flag2 = false; bool flag3 = false; byte[] arrBuffer = new byte[_cbServerReadBuffer]; do { try { iMaxByteCount = this.pipeServer.Receive(arrBuffer); if (0L == this.m_session.Timers.ServerBeginResponse.Ticks) { this.m_session.Timers.ServerBeginResponse = DateTime.Now; } if (iMaxByteCount <= 0) { flag = true; KProxyApplication.DoReadResponseBuffer(this.m_session, arrBuffer, 0); } else { if (KPCONFIG.bDebugSpew) { KProxyApplication.DebugSpew(Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount)); } if (!KProxyApplication.DoReadResponseBuffer(this.m_session, arrBuffer, iMaxByteCount)) { flag2 = true; } this.m_responseData.Write(arrBuffer, 0, iMaxByteCount); this.m_responseTotalDataCount += iMaxByteCount; if ((this.m_inHeaders == null) && this.GetHeaders()) { this.m_session.Timers.KProxyGotResponseHeaders = DateTime.Now; if ((this.m_session.state == SessionStates.Aborted) && this.m_session.isAnyFlagSet(SessionFlags.ProtocolViolationInResponse)) { return(false); } KProxyApplication.DoResponseHeadersAvailable(this.m_session); if (KPCONFIG.bStreamAudioVideo) { string str = this.m_inHeaders["Content-Type"]; if ((str.StartsWith("video/", StringComparison.OrdinalIgnoreCase) || str.StartsWith("audio/", StringComparison.OrdinalIgnoreCase)) || str.StartsWith("application/x-mms-framed", StringComparison.OrdinalIgnoreCase)) { this.m_session.bBufferResponse = false; } } if (!this.m_session.bBufferResponse) { this.m_session.bBufferResponse = this.m_session.HTTPMethodIs("CONNECT"); } if (!this.m_session.bBufferResponse && (this.m_session.oRequest.pipeClient == null)) { this.m_session.bBufferResponse = true; } if ((!this.m_session.bBufferResponse && ((0x191 == this.m_inHeaders.HTTPResponseCode) || (0x197 == this.m_inHeaders.HTTPResponseCode))) && this.m_session.oFlags.ContainsKey("x-AutoAuth")) { this.m_session.bBufferResponse = true; } this.m_session.SetBitFlag(SessionFlags.ResponseStreamed, !this.m_session.bBufferResponse); if (!this.m_session.bBufferResponse) { if (this.m_session.oFlags.ContainsKey("response-trickle-delay")) { int num2 = int.Parse(this.m_session.oFlags["response-trickle-delay"]); this.m_session.oRequest.pipeClient.TransmitDelay = num2; } if (this.m_session.oFlags.ContainsKey("log-drop-response-body") || KProxyApplication.Prefs.GetBoolPref("KProxy.network.streaming.ForgetStreamedData", false)) { flag3 = true; } } } if ((this.m_inHeaders != null) && this.m_session.isFlagSet(SessionFlags.ResponseStreamed)) { this.LeakResponseBytes(); if (flag3) { this.m_session.SetBitFlag(SessionFlags.ResponseBodyDropped, true); if (this._lngLastChunkInfoOffset > -1L) { this.ReleaseStreamedChunkedData(); } else if (this.m_inHeaders.ExistsAndContains("Transfer-Encoding", "chunked")) { this.ReleaseStreamedChunkedData(); } else { this.ReleaseStreamedData(); } } } } } catch (Exception exception) { flag2 = true; if (exception is OperationCanceledException) { this.m_session.state = SessionStates.Aborted; } else if (exception is OutOfMemoryException) { KProxyApplication.ReportException(exception); this.m_session.state = SessionStates.Aborted; } else { } } }while ((!flag && !flag2) && ((this.m_inHeaders == null) || !this.isResponseBodyComplete())); this.m_session.Timers.ServerDoneResponse = DateTime.Now; if (this.m_session.isFlagSet(SessionFlags.ResponseStreamed)) { this.m_session.Timers.ClientDoneResponse = this.m_session.Timers.ServerDoneResponse; } if ((this.m_responseTotalDataCount == 0L) && (this.m_inHeaders == null)) { flag2 = true; } arrBuffer = null; if (flag2) { this.m_responseData.Dispose(); this.m_responseData = null; return(false); } if (this.m_inHeaders == null) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, true, true, "The Server did not return properly formatted HTTP Headers. Maybe missing altogether (e.g. HTTP/0.9), maybe only \\r\\r instead of \\r\\n\\r\\n?\n"); this.m_session.SetBitFlag(SessionFlags.ResponseStreamed, false); this.m_inHeaders = new HTTPResponseHeaders(KPCONFIG.oHeaderEncoding); this.m_inHeaders.HTTPVersion = "HTTP/1.0"; this.m_inHeaders.HTTPResponseCode = 200; this.m_inHeaders.HTTPResponseStatus = "200 This buggy server did not return headers"; this.iEntityBodyOffset = 0; return(true); } return(true); }
public bool GetFromWinINET(string sConnectionName) { this.Clear(); try { INTERNET_PER_CONN_OPTION_LIST structure = new INTERNET_PER_CONN_OPTION_LIST(); INTERNET_PER_CONN_OPTION[] internet_per_conn_optionArray = new INTERNET_PER_CONN_OPTION[5]; if (sConnectionName == "DefaultLAN") { sConnectionName = null; } structure.Connection = sConnectionName; structure.OptionCount = internet_per_conn_optionArray.Length; structure.OptionError = 0; internet_per_conn_optionArray[0] = new INTERNET_PER_CONN_OPTION(); internet_per_conn_optionArray[0].dwOption = 1; internet_per_conn_optionArray[1] = new INTERNET_PER_CONN_OPTION(); internet_per_conn_optionArray[1].dwOption = 2; internet_per_conn_optionArray[2] = new INTERNET_PER_CONN_OPTION(); internet_per_conn_optionArray[2].dwOption = 3; internet_per_conn_optionArray[3] = new INTERNET_PER_CONN_OPTION(); internet_per_conn_optionArray[3].dwOption = 4; internet_per_conn_optionArray[4] = new INTERNET_PER_CONN_OPTION(); internet_per_conn_optionArray[4].dwOption = 10; int cb = 0; for (int i = 0; i < internet_per_conn_optionArray.Length; i++) { cb += Marshal.SizeOf(internet_per_conn_optionArray[i]); } IntPtr ptr = Marshal.AllocCoTaskMem(cb); IntPtr ptr2 = ptr; for (int j = 0; j < internet_per_conn_optionArray.Length; j++) { Marshal.StructureToPtr(internet_per_conn_optionArray[j], ptr2, false); ptr2 = (IntPtr)(((long)ptr2) + Marshal.SizeOf(internet_per_conn_optionArray[j])); } structure.pOptions = ptr; structure.Size = Marshal.SizeOf(structure); int size = structure.Size; bool flag = InternetQueryOptionList(IntPtr.Zero, 0x4b, ref structure, ref size); int num5 = Marshal.GetLastWin32Error(); if (!flag && (0x57 == num5)) { internet_per_conn_optionArray[4].dwOption = 5; ptr2 = ptr; for (int k = 0; k < internet_per_conn_optionArray.Length; k++) { Marshal.StructureToPtr(internet_per_conn_optionArray[k], ptr2, false); ptr2 = (IntPtr)(((long)ptr2) + Marshal.SizeOf(internet_per_conn_optionArray[k])); } structure.pOptions = ptr; structure.Size = Marshal.SizeOf(structure); size = structure.Size; flag = InternetQueryOptionList(IntPtr.Zero, 0x4b, ref structure, ref size); num5 = Marshal.GetLastWin32Error(); } if (flag) { ptr2 = ptr; for (int m = 0; m < internet_per_conn_optionArray.Length; m++) { Marshal.PtrToStructure(ptr2, internet_per_conn_optionArray[m]); ptr2 = (IntPtr)(((long)ptr2) + Marshal.SizeOf(internet_per_conn_optionArray[m])); } this._bDirect = 1 == (internet_per_conn_optionArray[0].Value.dwValue & 1); this._bUseConfigScript = 4 == (internet_per_conn_optionArray[0].Value.dwValue & 4); this._bAutoDetect = 8 == (internet_per_conn_optionArray[0].Value.dwValue & 8); this._bProxiesSpecified = 2 == (internet_per_conn_optionArray[0].Value.dwValue & 2); if (internet_per_conn_optionArray[4].dwOption == 10) { this._bAutoDetectWasUserSet = 8 == (internet_per_conn_optionArray[4].Value.dwValue & 8); } else { this._bAutoDetectWasUserSet = this._bAutoDetect && (1 == (internet_per_conn_optionArray[4].Value.dwValue & 1)); } this._sScriptURL = Marshal.PtrToStringAnsi(internet_per_conn_optionArray[3].Value.pszValue); Utilities.GlobalFree(internet_per_conn_optionArray[3].Value.pszValue); if (internet_per_conn_optionArray[1].Value.pszValue != IntPtr.Zero) { string sProxyString = Marshal.PtrToStringAnsi(internet_per_conn_optionArray[1].Value.pszValue); Utilities.GlobalFree(internet_per_conn_optionArray[1].Value.pszValue); this.InitializeFromProxyString(sProxyString); } if (internet_per_conn_optionArray[2].Value.pszValue != IntPtr.Zero) { this._sHostsThatBypass = Marshal.PtrToStringAnsi(internet_per_conn_optionArray[2].Value.pszValue); Utilities.GlobalFree(internet_per_conn_optionArray[2].Value.pszValue); this._bBypassIntranetHosts = this._sHostsThatBypass.Contains("<local>"); } } Marshal.FreeCoTaskMem(ptr); return(flag); } catch (Exception exception) { KProxyApplication.ReportException(exception, "Unable to get proxy information for " + (sConnectionName ?? "DefaultLAN")); return(false); } }