///<summary>Parses a specified HTTP query into its header fields.</summary> ///<param name="Query">The HTTP query string to parse.</param> ///<returns>A StringDictionary object containing all the header fields with their data.</returns> ///<exception cref="ArgumentNullException">The specified query is null.</exception> private StringDictionary ParseQuery(string Query) { StringDictionary retdict = new StringDictionary(); string [] Lines = Query.Replace("\r\n", "\n").Split('\n'); int Cnt, Ret; //Extract requested URL if (Lines.Length > 0) { //Parse the Http Request Type Ret = Lines[0].IndexOf(' '); if (Ret > 0) { HttpRequestType = Lines[0].Substring(0, Ret); Lines[0] = Lines[0].Substring(Ret).Trim(); } //Parse the Http Version and the Requested Path Ret = Lines[0].LastIndexOf(' '); if (Ret > 0) { HttpVersion = Lines[0].Substring(Ret).Trim(); RequestedPath = Lines[0].Substring(0, Ret); } else { RequestedPath = Lines[0]; } //Remove http:// if present if (RequestedPath.Length >= 7 && RequestedPath.Substring(0, 7).ToLower().Equals("http://")) { Ret = RequestedPath.IndexOf('/', 7); if (Ret == -1) { RequestedPath = "/"; } else { RequestedPath = RequestedPath.Substring(Ret); } } } for (Cnt = 1; Cnt < Lines.Length; Cnt++) { //RT: added - dont parse past the header! for XML/MPP //if (Lines[Cnt].Length==0){ // break; //} Ret = Lines[Cnt].IndexOf(":"); if (Ret > 0 && Ret < Lines[Cnt].Length - 1) { try { retdict.Add(Lines[Cnt].Substring(0, Ret), Lines[Cnt].Substring(Ret + 1).Trim()); } catch {} } } return(retdict); }
private 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(":", StringComparison.Ordinal); if (ret >= 0) { host = RequestedPath.Substring(0, ret); port = RequestedPath.Length > ret + 1 ? int.Parse(RequestedPath.Substring(ret + 1)) : 443; } else { host = RequestedPath; port = 443; } } else { //HTTP ret = HeaderFields["Host"].IndexOf(":", StringComparison.Ordinal); if (ret > 0) { host = HeaderFields["Host"].Substring(0, ret); port = int.Parse(HeaderFields["Host"].Substring(ret + 1)); } else { host = HeaderFields["Host"]; port = 80; } if (HttpRequestType.ToUpper().Equals("POST")) { var index = query.IndexOf("\r\n\r\n", StringComparison.Ordinal); _httpPost = query.Substring(index + 4); } } try { var destinationEndPoint = new IPEndPoint(Dns.GetHostEntry(host).AddressList[0], port); DestinationSocket = new Socket(destinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (HeaderFields.ContainsKey("Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive")) { DestinationSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); } DestinationSocket.BeginConnect(destinationEndPoint, OnConnected, DestinationSocket); } catch { SendBadRequest(); } }
private StringDictionary ParseQuery(string Query) { StringDictionary retdict = new StringDictionary(); string[] Lines = Query.Replace("\r\n", "\n").Split('\n'); int Cnt, Ret; //Extract requested URL if (Lines.Length > 0) { //Parse the Http Request Type Ret = Lines[0].IndexOf(' '); if (Ret > 0) { HttpRequestType = Lines[0].Substring(0, Ret); Lines[0] = Lines[0].Substring(Ret).Trim(); } //Parse the Http Version and the Requested Path Ret = Lines[0].LastIndexOf(' '); if (Ret > 0) { HttpVersion = Lines[0].Substring(Ret).Trim(); RequestedPath = Lines[0].Substring(0, Ret); } else { RequestedPath = Lines[0]; } //Remove http:// if present if (RequestedPath.Length >= 7 && RequestedPath.Substring(0, 7).ToLower().Equals("http://")) { Ret = RequestedPath.IndexOf('/', 7); if (Ret == -1) { RequestedPath = "/"; } else { RequestedPath = RequestedPath.Substring(Ret); } } } for (Cnt = 1; Cnt < Lines.Length; Cnt++) { Ret = Lines[Cnt].IndexOf(":"); if (Ret > 0 && Ret < Lines[Cnt].Length - 1) { try { retdict.Add(Lines[Cnt].Substring(0, Ret), Lines[Cnt].Substring(Ret + 1).Trim()); } catch (Exception ex) { Log.Write(MethodInfo.GetCurrentMethod(), ex); } } } return(retdict); }
///<summary>Parses a specified HTTP query into its header fields.</summary> ///<param name="query">The HTTP query string to parse.</param> ///<returns>A WebHeaderCollection object containing all the header fields with their data.</returns> ///<exception cref="ArgumentNullException">The specified query is null.</exception> public WebHeaderCollection ParseQuery(string query) { string[] lines = query.Replace("\r\n", "\n").Split('\n'); int index; //Extract requested URL if (lines.Length > 0) { //Parse the Http Request Type index = lines[0].IndexOf(' '); if (index > 0) { HttpRequestType = lines[0].Substring(0, index); lines[0] = lines[0].Substring(index).Trim(); } //Parse the Http Version and the Requested Path index = lines[0].LastIndexOf(' '); if (index > 0) { HttpVersion = lines[0].Substring(index).Trim(); RequestedPath = lines[0].Substring(0, index); } else { RequestedPath = lines[0]; } if (string.IsNullOrEmpty(OriginallyRequestedAbsoluteUri)) { OriginallyRequestedAbsoluteUri = new Uri(RequestedPath).AbsoluteUri; } if (string.IsNullOrEmpty(RequestedAbsoluteUri)) { RequestedAbsoluteUri = new Uri(RequestedPath).AbsoluteUri; } //Remove http:// if present if (RequestedPath.Length >= 7 && RequestedPath.Substring(0, 7).ToLower().Equals("http://")) { index = RequestedPath.IndexOf('/', 7); if (index == -1) { RequestedPath = "/"; } else { RequestedPath = RequestedPath.Substring(index); } } } return(ParseHeaders(lines, false)); }
private StringDictionary ParseQuery(string query) { var retdict = new StringDictionary(); var lines = query.Replace("\r\n", "\n").Split('\n'); int cnt, ret; //Extract requested URL if (lines.Length > 0) { //Parse the Http Request Type ret = lines[0].IndexOf(' '); if (ret > 0) { HttpRequestType = lines[0].Substring(0, ret); lines[0] = lines[0].Substring(ret).Trim(); } //Parse the Http Version and the Requested Path ret = lines[0].LastIndexOf(' '); if (ret > 0) { HttpVersion = lines[0].Substring(ret).Trim(); RequestedPath = lines[0].Substring(0, ret); } else { RequestedPath = lines[0]; } //Remove http:// if present if (RequestedPath.Length >= 7 && RequestedPath.Substring(0, 7).ToLower().Equals("http://")) { ret = RequestedPath.IndexOf('/', 7); RequestedPath = ret == -1 ? "/" : RequestedPath.Substring(ret); } } for (cnt = 1; cnt < lines.Length; cnt++) { ret = lines[cnt].IndexOf(":", StringComparison.Ordinal); if (ret <= 0 || ret >= lines[cnt].Length - 1) { continue; } try { retdict.Add(lines[cnt].Substring(0, ret), lines[cnt].Substring(ret + 1).Trim()); } catch { } } return(retdict); }
private 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 { IPEndPoint DestinationEndPoint = new IPEndPoint(Dns.Resolve(Host).AddressList[0], Port); DestinationSocket = new Socket(DestinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (HeaderFields.ContainsKey("Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive")) { DestinationSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); } DestinationSocket.BeginConnect(DestinationEndPoint, new AsyncCallback(this.OnConnected), DestinationSocket); } catch { SendBadRequest(); return; } }
///<summary>Processes a specified query and connects to the requested HTTP web server.</summary> ///<param name="Query">A string containing the query to process.</param> ///<remarks>If there's an error while processing the HTTP request or when connecting to the remote server, the Proxy sends a "400 - Bad Request" error to the client.</remarks> private void ProcessQuery(string Query) { HeaderFields = ParseQuery(Query); if (HeaderFields == null || !HeaderFields.HasKeys() || !DoHeadersContainKey(HeaderFields, "Host")) { SendBadRequest(); return; } if (OnProcessQueryEnd != null) { OnProcessQueryEnd.Invoke(DestinationSocket, this); } if (Cancel) { SendCancelledResponse(); 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 = (HeaderFields["Host"]).IndexOf(":"); if (Ret > 0) { Host = (HeaderFields["Host"]).Substring(0, Ret); Port = int.Parse((HeaderFields["Host"]).Substring(Ret + 1)); } else { Host = HeaderFields["Host"]; Port = 80; } if (HttpRequestType.ToUpper().Equals("POST")) { int index = Query.IndexOf("\r\n\r\n"); m_HttpPost = Query.Substring(index + 4); } } try { IPEndPoint DestinationEndPoint = new IPEndPoint(Dns.Resolve(Host).AddressList[0], Port); DestinationSocket = new Socket(DestinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (DoHeadersContainKey(HeaderFields, "Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive")) { //DestinationSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); } DestinationSocket.BeginConnect(DestinationEndPoint, OnConnected, DestinationSocket); } catch { SendBadRequest(); return; } }
private void ProcessQuery(string Query) { HeaderFields = ParseQuery(Query); if (HeaderFields == null || !HeaderFields.ContainsKey("Host")) { SendBadRequest(); return; } if (UserValidator != null) { var authValid = true; try { if (HeaderFields.ContainsKey("Proxy-Authorization") == false) { authValid = false; } else { var authHeader = HeaderFields["Proxy-Authorization"]; if (authHeader.IndexOf("Basic") > -1) { var base64String = authHeader.Replace("Basic", "").Trim(); var strUserPass = Encoding.UTF8.GetString(Convert.FromBase64String(base64String)); var authParam = strUserPass.Split(':'); var username = authParam[0]; var password = authParam[1]; authValid = UserValidator.IsValid(username, password); } else { authValid = false; } } } catch (Exception ex) { Log.Write(MethodInfo.GetCurrentMethod(), ex); authValid = false; } if (authValid == false) { SendAuthenticationFailed(); 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 { IPEndPoint DestinationEndPoint = new IPEndPoint(Dns.GetHostEntry(Host).AddressList[0], Port); DestinationSocket = new Socket(DestinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (HeaderFields.ContainsKey("Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive")) { DestinationSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); } DestinationSocket.BeginConnect(DestinationEndPoint, new AsyncCallback(this.OnConnected), DestinationSocket); } catch { SendBadRequest(); return; } }
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 void QueryHandle(string query) { HeaderFields = ParseQuery(query); if ((HeaderFields == null) || !HeaderFields.ContainsKey("Host")) { SendBadRequest(); } else { int num; string requestedPath; int index; if (HttpRequestType.ToUpper().Equals("CONNECT")) { index = RequestedPath.IndexOf(":"); if (index >= 0) { requestedPath = RequestedPath.Substring(0, index); num = RequestedPath.Length > (index + 1) ? int.Parse(RequestedPath.Substring(index + 1)) : 443; } else { requestedPath = RequestedPath; num = 80; } } else { index = HeaderFields["Host"].IndexOf(":"); if (index > 0) { requestedPath = HeaderFields["Host"].Substring(0, index); num = int.Parse(HeaderFields["Host"].Substring(index + 1)); } else { requestedPath = HeaderFields["Host"]; num = 80; } if (HttpRequestType.ToUpper().Equals("POST")) { int tempnum = query.IndexOf("\r\n\r\n"); _mHttpPost = query.Substring(tempnum + 4); } } var localFile = String.Empty; if (MonitorLog.RegexUrl(RequestedUrl)) { localFile = UrlOperate.MatchFile(RequestedUrl); } _uinfo.PsnUrl = string.IsNullOrEmpty(_uinfo.PsnUrl) ? RequestedUrl : _uinfo.PsnUrl; if (!HttpRequestType.ToUpper().Equals("CONNECT") && localFile != string.Empty && File.Exists(localFile)) { _uinfo.ReplacePath = localFile; _updataUrlLog(_uinfo); SendLocalFile(localFile, HeaderFields.ContainsKey("Range") ? HeaderFields["Range"] : null, HeaderFields.ContainsKey("Proxy-Connection") ? HeaderFields["Proxy-Connection"] : null); } else { try { bool iscdn; IPAddress hostIp = CdnOperate.GetCdnAddress(requestedPath, out iscdn); var remoteEp = new IPEndPoint(hostIp, num); DestinationSocket = new Socket(remoteEp.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (HeaderFields.ContainsKey("Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive")) { DestinationSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); } DestinationSocket.BeginConnect(remoteEp, OnConnected, DestinationSocket); _uinfo.Host = hostIp.ToString(); _uinfo.IsCdn = iscdn; _uinfo.ReplacePath = string.Empty; _updataUrlLog(_uinfo); } catch { SendBadRequest(); } } } }
///<summary>Processes a specified query and connects to the requested HTTP web server.</summary> ///<param name="Query">A string containing the query to process.</param> ///<remarks>If there's an error while processing the HTTP request or when connecting to the remote server, the Proxy sends a "400 - Bad Request" error to the client.</remarks> private void ProcessQuery(string Query) { HeaderFields = ParseQuery(Query); if (HeaderFields == null || !HeaderFields.ContainsKey("Host")) { SendBadRequest(); return; } #region Parse destination address and port int Port; string Host; int Ret; if (HttpRequestType.ToUpper().Equals("CONNECT")) //HTTPS { isThisSSL = true; this.isPayloadSecure = true; Ret = RequestedPath.IndexOf(":"); if (Ret >= 0) { Host = RequestedPath.Substring(0, Ret); if (RequestedPath.Length > Ret + 1) { Port = int.Parse(RequestedPath.Substring(Ret + 1)); CurrentHTTPSport = Port; } else { Port = 443; CurrentHTTPSport = 443; } } else { Host = RequestedPath; Port = 443; CurrentHTTPSport = 443; } } else { isThisSSL = false; Ret = ((string)HeaderFields["Host"]).IndexOf(":"); if (Ret > 0) { Host = ((string)HeaderFields["Host"]).Substring(0, Ret); Port = int.Parse(((string)HeaderFields["Host"]).Substring(Ret + 1)); CurrentHTTPSport = Port; } else { Host = (string)HeaderFields["Host"]; Port = 80; CurrentHTTPSport = 80; } if (HttpRequestType.ToUpper().Equals("GET") == false) { int index = Query.IndexOf("\r\n\r\n"); m_HttpPost = Query.Substring(index + 4); } } #endregion #region Create destination socket try { IPEndPoint DestinationEndPoint = new IPEndPoint(Dns.Resolve(Host).AddressList[0], Port); if (this.isPayloadSecure) { SecurityOptions options = new SecurityOptions( SecureProtocol.Ssl3 | SecureProtocol.Tls1, // use SSL3 or TLS1 null, // not required for SSL client ConnectionEnd.Client, // this is the client side CredentialVerification.None, // do not check the certificate -- this should not be used in a real-life application :-) null, // not used with automatic certificate verification "www.bogus.com", // this is the common name of the Microsoft web server SecurityFlags.Default, // use the default security flags SslAlgorithms.SECURE_CIPHERS, // only use secure ciphers null); // do not process certificate requests. // This line for intercept proxy DestinationSocket = new SecureSocket(DestinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp, options); // This line for pass-through proxy //DestinationSocket = new SecureSocket(DestinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } else { DestinationSocket = new SecureSocket(DestinationEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } if (HeaderFields.ContainsKey("Proxy-Connection") && HeaderFields["Proxy-Connection"].ToLower().Equals("keep-alive")) { DestinationSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); } DestinationSocket.BeginConnect(DestinationEndPoint, new AsyncCallback(this.OnConnected), DestinationSocket); } catch { SendBadRequest(); return; } #endregion }