Пример #1
0
        private bool HandleDefaultDocument(IRewriteContext context)
        {
            var uri = new Uri(this._httpContext.RequestUrl, context.Location);
            var b   = new UriBuilder(uri);

            b.Path += "/";
            uri     = b.Uri;
            if (uri.Host == this._httpContext.RequestUrl.Host)
            {
                var filename = this._httpContext.MapPath(uri.AbsolutePath);
                if (Directory.Exists(filename))
                {
                    foreach (var document in this._configuration.DefaultDocuments)
                    {
                        var pathName = Path.Combine(filename, document);
                        if (File.Exists(pathName))
                        {
                            context.Location = new Uri(uri, document).AbsolutePath;
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Пример #2
0
        internal override Expression OnVisit(IRewriteContext context, Expression node)
        {
            if (node == null)
            {
                return(null);
            }

            TExpression queryExpression = node as TExpression;

            if (queryExpression != null)
            {
                return(Visit(context, queryExpression));
            }

            if (!(node is QueryExpression) && QueryExpression.TryWrap(node, out queryExpression))
            {
                var visited = Visit(context, queryExpression);
                var visitedAsQueryExpression = visited as QueryExpression;
                if (visitedAsQueryExpression != null)
                {
                    // Unwrap
                    return(visitedAsQueryExpression.Node);
                }
                return(visited);
            }
            return(node);
        }
Пример #3
0
 private void AppendCookies(IRewriteContext context)
 {
     for (var i = 0; i < context.ResponseCookies.Count; i++)
     {
         this._httpContext.SetResponseCookie(context.ResponseCookies[i]);
     }
 }
Пример #4
0
    public void Initialize(IDictionary <string, string> settings, IRewriteContext rewriteContext)
    {
        string oldCharString, newCharString;

        if (!settings.TryGetValue("OldChar", out oldCharString) || string.IsNullOrEmpty(oldCharString))
        {
            throw new ArgumentException("OldChar provider setting is required and cannot be empty");
        }

        if (!settings.TryGetValue("NewChar", out newCharString) || string.IsNullOrEmpty(newCharString))
        {
            throw new ArgumentException("NewChar provider setting is required and cannot be empty");
        }

        if (!string.IsNullOrEmpty(oldCharString))
        {
            oldChar = oldCharString.Trim()[0];
        }
        else
        {
            throw new ArgumentException("OldChar parameter cannot be empty");
        }

        if (!string.IsNullOrEmpty(newCharString))
        {
            newChar = newCharString.Trim()[0];
        }
        else
        {
            throw new ArgumentException("NewChar parameter cannot be empty");
        }
    }
Пример #5
0
 private void AppendHeaders(IRewriteContext context)
 {
     foreach (string headerKey in context.ResponseHeaders)
     {
         this._httpContext.SetResponseHeader(headerKey, context.ResponseHeaders[headerKey]);
     }
 }
Пример #6
0
        public void Execute_WithNullContext_Throws()
        {
            // Arrange
            ForbiddenAction action  = new ForbiddenAction();
            IRewriteContext context = null;

            // Act/Assert
            ExceptionAssert.Throws <ArgumentNullException>(() => action.Execute(context));
        }
Пример #7
0
        public void Execute_WithNullContext_Throws()
        {
            // Arrange
            SetCookieAction action  = new SetCookieAction("CookieName", "CookieValue");
            IRewriteContext context = null;

            // Act/Assert
            ExceptionAssert.Throws <ArgumentNullException>(() => action.Execute(context));
        }
Пример #8
0
        public void Execute_WithNullContext_Throws()
        {
            // Arrange
            RewriteAction   action  = new RewriteAction("/", RewriteProcessing.RestartProcessing);
            IRewriteContext context = null;

            // Act/Assert
            ExceptionAssert.Throws <ArgumentNullException>(() => action.Execute(context));
        }
Пример #9
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public override bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            return Pattern.IsMatch(context.HttpContext.HttpMethod);
        }
Пример #10
0
        public void Execute_WithNullContext_Throws()
        {
            // Arrange
            RedirectAction  action  = new RedirectAction("/", true);
            IRewriteContext context = null;

            // Act/Assert
            ExceptionAssert.Throws <ArgumentNullException>(() => action.Execute(context));
        }
Пример #11
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            return !_chainedCondition.IsMatch(context);
        }
Пример #12
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return(!this._chainedCondition.IsMatch(context));
        }
Пример #13
0
        public void Execute_WithNullContext_Throws()
        {
            // Arrange
            SetStatusAction action  = new SetStatusAction(HttpStatusCode.OK);
            IRewriteContext context = null;

            // Act/Assert
            ExceptionAssert.Throws <ArgumentNullException>(() => action.Execute(context));
        }
Пример #14
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public override bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            return(Pattern.IsMatch(context.HttpContext.HttpMethod));
        }
Пример #15
0
        /// <summary>
        /// Returns true provided all the conditions in the list are met for the given context.
        /// </summary>
        /// <param name="conditions">The list of conditions</param>
        /// <param name="context">The rewrite context</param>
        /// <returns>True if all the conditions are met</returns>
        public static bool IsMatch(this IList <IRewriteCondition> conditions, IRewriteContext context)
        {
            if (conditions == null)
            {
                throw new ArgumentNullException(nameof(conditions));
            }

            // Ensure all the conditions are met, i.e. return false if any are not met.
            return(conditions.All(condition => condition.IsMatch(context)));
        }
Пример #16
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.ResponseHeaders.Add(Header, Value);

            return RewriteProcessing.ContinueProcessing;
        }
Пример #17
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        public virtual RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Location = context.ResolveLocation(context.Expand(Location));

            return RewriteProcessing.StopProcessing;
        }
Пример #18
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Properties.Set(Name, context.Expand(Value));

            return RewriteProcessing.ContinueProcessing;
        }
Пример #19
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Properties.Set(Name, context.Expand(Value));

            return(RewriteProcessing.ContinueProcessing);
        }
Пример #20
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            string ipAddress = context.Properties[Constants.RemoteAddressHeader];

            return (ipAddress != null && _range.InRange(IPAddress.Parse(ipAddress)));
        }
Пример #21
0
        public override Expression Visit(IRewriteContext context, WhereExpression node)
        {
            var sourceAsWhere = node.Source as WhereExpression;

            if (sourceAsWhere != null)
            {
                var mergedPredicate = sourceAsWhere.Predicate.MergePredicateWith(node.Predicate);
                return(WhereExpression.Create(sourceAsWhere.Source, mergedPredicate));
            }
            return(node);
        }
        public void Execute_WithNullContext_Throws()
        {
            // Arrange
            string propertyName  = "PropertyName";
            string appSettingKey = "AppSettingKey";
            SetAppSettingPropertyAction action  = new SetAppSettingPropertyAction(propertyName, appSettingKey);
            IRewriteContext             context = null;

            // Act/Assert
            ExceptionAssert.Throws <ArgumentNullException>(() => action.Execute(context));
        }
Пример #23
0
        public void Execute_WithNullContext_Throws()
        {
            // Arrange
            string          header  = "HeaderName";
            string          value   = "HeaderValue";
            IRewriteContext context = null;
            AddHeaderAction action  = new AddHeaderAction(header, value);

            // Act/Assert
            ExceptionAssert.Throws <ArgumentNullException>(() => action.Execute(context));
        }
Пример #24
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        public virtual RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Location = context.ResolveLocation(context.Expand(Location));

            return(RewriteProcessing.StopProcessing);
        }
Пример #25
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            context.ResponseHeaders.Add(this.Header, this.Value);

            return(RewriteProcessing.ContinueProcessing);
        }
Пример #26
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var ipAddress = context.Properties[Constants.RemoteAddressHeader];

            return(ipAddress != null && this._range.InRange(IPAddress.Parse(ipAddress)));
        }
Пример #27
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        public virtual RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.StatusCode = StatusCode;

            return(((int)StatusCode >= 300)
                    ? RewriteProcessing.StopProcessing
                    : RewriteProcessing.ContinueProcessing);
        }
Пример #28
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        public virtual RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.StatusCode = StatusCode;

            return ((int)StatusCode >= 300)
                    ? RewriteProcessing.StopProcessing
                    : RewriteProcessing.ContinueProcessing;
        }
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // If the value cannot be found in AppSettings, default to an empty string.
            string appSettingValue = context.ConfigurationManager.AppSettings[_appSettingsKey] ?? String.Empty;
            context.Properties.Set(Name, appSettingValue);

            return RewriteProcessing.ContinueProcessing;
        }
Пример #30
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var cookie = new HttpCookie(this.Name, this.Value);

            context.ResponseCookies.Add(cookie);

            return(RewriteProcessing.ContinueProcessing);
        }
Пример #31
0
        private void SetContextItems(IRewriteContext context)
        {
            OriginalQueryString = new Uri(_httpContext.RequestUrl, _httpContext.RawUrl).Query.Replace("?", "");
            QueryString         = new Uri(_httpContext.RequestUrl, context.Location).Query.Replace("?", "");

            // Add in the properties as context items, so these will be accessible to the handler
            foreach (string propertyKey in context.Properties.Keys)
            {
                string itemsKey   = String.Format("Rewriter.{0}", propertyKey);
                string itemsValue = context.Properties[propertyKey];

                _httpContext.Items[itemsKey] = itemsValue;
            }
        }
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // If the value cannot be found in AppSettings, default to an empty string.
            string appSettingValue = context.ConfigurationManager.AppSettings[_appSettingsKey] ?? String.Empty;

            context.Properties.Set(Name, appSettingValue);

            return(RewriteProcessing.ContinueProcessing);
        }
Пример #33
0
        private void SetContextItems(IRewriteContext context)
        {
            this.OriginalQueryString = new Uri(this._httpContext.RequestUrl, this._httpContext.RawUrl).Query.Replace("?", string.Empty);
            this.QueryString         = new Uri(this._httpContext.RequestUrl, context.Location).Query.Replace("?", string.Empty);

            // Add in the properties as context items, so these will be accessible to the handler
            foreach (string propertyKey in context.Properties.Keys)
            {
                var itemsKey   = $"Rewriter.{propertyKey}";
                var itemsValue = context.Properties[propertyKey];

                this._httpContext.Items[itemsKey] = itemsValue;
            }
        }
Пример #34
0
        /// <summary>
        /// Expands the given input based on the current context.
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="input">The input to expand.</param>
        /// <returns>The expanded input</returns>
        public string Expand(IRewriteContext context, string input)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            /* replacement :- $n
             * |	${[a-zA-Z0-9\-]+}
             * |	${fn( <replacement> )}
             * |	${<replacement-or-id>:<replacement-or-value>:<replacement-or-value>}
             *
             * replacement-or-id :- <replacement> | <id>
             * replacement-or-value :- <replacement> | <value>
             */

            /* $1 - regex replacement
             * ${propertyname}
             * ${map-name:value}				map-name is replacement, value is replacement
             * ${map-name:value|default-value}	map-name is replacement, value is replacement, default-value is replacement
             * ${fn(value)}						value is replacement
             */
            using (var reader = new StringReader(input))
            {
                using (var writer = new StringWriter())
                {
                    var ch = (char)reader.Read();
                    while (ch != EndChar)
                    {
                        if (ch == '$')
                        {
                            writer.Write(this.Reduce(context, reader));
                        }
                        else
                        {
                            writer.Write(ch);
                        }

                        ch = (char)reader.Read();
                    }

                    return(writer.GetStringBuilder().ToString());
                }
            }
        }
Пример #35
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        public override RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            base.Execute(context);

            context.StatusCode = (_permanent)
                ? HttpStatusCode.Moved
                : HttpStatusCode.Found;

            return RewriteProcessing.StopProcessing;
        }
Пример #36
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        public override RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            base.Execute(context);

            context.StatusCode = (this._permanent)
                ? HttpStatusCode.Moved
                : HttpStatusCode.Found;

            return(RewriteProcessing.StopProcessing);
        }
Пример #37
0
        /// <summary>
        /// Gets regular expression to evaluate.
        /// </summary>
        private Regex GetRegex(IRewriteContext context)
        {
            // Use double-checked locking pattern to synchronise access to the regex.
            if (this._regex != null)
            {
                return(this._regex);
            }

            lock (this)
            {
                this._regex ??= new Regex(context.ResolveLocation(this.Pattern), RegexOptions.IgnoreCase);
            }

            return(this._regex);
        }
Пример #38
0
        /// <summary>
        /// Executes the rule.
        /// </summary>
        /// <param name="context">The rewrite context</param>
        public virtual RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // Execute the actions.
            return((from t in this.Actions
                    let condition = t as IRewriteCondition
                                    where condition == null || condition.IsMatch(context)
                                    select t
                                    into action
                                    select action.Execute(context))
                   .FirstOrDefault(processing => processing != RewriteProcessing.ContinueProcessing));
        }
        public override Expression Visit(IRewriteContext context, OfTypeExpression node)
        {
            if (node.ElementType == node.Source.ElementType)
            {
                return(node.Source);
            }

            var isExpandingTypeOf = node.Source.ElementType.IsAssignableFrom(node.ElementType);
            var whereNode         = node.Source as WhereExpression;

            if (isExpandingTypeOf && whereNode != null)
            {
                return(whereNode.Source.OfType(node.ElementType).Where(whereNode.Predicate));
            }
            return(node);
        }
Пример #40
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            Regex regex = GetRegex(context);

            Match match = regex.Match(context.Location);
            if (match.Success)
            {
                context.LastMatch = match;
            }

            return match.Success;
        }
Пример #41
0
        /// <summary>
        /// Returns true provided all the conditions in the list are met for the given context.
        /// </summary>
        /// <param name="conditions">The list of conditions</param>
        /// <param name="context">The rewrite context</param>
        /// <returns>True if all the conditions are met</returns>
        public static bool IsMatch(this IList<IRewriteCondition> conditions, IRewriteContext context)
        {
            if (conditions == null)
            {
                throw new ArgumentNullException("conditions");
            }

            // Ensure all the conditions are met, i.e. return false if any are not met.
            foreach (IRewriteCondition condition in conditions)
            {
                if (!condition.IsMatch(context))
                {
                    return false;
                }
            }

            return true;
        }
Пример #42
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            try
            {
                string filename = context.HttpContext.MapPath(context.Expand(_location));
                return File.Exists(filename) || Directory.Exists(filename);
            }
            catch
            {
                // An HTTP exception or an I/O exception indicates that the file definitely
                // does not exist.
                return false;
            }
        }
Пример #43
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public override bool IsMatch(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            string property = context.Properties[PropertyName];
            if (property != null)
            {
                Match match = Pattern.Match(property);
                if (match.Success)
                {
                    context.LastMatch = match;
                }
                return match.Success;
            }

            return false;
        }
Пример #44
0
        /// <summary>
        /// Executes the rule.
        /// </summary>
        /// <param name="context">The rewrite context</param>
        public virtual RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // Execute the actions.
            for (int i = 0; i < Actions.Count; i++)
            {
                IRewriteCondition condition = Actions[i] as IRewriteCondition;
                if (condition == null || condition.IsMatch(context))
                {
                    IRewriteAction action = Actions[i];
                    RewriteProcessing processing = action.Execute(context);
                    if (processing != RewriteProcessing.ContinueProcessing)
                    {
                        return processing;
                    }
                }
            }

            return RewriteProcessing.ContinueProcessing;
        }
Пример #45
0
 private void ProcessRules(IRewriteContext context)
 {
     ProcessRules(context, _configuration.Rules, 0);
 }
Пример #46
0
 /// <summary>
 /// Determines if the rewrite rule matches.
 /// </summary>
 /// <param name="context">The rewrite context.</param>
 /// <returns>True if the rule matches.</returns>
 public bool IsMatch(IRewriteContext context)
 {
     return Conditions.IsMatch(context);
 }
Пример #47
0
 /// <summary>
 /// Executes the action.
 /// </summary>
 /// <param name="context">The rewrite context.</param>
 public override RewriteProcessing Execute(IRewriteContext context)
 {
     base.Execute(context);
     return _processing;
 }
Пример #48
0
        /// <summary>
        /// Gets regular expression to evaluate.
        /// </summary>
        private Regex GetRegex(IRewriteContext context)
        {
            // Use double-checked locking pattern to synchronise access to the regex.
            if (_regex == null)
            {
                lock (this)
                {
                    if (_regex == null)
                    {
                        _regex = new Regex(context.ResolveLocation(_pattern), RegexOptions.IgnoreCase);
                    }
                }
            }

            return _regex;
        }
Пример #49
0
 /// <summary>
 /// Mock implementation of IRewriteCondition.IsMatch
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public bool IsMatch(IRewriteContext context)
 {
     return _result;
 }
Пример #50
0
 /// <summary>
 /// Determines if the condition is matched.
 /// </summary>
 /// <param name="context">The rewriting context.</param>
 /// <returns>True if the condition is met.</returns>
 public abstract bool IsMatch(IRewriteContext context);
        public void Initialize(IDictionary<string, string> settings, IRewriteContext rewriteContext)
        {

        }
Пример #52
0
        private void SetContextItems(IRewriteContext context)
        {
            OriginalQueryString = new Uri(_httpContext.RequestUrl, _httpContext.RawUrl).Query.Replace("?", "");
            QueryString = new Uri(_httpContext.RequestUrl, context.Location).Query.Replace("?", "");

            // Add in the properties as context items, so these will be accessible to the handler
            foreach (string propertyKey in context.Properties.Keys)
            {
                string itemsKey = String.Format("Rewriter.{0}", propertyKey);
                string itemsValue = context.Properties[propertyKey];

                _httpContext.Items[itemsKey] = itemsValue;
            }
        }
Пример #53
0
 private void VerifyResultExists(IRewriteContext context)
 {
     if ((String.Compare(context.Location, _httpContext.RawUrl) != 0) && ((int)context.StatusCode < 300))
     {
         Uri uri = new Uri(_httpContext.RequestUrl, context.Location);
         if (uri.Host == _httpContext.RequestUrl.Host)
         {
             string filename = _httpContext.MapPath(uri.AbsolutePath);
             if (!File.Exists(filename))
             {
                 _configuration.Logger.Debug(MessageProvider.FormatString(Message.ResultNotFound, filename));
                 context.StatusCode = HttpStatusCode.NotFound;
             }
             else
             {
                 HandleDefaultDocument(context);
             }
         }
     }
 }
Пример #54
0
        private void ProcessRules(IRewriteContext context, IList<IRewriteAction> rewriteRules, int restarts)
        {
            foreach (IRewriteAction action in rewriteRules)
            {
                // If the rule is conditional, ensure the conditions are met.
                IRewriteCondition condition = action as IRewriteCondition;
                if (condition == null || condition.IsMatch(context))
                {
                    // Execute the action.
                    RewriteProcessing processing = action.Execute(context);

                    // If the action is Stop, then break out of the processing loop
                    if (processing == RewriteProcessing.StopProcessing)
                    {
                        _configuration.Logger.Debug(MessageProvider.FormatString(Message.StoppingBecauseOfRule));

                        // Exit the loop.
                        break;
                    }

                    // If the action is Restart, then start again.
                    if (processing == RewriteProcessing.RestartProcessing)
                    {
                        _configuration.Logger.Debug(MessageProvider.FormatString(Message.RestartingBecauseOfRule));

                        // Increment the number of restarts and check that we have not exceeded our max.
                        restarts++;
                        if (restarts > MaxRestarts)
                        {
                            throw new InvalidOperationException(MessageProvider.FormatString(Message.TooManyRestarts));
                        }

                        // Restart again from the first rule by calling this method recursively.
                        ProcessRules(context, rewriteRules, restarts);

                        // Exit the loop.
                        break;
                    }
                }
            }
        }
Пример #55
0
        private string Reduce(IRewriteContext context, StringReader reader)
        {
            string result;
            char ch = (char)reader.Read();
            if (Char.IsDigit(ch))
            {
                string num = ch.ToString();
                if (Char.IsDigit((char)reader.Peek()))
                {
                    ch = (char)reader.Read();
                    num += ch.ToString();
                }
                if (context.LastMatch != null)
                {
                    Group group = context.LastMatch.Groups[Convert.ToInt32(num)];
                    result = (group == null) ? String.Empty : group.Value;
                }
                else
                {
                    result = String.Empty;
                }
            }
            else if (ch == '<')
            {
                string expr;

                using (StringWriter writer = new StringWriter())
                {
                    ch = (char)reader.Read();
                    while (ch != '>' && ch != EndChar)
                    {
                        if (ch == '$')
                        {
                            writer.Write(Reduce(context, reader));
                        }
                        else
                        {
                            writer.Write(ch);
                        }
                        ch = (char)reader.Read();
                    }

                    expr = writer.GetStringBuilder().ToString();
                }

                if (context.LastMatch != null)
                {
                    Group group = context.LastMatch.Groups[expr];
                    result = (group == null) ? String.Empty : group.Value;
                }
                else
                {
                    result = String.Empty;
                }
            }
            else if (ch == '{')
            {
                string expr;
                bool isMap = false;
                bool isFunction = false;

                using (StringWriter writer = new StringWriter())
                {
                    ch = (char)reader.Read();
                    while (ch != '}' && ch != EndChar)
                    {
                        if (ch == '$')
                        {
                            writer.Write(Reduce(context, reader));
                        }
                        else
                        {
                            if (ch == ':')
                            {
                                isMap = true;
                            }
                            else if (ch == '(')
                            {
                                isFunction = true;
                            }
                            writer.Write(ch);
                        }
                        ch = (char)reader.Read();
                    }

                    expr = writer.GetStringBuilder().ToString();
                }

                if (isMap)
                {
                    Match match = Regex.Match(expr, @"^([^\:]+)\:([^\|]+)(\|(.+))?$");
                    string mapName = match.Groups[1].Value;
                    string mapArgument = match.Groups[2].Value;
                    string mapDefault = match.Groups[4].Value;

                    IRewriteTransform tx = _configuration.TransformFactory.GetTransform(mapName);
                    if (tx == null)
                    {
                        throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.MappingNotFound, mapName));
                    }

                    result = tx.ApplyTransform(mapArgument) ?? mapDefault;
                }
                else if (isFunction)
                {
                    Match match = Regex.Match(expr, @"^([^\(]+)\((.+)\)$");
                    string functionName = match.Groups[1].Value;
                    string functionArgument = match.Groups[2].Value;

                    IRewriteTransform tx = _configuration.TransformFactory.GetTransform(functionName);
                    if (tx == null)
                    {
                        throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.TransformFunctionNotFound, functionName));
                    }

                    result = tx.ApplyTransform(functionArgument);
                }
                else
                {
                    result = context.Properties[expr];
                }
            }
            else
            {
                result = ch.ToString();
            }

            return result;
        }
Пример #56
0
        /// <summary>
        /// Expands the given input based on the current context.
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="input">The input to expand.</param>
        /// <returns>The expanded input</returns>
        public string Expand(IRewriteContext context, string input)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            /* replacement :- $n
                         * |	${[a-zA-Z0-9\-]+}
                         * |	${fn( <replacement> )}
                         * |	${<replacement-or-id>:<replacement-or-value>:<replacement-or-value>}
                         *
                         * replacement-or-id :- <replacement> | <id>
                         * replacement-or-value :- <replacement> | <value>
                         */

            /* $1 - regex replacement
             * ${propertyname}
             * ${map-name:value}				map-name is replacement, value is replacement
             * ${map-name:value|default-value}	map-name is replacement, value is replacement, default-value is replacement
             * ${fn(value)}						value is replacement
             */

            using (StringReader reader = new StringReader(input))
            {
                using (StringWriter writer = new StringWriter())
                {
                    char ch = (char)reader.Read();
                    while (ch != EndChar)
                    {
                        if (ch == '$')
                        {
                            writer.Write(Reduce(context, reader));
                        }
                        else
                        {
                            writer.Write(ch);
                        }

                        ch = (char)reader.Read();
                    }

                    return writer.GetStringBuilder().ToString();
                }
            }
        }
Пример #57
0
        private void HandleError(IRewriteContext context)
        {
            // Return the status code.
            _httpContext.SetStatusCode(context.StatusCode);

            // Get the error handler if there is one.
            if (!_configuration.ErrorHandlers.ContainsKey((int)context.StatusCode))
            {
                // No error handler for this status code?
                // Just throw an HttpException with the appropriate status code.
                throw new HttpException((int)context.StatusCode, context.StatusCode.ToString());
            }

            IRewriteErrorHandler handler = _configuration.ErrorHandlers[(int) context.StatusCode];

            try
            {
                _configuration.Logger.Debug(MessageProvider.FormatString(Message.CallingErrorHandler));

                // Execute the error handler.
                _httpContext.HandleError(handler);
            }
            catch (HttpException)
            {
                // Any HTTP errors that result from executing the error page should be propogated.
                throw;
            }
            catch (Exception exc)
            {
                // Any other error should result in a 500 Internal Server Error.
                _configuration.Logger.Error(exc.Message, exc);

                HttpStatusCode serverError = HttpStatusCode.InternalServerError;
                throw new HttpException((int)serverError, serverError.ToString());
            }
        }
Пример #58
0
        private bool HandleDefaultDocument(IRewriteContext context)
        {
            Uri uri = new Uri(_httpContext.RequestUrl, context.Location);
            UriBuilder b = new UriBuilder(uri);
            b.Path += "/";
            uri = b.Uri;
            if (uri.Host == _httpContext.RequestUrl.Host)
            {
                string filename = _httpContext.MapPath(uri.AbsolutePath);
                if (Directory.Exists(filename))
                {
                    foreach (string document in _configuration.DefaultDocuments)
                    {
                        string pathName = Path.Combine(filename, document);
                        if (File.Exists(pathName))
                        {
                            context.Location = new Uri(uri, document).AbsolutePath;
                            return true;
                        }
                    }
                }
            }

            return false;
        }
Пример #59
0
 private void AppendHeaders(IRewriteContext context)
 {
     foreach (string headerKey in context.ResponseHeaders)
     {
         _httpContext.SetResponseHeader(headerKey, context.ResponseHeaders[headerKey]);
     }
 }
Пример #60
0
 private void AppendCookies(IRewriteContext context)
 {
     for (int i = 0; i < context.ResponseCookies.Count; i++)
     {
         _httpContext.SetResponseCookie(context.ResponseCookies[i]);
     }
 }