Example #1
0
        public override void Execute(ref string codes, string pageUrl, string pageUrlNoQuery, string pagePath, string rootUrl)
        {
            try
            {
                // 1- executing plugins
                if (Plugins.IsPluginAvailable(PluginHosts.IPluginCSSProcessor))
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginCSSProcessor,
                                             PluginMethods.IPluginCSSProcessor.BeforeExecute,
                                             this, (object)codes, pageUrl, pageUrlNoQuery, pagePath, rootUrl);
                }

                // ASProxy pages url formats generator
                ASProxyPagesFormat pages = new ASProxyPagesFormat(_UserOptions.EncodeUrl);

                // For @Import rule
                CSSReplacer.ReplaceCSSClassStyleUrl(ref codes,
                                                    pageUrlNoQuery,
                                                    pages.PageAnyType,
                                                    pagePath,
                                                    rootUrl,
                                                    _UserOptions.EncodeUrl,
                                                    true);

                // For backgrounds
                CSSReplacer.ReplaceCSSClassStyleUrl(ref codes,
                                                    pageUrlNoQuery,
                                                    pages.PageAnyType,
                                                    pagePath,
                                                    rootUrl,
                                                    _UserOptions.EncodeUrl,
                                                    false);


                // 2- executing plugins
                if (Plugins.IsPluginAvailable(PluginHosts.IPluginCSSProcessor))
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginCSSProcessor,
                                             PluginMethods.IPluginCSSProcessor.AfterExecute,
                                             this, (object)codes, pageUrl, pageUrlNoQuery, pagePath, rootUrl);
                }
            }
            catch (Exception ex)
            {
                // error logs
                if (Systems.LogSystem.ErrorLogEnabled)
                {
                    Systems.LogSystem.LogError(ex, pageUrl);
                }

                LastStatus       = LastStatus.ContinueWithError;
                LastException    = ex;
                LastErrorMessage = "ASProxy has some errors!";

                codes = "/* ASProxy has some errors! \n"
                        + ex.Message + " */"
                        + codes;
            }
        }
Example #2
0
        /// <summary>
        /// Logs exception, request host, requested url and specified items
        /// </summary>
        public override void LogError(Exception ex, HttpRequest request, string message, string requestedUrl, params object[] optionalData)
        {
            if (ErrorLogEnabled == false)
            {
                return;
            }

            // executing plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginLogSystem,
                                         PluginMethods.IPluginLogSystem.BeforeLogError,
                                         this, ex, request, message, requestedUrl, optionalData);
            }

            StringBuilder builder = new StringBuilder();

            if (!string.IsNullOrEmpty(requestedUrl))
            {
                builder.AppendFormat(_strUrlFormat, requestedUrl);
            }

            if (request != null)
            {
                builder.AppendFormat(_strIPFormat, request.UserHostAddress);
                builder.AppendFormat(_strASProxyRequestUrl, request.Url.PathAndQuery);
            }

            if (!string.IsNullOrEmpty(message))
            {
                builder.AppendFormat(_strMessage, message);
            }

            builder.AppendFormat(_strDateTimeFormat, DateTime.Now.ToString());
            if (ex != null)
            {
                builder.AppendFormat(_strError, ex.ToString());
            }

            for (int i = 0; i < optionalData.Length; i++)
            {
                builder.AppendFormat(_strDataFormat, optionalData[i]);
            }

            string result = string.Format(_strEntityFormat, LogEntity.Error, builder.ToString());

            try
            {
                SaveToErrorFile(result);
            }
            catch { }
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        public override void Initialize(HttpRequest httpRequest)
        {
            IntializeRequestInfo(httpRequest);
            IntializeRequestInfoPostData(httpRequest);

            // 0- executing plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginEngine,
                                         PluginMethods.IPluginEngine.AfterInitialize,
                                         this);
            }
        }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        public override void Initialize(string requestUrl)
        {
            RequestInfo.RequestUrl    = requestUrl;
            RequestInfo.RequestMethod = WebMethods.GET;
            IntializeRequestInfoPostData(null);

            // 0- executing plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginEngine,
                                         PluginMethods.IPluginEngine.AfterInitialize,
                                         this);
            }
        }
        public override NetworkCredential GetNetworkCertification(string url)
        {
            NetworkCredential result = GetNetworkCertification(GetCertification(url));

            // 1- executing plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginCredentialCache,
                                         PluginMethods.IPluginCredentialCache.OnGetNetworkCertification,
                                         this, url, result);
            }

            return(result);
        }
Example #6
0
        /// <summary>
        /// Logs http request, requested url and specified items
        /// </summary>
        public override void Log(LogEntity entity, HttpRequest request, string requestedUrl, params object[] optionalData)
        {
            if (ActivityLogEnabled == false)
            {
                return;
            }
            if (entity == LogEntity.ImageRequested && Configurations.LogSystem.ActivityLog_Images == false)
            {
                return;
            }

            // executing plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginLogSystem,
                                         PluginMethods.IPluginLogSystem.BeforeLog,
                                         this, request, requestedUrl, optionalData);
            }


            StringBuilder builder = new StringBuilder();

            builder.AppendFormat(_strUrlFormat, requestedUrl);

            if (request != null)
            {
                builder.AppendFormat(_strIPFormat, request.UserHostAddress);
            }
            builder.AppendFormat(_strDateTimeFormat, DateTime.Now.ToString());

            for (int i = 0; i < optionalData.Length; i++)
            {
                builder.AppendFormat(_strDataFormat, optionalData[i]);
            }

            string result = string.Format(_strEntityFormat, entity, builder.ToString());

            try
            {
                SaveToActivityFile(result);
            }
            catch { }
        }
        public override void AddCertification(string url, string userName, string password)
        {
            HttpSessionState session = HttpContext.Current.Session;

            if (session == null)
            {
                return;
            }

            string            key     = GetCertificatedKey(url);
            CredentialDetails details = new CredentialDetails();

            details.UserName = userName;
            details.Password = password;
            session[key]     = details;

            // 0- executing plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginCredentialCache,
                                         PluginMethods.IPluginCredentialCache.AfterAddCertification,
                                         this, url, userName, password);
            }
        }
Example #8
0
        public override void Execute()
        {
            // fresh
            _webResponse = null;
            try
            {
                // Create a request instance
                if (_webRequest == null)
                {
                    _webRequest = WebRequest.Create(RequestInfo.RequestUrl);
                }

                // Initializa the instance
                InitializeWebRequest(_webRequest);

                // Post data
                ApplyPostDataToRequest(_webRequest);

                // Partial content data ranges
                ApplyContentRanges(_webRequest);

                // 0- executing plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                                             PluginMethods.IPluginWebData.BeforeExecuteGetResponse,
                                             this, _webRequest);
                }

                try
                {
                    // Get the response
                    _webResponse = _webRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    // ADDED Since V4.1:
                    // Captures unauthorized access errors.
                    // If the error isn't an unauthorized access error, then throw a relative exception.

                    WebResponse response = ex.Response;
                    if (response != null)
                    {
                        if (response is HttpWebResponse)
                        {
                            HttpWebResponse webRes = (HttpWebResponse)response;
                            if (webRes.StatusCode == HttpStatusCode.Unauthorized)
                            {
                                // Set unauthorized response data
                                FinalizeUnauthorizedWebResponse(webRes);

                                // response range
                                ReadResponseRangeInfo(webRes);

                                // Set status to normal
                                LastStatus = LastStatus.Normal;

                                // Do not continue the proccess
                                return;
                            }
                        }
                        else if (response is FtpWebResponse)
                        {
                            FtpWebResponse ftpRes = (FtpWebResponse)response;
                            if (ftpRes.StatusCode == FtpStatusCode.NotLoggedIn)
                            {
                                // Set unauthorized response data
                                FinalizeUnauthorizedWebResponse(ftpRes);

                                // response range
                                ReadResponseRangeInfo(ftpRes);

                                // Set status to normal
                                LastStatus = LastStatus.Normal;

                                // Do not continue the proccess
                                return;
                            }
                        }
                    }

                    // Nothing is captured, so throw the error
                    throw;
                }

                // 1- executing plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                                             PluginMethods.IPluginWebData.AfterExecuteGetResponse,
                                             this, _webResponse);
                }


                // Check for response persmission set from "Administration UI"
                ValidateResponse(_webResponse);

                // Response is successfull, continue to get data
                FinalizeWebResponse(_webResponse);

                // response range
                ReadResponseRangeInfo(_webResponse);

                // 2- executing plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                                             PluginMethods.IPluginWebData.AfterExecuteFinalizeWebResponse,
                                             this, _webResponse);
                }

                // Getting data
                ResponseData = ReadResponseData(_webResponse);

                // 3- executing plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                                             PluginMethods.IPluginWebData.AfterExecuteReadResponseData,
                                             this);
                }
            }
            catch (WebException ex)
            {
                // adds a special message for conenction failure
                if (ex.Status == WebExceptionStatus.ConnectFailure)
                {
                    // http status
                    if (ex.Response != null)
                    {
                        ApplyResponseHttpStatus(ex.Response);
                    }
                    else
                    {
                        ResponseInfo.HttpStatusDescription = ex.Message;
                        ResponseInfo.HttpStatusCode        = (int)HttpStatusCode.NotFound;
                    }

                    ResponseInfo.ContentLength = -1;
                    LastStatus    = LastStatus.Error;
                    LastException = ex;

                    // special message
                    LastErrorMessage = ex.Message +
                                       "\n<br />" + "ASProxy is behind a firewall? If so, go through the proxy server or config ASProxy to pass it.";

                    return;
                }

                // ADDED 3.8.1::
                // Try to recover the request state and display original error state

                // Display original error page if requested.
                if (!RequestInfo.PrrocessErrorPage)
                {
                    throw;
                }

                // Continue to get data
                FinalizeWebResponse(ex.Response);

                // response range
                ReadResponseRangeInfo(ex.Response);

                // 2- executing plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                                             PluginMethods.IPluginWebData.AfterExecuteFinalizeWebResponse,
                                             this, ex.Response);
                }

                // Getting data
                ResponseData = ReadResponseData(_webResponse);

                // 3- executing plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                                             PluginMethods.IPluginWebData.AfterExecuteReadResponseData,
                                             this);
                }


                // The state is error page
                LastStatus       = LastStatus.ContinueWithError;
                LastException    = ex;
                LastErrorMessage = ex.Message;
            }
            catch (Exception ex)
            {
                ResponseInfo.ContentLength = -1;
                LastStatus       = LastStatus.Error;
                LastErrorMessage = ex.Message;
                LastException    = ex;
            }
            finally
            {
                // dispose only if data is ready
                // not for streaming options
                if (RequestInfo.BufferResponse)
                {
                    if (_webResponse != null)
                    {
                        _webResponse.Close();
                        _webResponse = null;
                    }
                }
            }
        }
Example #9
0
        public override void Execute(ref string codes,
                                     string pageUrl,
                                     string pageUrlNoQuery,
                                     string pagePath,
                                     string rootUrl)
        {
            try
            {
                // 1- executing plugins
                if (Plugins.IsPluginAvailable(PluginHosts.IPluginJSProcessor))
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginJSProcessor,
                                             PluginMethods.IPluginJSProcessor.BeforeExecute,
                                             this, (object)codes, pageUrl, pageUrlNoQuery, pagePath, rootUrl);
                }

                // BugFix: setting document.domain will cause error in javascript
                // Also checking the value of document.domain may cause bad behaviours
                // so both are going ot be disabled here
                JSReplacer.ReplacePropertyUsages(ref codes,
                                                 "document.domain", Consts.ClientContent.JSEncoder_ASProxyLocationXDomain);


                // New location should be encoded!
                JSReplacer.AddEncoderMethodToPropertySet(ref codes,
                                                         new string[] { "location.href", "window.location",
                                                                        "document.location", "top.location",
                                                                        "self.location", "parent.location" },
                                                         Consts.ClientContent.JSEncoder_ASProxyEncoderMethodName);


                // Cookie set
                JSReplacer.AddEncoderMethodToPropertySet(ref codes,
                                                         "document.cookie",
                                                         Consts.ClientContent.JSEncoder_ASProxySetCookieMethodName);

                // Cookie get, Since v5.0
                JSReplacer.AddEncoderMethodToPropertyGet(ref codes,
                                                         "document.cookie",
                                                         Consts.ClientContent.JSEncoder_ASProxyGetCookieMethodName, true);


                // Replaces these properties by __XUrl
                // top.location , parent.location and self.location
                JSReplacer.AddEncoderMethodToPropertyGet(ref codes,
                                                         new string[] { "top", "parent", "self" },
                                                         new string[] { "location" },
                                                         Consts.ClientContent.JSEncoder_ASProxyWindowLocOverrider,
                                                         false);


                // document.URL is only getter and its string
                JSReplacer.AddEncoderMethodToPropertyGet(ref codes,
                                                         new string[] { "document" },
                                                         new string[] { "URL" },
                                                         Consts.ClientContent.JSEncoder_ASProxyWindowLocHref,
                                                         false);

                // fisrt test location with base objects
                JSReplacer.AddEncoderMethodToPropertyGet(ref codes,
                                                         new string[] { "window", "document", "location" },
                                                         new string[] { "location" },
                                                         Consts.ClientContent.JSEncoder_ASProxyWindowLocOverrider,
                                                         false);

                // then location attributes test
                JSReplacer.AddEncoderMethodToPropertyGetFirstPart(ref codes,
                                                                  new string[] { "location" },
                                                                  new string[] { "href", "search", "hash", "host", "hostname", "pathname", "port", "protocol", "replace", "assign" },
                                                                  Consts.ClientContent.JSEncoder_ASProxyWindowLocOverrider,
                                                                  false);

                JSReplacer.AddEncoderMethodToMethodFirstParameter(ref codes,
                                                                  "location.replace",
                                                                  Consts.ClientContent.JSEncoder_ASProxyEncoderMethodName);

                // It is not common to use "open" method directly.
                // So i ignore to handle it here
                //JSReplacer.AddEncoderMethodToMethodFirstParameter(ref html, "open", Consts.JSEncoder_ASProxyEncoderMethodName);

                // Don't proccess these
                // The "open" method will proccess in JavaScript encoder in "asproxyencoder.js" file.
                // Since v4.8
                //JSReplacer.AddEncoderMethodToMethodFirstParameter(ref html, "window.open", Consts.JSEncoder_ASProxyEncoderMethodName);
                //JSReplacer.AddEncoderMethodToMethodFirstParameter(ref html, "location.open", Consts.JSEncoder_ASProxyEncoderMethodName);


                // 2- executing plugins
                if (Plugins.IsPluginAvailable(PluginHosts.IPluginJSProcessor))
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginJSProcessor,
                                             PluginMethods.IPluginJSProcessor.AfterExecute,
                                             this, (object)codes, pageUrl, pageUrlNoQuery, pagePath, rootUrl);
                }
            }
            catch (Exception ex)
            {
                // error logs
                if (Systems.LogSystem.ErrorLogEnabled)
                {
                    Systems.LogSystem.LogError(ex, pageUrl);
                }

                LastStatus       = LastStatus.ContinueWithError;
                LastException    = ex;
                LastErrorMessage = "ASProxy has some errors!";


                codes = "/* ASProxy has some errors! \n"
                        + ex.Message + " */"
                        + codes;
            }
        }
Example #10
0
        /// <summary>
        /// Communicates with back-end and gets response information
        /// </summary>
        public override void ExecuteHandshake()
        {
            // Checks if handshake is alreadu done
            // Hashshakhe can only run one time
            if (_webData != null)
            {
                return;
            }

            // 1- executing the plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginEngine,
                                         PluginMethods.IPluginEngine.BeforeHandshake,
                                         this, _webData);
            }

            // If this is an image request, we should provide orginal link as referer
            if (RequestInfo.ContentTypeMime == MimeContentType.image_gif ||
                RequestInfo.ContentTypeMime == MimeContentType.image_jpeg)
            {
                // We ignore what setting was. It should send referrer for images.
                RequestInfo.RequestUrlAsReferrer = true;
            }

            do
            {
                // If this is auto recection request send request again to new location
                if (_webData != null && _webData.ResponseInfo.AutoRedirect)
                {
                    // Handles the redirect request
                    HandleResponseAutoRedirect();

                    // Exit the method
                    return;
                }
                else
                {
                    // Generated user agent
                    // Since v5.1
                    string userAgent = Common.GenerateUserAgent(HttpContext.Current);

                    if (_webData != null)
                    {
                        _webData.Dispose();
                    }

                    // initializing new DataCore
                    _webData = (IWebData)Providers.GetProvider(ProviderType.IWebData);
                    _webData.RequestInfo.RequestUrl = RequestInfo.RequestUrl;
                    _webData.RequestInfo.UserAgent  = userAgent;
                }

                // WebData request info
                ApplyWebDataRequestInfo(_webData);

                // Execute the request
                _webData.Execute();

                // If execution failed
                if (_webData.LastStatus == LastStatus.Error)
                {
                    LastStatus       = LastStatus.Error;
                    LastErrorMessage = _webData.LastErrorMessage;
                    LastException    = _webData.LastException;
                    return;
                }
                else if (_webData.LastStatus == LastStatus.ContinueWithError)
                {
                    LastStatus       = LastStatus.ContinueWithError;
                    LastErrorMessage = _webData.LastErrorMessage;
                    LastException    = _webData.LastException;
                }

                // Read response info
                FinilizeResponseInfo(_webData);
            } while (_webData.ResponseInfo.AutoRedirect);

            // 2- executing the plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginEngine,
                                         PluginMethods.IPluginEngine.AfterHandshake,
                                         this, _webData);
            }
        }
Example #11
0
        /// <summary>
        ///
        /// </summary>
        public override void ExecuteToStream(Stream stream)
        {
            // handshake should be ran before and there should not be error
            if (_webData == null || LastStatus == LastStatus.Error)
            {
                return;
            }

            // process type
            DataTypeToProcess processType = DataTypeToProcess;

            // gets mime type of content type
            MimeContentType contentMimeType = _webData.ResponseInfo.ContentTypeMime;

            // detecting processing method by response content type
            if (processType == DataTypeToProcess.AutoDetect)
            {
                // gets its process type
                processType = Common.MimeTypeToToProcessType(contentMimeType);
            }

            IDataProcessor dataProcessor = null;

            switch (processType)
            {
            case DataTypeToProcess.AutoDetect:
                break;

            case DataTypeToProcess.Html:
                dataProcessor = (IDataProcessor)Providers.GetProvider(ProviderType.IHtmlProcessor);
                break;

            case DataTypeToProcess.JavaScript:
                dataProcessor = (IDataProcessor)Providers.GetProvider(ProviderType.IJSProcessor);
                break;

            case DataTypeToProcess.Css:
                dataProcessor = (IDataProcessor)Providers.GetProvider(ProviderType.ICssProcessor);
                break;

            case DataTypeToProcess.AdobeFlash:
            // still nothing
            case DataTypeToProcess.None:
                break;

            default:
                break;
            }

            if (dataProcessor != null)
            {
                // 3- executing the plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginEngine,
                                             PluginMethods.IPluginEngine.BeforeProcessor,
                                             this, dataProcessor);
                }

                // Web data instance
                dataProcessor.WebData = _webData;

                // executes the process
                string response = dataProcessor.Execute();

                // If execution occurred
                if (dataProcessor.LastStatus == LastStatus.Error)
                {
                    LastStatus       = LastStatus.Error;
                    LastErrorMessage = dataProcessor.LastErrorMessage;
                    LastException    = dataProcessor.LastException;
                    return;
                }
                else if (dataProcessor.LastStatus == LastStatus.ContinueWithError)
                {
                    LastStatus       = LastStatus.ContinueWithError;
                    LastErrorMessage = dataProcessor.LastErrorMessage;
                    LastException    = dataProcessor.LastException;
                }

                // processed content encoding
                ResponseInfo.ContentEncoding = dataProcessor.ContentEncoding;
                ResponseInfo.ContentLength   = response.Length;



                // Html specifies
                if (processType == DataTypeToProcess.Html && dataProcessor is IHtmlProcessor)
                {
                    IHtmlProcessor htmlProcessor = (IHtmlProcessor)dataProcessor;

                    ResponseInfo.HtmlPageTitle     = htmlProcessor.PageTitle;
                    ResponseInfo.HtmlIsFrameSet    = htmlProcessor.IsFrameSet;
                    ResponseInfo.ExtraCodesForPage = htmlProcessor.ExtraCodesForPage;
                    ResponseInfo.ExtraCodesForBody = htmlProcessor.ExtraCodesForBody;
                    ResponseInfo.HtmlDocType       = htmlProcessor.DocType;
                }

                // 4- executing the plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginEngine,
                                             PluginMethods.IPluginEngine.AfterProcessor,
                                             this);
                }

                // the processed content
                byte[] streamBuff = ResponseInfo.ContentEncoding.GetBytes(response);
                stream.Write(streamBuff, 0, streamBuff.Length);
            }
            else
            {
                // used to resolvent mime processing conflict
                bool ContinueNonMime = true;

                // if response is a image
                if ((UserOptions.ImageCompressor) &&
                    (contentMimeType == MimeContentType.image_gif || contentMimeType == MimeContentType.image_jpeg))
                {
                    using (MemoryStream imgMem = ImageCompressor.CompressImage(
                               _webData.ResponseData))
                    {
                        // check if compression is decreased size of data
                        if (imgMem.Length < _webData.ResponseData.Length)
                        {
                            ContinueNonMime = false;

                            // write the image to result
                            imgMem.WriteTo(stream);
                        }
                        else
                        {
                            // Oops! the original image is smaller
                            ContinueNonMime = true;
                        }
                    }
                }

                // can process other types?
                if (ContinueNonMime)
                {
                    if (processType == DataTypeToProcess.None &&
                        _webData.ResponseData is MemoryStream)
                    {
                        MemoryStream mem = (MemoryStream)_webData.ResponseData;
                        if (mem.Length > 0)
                        {
                            mem.WriteTo(stream);
                        }
                    }
                    else if (processType == DataTypeToProcess.None)
                    {
                        int       readed    = -1;
                        const int blockSize = 1024 * 5;

                        byte[] buffer = new byte[blockSize];
                        while ((int)(readed = _webData.ResponseData.Read(buffer, 0, blockSize)) > 0)
                        {
                            stream.Write(buffer, 0, readed);
                        }
                    }
                    else
                    {
                        Encoding contentEncoding;
                        // Reads response stream to a string
                        string response = StringStream.GetString(
                            _webData.ResponseData,
                            WebData.ResponseInfo.ContentType,
                            UserOptions.ForceEncoding,
                            false,
                            out contentEncoding);

                        ResponseInfo.ContentEncoding = contentEncoding;
                        ResponseInfo.ContentLength   = response.Length;

                        byte[] streamBuff = ResponseInfo.ContentEncoding.GetBytes(response);
                        stream.Write(streamBuff, 0, streamBuff.Length);
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        public override string ExecuteToString()
        {
            // hanshake should be ran before and there should not be error
            if (_webData == null || LastStatus == LastStatus.Error)
            {
                return(String.Empty);
            }

            // process type
            DataTypeToProcess processType = DataTypeToProcess;

            // gets mime type of content type
            MimeContentType contentMimeType = _webData.ResponseInfo.ContentTypeMime;

            // detecting processing method by response content type
            if (processType == DataTypeToProcess.AutoDetect)
            {
                // gets its process type
                processType = Common.MimeTypeToToProcessType(contentMimeType);
            }

            if (processType == DataTypeToProcess.Html && Systems.LogSystem.ActivityLogEnabled)
            {
                Systems.LogSystem.Log(LogEntity.UrlRequested, ResponseInfo.ResponseUrl);
            }

            IDataProcessor dataProcessor = null;

            switch (processType)
            {
            case DataTypeToProcess.AutoDetect:
                break;

            case DataTypeToProcess.Html:
                dataProcessor = (IDataProcessor)Providers.GetProvider(ProviderType.IHtmlProcessor);
                break;

            case DataTypeToProcess.JavaScript:
                dataProcessor = (IDataProcessor)Providers.GetProvider(ProviderType.IJSProcessor);
                break;

            case DataTypeToProcess.Css:
                dataProcessor = (IDataProcessor)Providers.GetProvider(ProviderType.ICssProcessor);
                break;

            case DataTypeToProcess.AdobeFlash:
            // still nothing
            default:
                break;
            }

            if (dataProcessor != null)
            {
                // 3- executing the plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginEngine,
                                             PluginMethods.IPluginEngine.BeforeProcessor,
                                             this, dataProcessor);
                }

                // Web data instance
                dataProcessor.WebData = _webData;

                // executes the process
                string response = dataProcessor.Execute();

                // If execution occurred
                if (dataProcessor.LastStatus == LastStatus.Error)
                {
                    LastStatus       = LastStatus.Error;
                    LastErrorMessage = dataProcessor.LastErrorMessage;
                    LastException    = dataProcessor.LastException;
                    return(response);
                }
                else if (dataProcessor.LastStatus == LastStatus.ContinueWithError)
                {
                    LastStatus       = LastStatus.ContinueWithError;
                    LastErrorMessage = dataProcessor.LastErrorMessage;
                    LastException    = dataProcessor.LastException;
                }

                // processed content encoding
                ResponseInfo.ContentEncoding = dataProcessor.ContentEncoding;
                ResponseInfo.ContentLength   = response.Length;



                // Html specifies
                if (processType == DataTypeToProcess.Html && dataProcessor is IHtmlProcessor)
                {
                    IHtmlProcessor htmlProcessor = (IHtmlProcessor)dataProcessor;

                    ResponseInfo.HtmlPageTitle     = htmlProcessor.PageTitle;
                    ResponseInfo.HtmlIsFrameSet    = htmlProcessor.IsFrameSet;
                    ResponseInfo.ExtraCodesForPage = htmlProcessor.ExtraCodesForPage;
                    ResponseInfo.ExtraCodesForBody = htmlProcessor.ExtraCodesForBody;
                    ResponseInfo.HtmlDocType       = htmlProcessor.DocType;
                }

                // 4- executing the plugins
                if (_isPluginAvailable)
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginEngine,
                                             PluginMethods.IPluginEngine.AfterProcessor,
                                             this);
                }

                // the processed content
                return(response);
            }
            else
            {
                Encoding contentEncoding;

                // Reads response stream to a string
                string response = StringStream.GetString(
                    _webData.ResponseData,
                    WebData.ResponseInfo.ContentType,
                    UserOptions.ForceEncoding,
                    false,
                    out contentEncoding);

                ResponseInfo.ContentEncoding = contentEncoding;
                ResponseInfo.ContentLength   = response.Length;

                return(response);
            }
        }
Example #13
0
        /// <summary>
        /// Processes the html codes
        /// </summary>
        /// <param name="codes">Html codes</param>
        /// <param name="pageUrl">Page url. E.G. http://Site.com/users/profile.aspx?uid=90</param>
        /// <param name="rootUrl">Root path. E.G. http://Site.com/</param>
        public override void Execute(ref string codes, string pageUrl, string pageUrlNoQuery, string pagePath, string rootUrl)
        {
            try
            {
                // 1- executing plugins
                if (Plugins.IsPluginAvailable(PluginHosts.IPluginHtmlProcessor))
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginHtmlProcessor,
                                             PluginMethods.IPluginHtmlProcessor.BeforeExecute,
                                             this, (object)codes, pageUrl, pageUrlNoQuery, pagePath, rootUrl);
                }

                // ASProxy pages url formats generator
                ASProxyPagesFormat pages = new ASProxyPagesFormat(_UserOptions.EncodeUrl);

                // Original urls addistional codes option
                bool orginalUrlRequired = false;


                // Renames ASPDotNET standard ViewState name to a temporary name
                // This name will reset to default when the page posted back
                HtmlReplacer.ReplaceAspDotNETViewState(ref codes);


                // If remove scripts chosen, remove all the scripts.
                if (_UserOptions.RemoveScripts)
                {
                    HtmlReplacer.RemoveScripts(ref codes);
                }


                // If remove embeded objects is requested
                if (_UserOptions.RemoveObjects)
                {
                    // Removing <object> tag
                    HtmlParser.RemoveTagContent(ref codes, "object", true);

                    // Removing <embed> tag
                    HtmlParser.RemoveTagContent(ref codes, "embed", true);
                }

                // Applying the BASE tag to the URLs.
                string baseHref;
                if (HtmlReplacer.ReplaceBaseSources(ref codes, true, out baseHref))
                {
                    // changing page base path to specified Base in the document
                    pagePath = UrlProvider.AddSlashToEnd(baseHref);

                    // BUGFIX v4.6.1:: site root url should change also
                    rootUrl = UrlProvider.GetRootPath(rootUrl);
                }

                // processing style sheet links
                if (_UserOptions.Images)
                {
                    HtmlReplacer.ReplaceCssLinks(ref codes,
                                                 pageUrlNoQuery,
                                                 pages.PageAnyType,
                                                 pagePath,
                                                 rootUrl,
                                                 _UserOptions.EncodeUrl);

                    // TODO: CSSReplacer
                    // This function replaces "Import" rule and background images!
                    // So, this breaches to background option role. Since v4.0
                    CSSReplacer.ReplaceStyleTagStyleUrl(ref codes,
                                                        pageUrlNoQuery,
                                                        pages.PageAnyType,
                                                        pages.PageAnyType,
                                                        pagePath,
                                                        rootUrl,
                                                        _UserOptions.EncodeUrl);
                }

                // It seems with javascript encoding these methods are useless!!
                // The javascript may be disabled in browser so we have to this anyway
                if (_UserOptions.Links)
                {
                    string extraAttib = "";

                    // Add displaying orginal url address code
                    if (_UserOptions.OrginalUrl)
                    {
                        orginalUrlRequired = true;
                        extraAttib         = Resources.STR_OrginalUrl_TagAttributeFormat;
                    }

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttib += Consts.ClientContent.attrAlreadyEncodedAttributeWithValue;

                    HtmlReplacer.ReplaceAnchors(ref codes,
                                                pageUrlNoQuery,
                                                pages.PageDefault,
                                                pagePath,
                                                rootUrl,
                                                _UserOptions.EncodeUrl,
                                                extraAttib);

                    HtmlReplacer.ReplaceHttpRefresh(ref codes,
                                                    pageUrlNoQuery,
                                                    pages.PageDefault,
                                                    pagePath,
                                                    rootUrl,
                                                    _UserOptions.EncodeUrl);
                }
                else
                {
                    string extraAttib;

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttib = Consts.ClientContent.attrAlreadyEncodedAttributeWithValue;

                    HtmlReplacer.ReplaceAnchors(ref codes,
                                                pageUrlNoQuery,
                                                "{0}",
                                                pagePath,
                                                rootUrl,
                                                false,
                                                extraAttib);

                    HtmlReplacer.ReplaceHttpRefresh(ref codes,
                                                    pageUrlNoQuery,
                                                    "{0}",
                                                    pagePath,
                                                    rootUrl,
                                                    _UserOptions.EncodeUrl);
                }

                if (_UserOptions.Frames)
                {
                    string extraAttrib = Resources.STR_IFrame_ExtraAttribute;

                    // Encode <iframe> tags
                    HtmlReplacer.ReplaceIFrames(ref codes,
                                                pageUrlNoQuery,
                                                pages.PageHtml,
                                                pagePath,
                                                rootUrl,
                                                _UserOptions.EncodeUrl,
                                                extraAttrib);

                    // Encode <framset> tags
                    HtmlReplacer.ReplaceFrameSets(ref codes,
                                                  pageUrlNoQuery,
                                                  pages.PageHtml,
                                                  pagePath,
                                                  rootUrl,
                                                  _UserOptions.EncodeUrl);
                }

                // Encode <img> tags
                if (_UserOptions.Images)
                {
                    string extraAttrib = "";

                    // Add code to display orginal url address
                    if (_UserOptions.OrginalUrl)
                    {
                        orginalUrlRequired = true;
                        extraAttrib        = Resources.STR_OrginalUrl_TagAttributeFormat;
                    }

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttrib += Consts.ClientContent.attrAlreadyEncodedAttributeWithValue;

                    HtmlReplacer.ReplaceImages(ref codes,
                                               pageUrlNoQuery,
                                               pages.PageAnyType,
                                               pagePath,
                                               rootUrl,
                                               _UserOptions.EncodeUrl,
                                               extraAttrib);

                    // Encode background image of <body> , <table> and <td> tags
                    HtmlReplacer.ReplaceBackgrounds(ref codes,
                                                    pageUrlNoQuery,
                                                    pages.PageAnyType,
                                                    pagePath,
                                                    rootUrl,
                                                    _UserOptions.EncodeUrl);
                }
                else
                {
                    string extraAttrib;

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttrib = Consts.ClientContent.attrAlreadyEncodedAttributeWithValue;

                    HtmlReplacer.ReplaceImages(ref codes,
                                               pageUrlNoQuery,
                                               "{0}",
                                               pagePath,
                                               rootUrl,
                                               false,
                                               extraAttrib);
                }

                // Encodes script tags if RemoveScripts option is disabled
                if (_UserOptions.RemoveScripts == false)
                {
                    HtmlReplacer.ReplaceScripts(ref codes,
                                                pageUrlNoQuery,
                                                pages.PageAnyType,
                                                pagePath,
                                                rootUrl,
                                                _UserOptions.EncodeUrl);

                    // TODO: JSReplacer
                    JSReplacer.ReplaceScriptTagCodes(ref codes);

                    // V5.2: Replaces tags events using RegEx
                    HtmlReplacer.ReplaceTagsEvents(ref codes,
                                                   pageUrlNoQuery,
                                                   pages.PageAnyType,
                                                   pagePath,
                                                   pageUrl,
                                                   rootUrl,
                                                   _UserOptions.EncodeUrl);
                }

                // Encode <embed> tags
                HtmlReplacer.ReplaceEmbeds(ref codes,
                                           pageUrlNoQuery,
                                           pages.PageAnyType,
                                           pagePath,
                                           rootUrl,
                                           _UserOptions.EncodeUrl);

                // Encode <form> tags
                if (_UserOptions.SubmitForms)
                {
                    string extraAttrib;

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttrib =
                        Consts.ClientContent.attrAlreadyEncodedAttributeWithValue
                        + Resources.STR_SubmitForms_ExtraAttribute;

                    HtmlReplacer.ReplaceFormsSources(ref codes,
                                                     pageUrlNoQuery,
                                                     pages.PageDefault,
                                                     pagePath,
                                                     rootUrl,
                                                     _UserOptions.EncodeUrl,
                                                     _UserOptions.SubmitForms,
                                                     extraAttrib);
                }
                else
                {
                    string extraAttib;

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttib =
                        Consts.ClientContent.attrAlreadyEncodedAttributeWithValue
                        + Resources.STR_SubmitForms_ExtraAttribute;

                    HtmlReplacer.ReplaceFormsSources(ref codes,
                                                     pageUrlNoQuery,
                                                     "{0}",
                                                     pagePath,
                                                     pagePath,
                                                     false,
                                                     _UserOptions.SubmitForms,
                                                     extraAttib);
                }

                // Add dynamic encoding javascript codes
                string jsEncoderCodes = GenerateJsEncoderCodes(pageUrl,
                                                               pageUrlNoQuery,
                                                               pagePath,
                                                               rootUrl);


                // Add jsEncoder codes to page
                ExtraCodesForPage = jsEncoderCodes + ExtraCodesForPage;

                // OrginalUrl additional injection html codes
                if (orginalUrlRequired)
                {
                    // TODO: Check necessary
                    ExtraCodesForPage = Resources.STR_OrginalUrl_FloatBar + ExtraCodesForPage;

                    // Inject to html, right after the body element
                    ExtraCodesForBody = Resources.STR_OrginalUrl_Functions + ExtraCodesForBody;
                }


                // 2- executing plugins
                if (Plugins.IsPluginAvailable(PluginHosts.IPluginHtmlProcessor))
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginHtmlProcessor,
                                             PluginMethods.IPluginHtmlProcessor.AfterExecute,
                                             this, (object)codes, pageUrl, pageUrlNoQuery, pagePath, rootUrl);
                }
            }
            catch (Exception ex)
            {
                // error logs
                if (Systems.LogSystem.ErrorLogEnabled)
                {
                    Systems.LogSystem.LogError(ex, pageUrl);
                }

                codes = "<center><b>ASProxy has some errors! The delivered content may not work properly.</b></center>" + ex.Message + "<br />"
                        + codes;
            }
        }
Example #14
0
        /// <summary>
        /// Validates the request context for UAC
        /// </summary>
        public override bool ValidateContext(HttpContext context)
        {
            // executing plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginUAC,
                                         PluginMethods.IPluginUAC.ValidateContext,
                                         this, context);
            }

            if (!Configurations.UserAccessControl.Enabled)
            {
                return(true);
            }

            // user ip
            string userIP = context.Request.UserHostAddress;

            if (Configurations.UserAccessControl.AllowedList != null ||
                Configurations.UserAccessControl.AllowedRange != null)
            {
                // Search in single ip addresses
                if (Configurations.UserAccessControl.AllowedList != null)
                {
                    // Is the IP allowed?
                    if (Configurations.UserAccessControl.AllowedList.Contains(userIP))
                    {
                        return(true);
                    }
                }

                if (Configurations.UserAccessControl.AllowedRange != null)
                {
                    foreach (Configurations.UserAccessControlConfig.IPRange range in Configurations.UserAccessControl.AllowedRange)
                    {
                        // Is between the range?
                        if (CompareIPs.IsGreaterOrEqual(userIP, range.Low) && CompareIPs.IsLessOrEqual(userIP, range.High))
                        {
                            return(true);
                        }
                    }
                }

                // No match found, end app anyway!
                EndApplication(context);
                return(false);
            }

            // Search in single blocked ip addresses
            if (Configurations.UserAccessControl.BlockedList != null)
            {
                // Is the IP blocked?
                if (Configurations.UserAccessControl.BlockedList.Contains(userIP))
                {
                    EndApplication(context);
                    return(false);
                }
            }

            if (Configurations.UserAccessControl.BlockedRange != null)
            {
                foreach (Configurations.UserAccessControlConfig.IPRange range in Configurations.UserAccessControl.BlockedRange)
                {
                    // Is between the range?
                    if (CompareIPs.IsGreaterOrEqual(userIP, range.Low) && CompareIPs.IsLessOrEqual(userIP, range.High))
                    {
                        EndApplication(context);
                        return(false);
                    }
                }
            }

            return(true);
        }