File: CachingParameterInspector.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (366 lines) | stat: -rw-r--r-- 16,788 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Web;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.UI;
using System.ServiceModel.Activation;

namespace System.ServiceModel.Web
{
    class CachingParameterInspector : IParameterInspector
    {
        const char seperatorChar = ';';
        const char escapeChar = '\\';
        const char tableDbSeperatorChar = ':';
        const string invalidSqlDependencyString = "Invalid Sql dependency string.";

        [Fx.Tag.SecurityNote(Critical = "A config object, which should not be leaked.")]
        [SecurityCritical]
        OutputCacheProfile cacheProfile;

        SqlDependencyInfo[] cacheDependencyInfoArray;

        [Fx.Tag.SecurityNote(Critical = "Handles config objects, which should not be leaked.",
            Safe = "The config object never leaves the CachingParameterInspector.")]
        [SecuritySafeCritical]
        public CachingParameterInspector(string cacheProfileName)
        {
            if (string.IsNullOrEmpty(cacheProfileName))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.CacheProfileNameNullOrEmpty));
            }

            OutputCacheSettingsSection cacheSettings = AspNetEnvironment.Current.UnsafeGetConfigurationSection("system.web/caching/outputCacheSettings") as OutputCacheSettingsSection;
            if (cacheSettings == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.CacheProfileNotConfigured, cacheProfileName)));
            }

            this.cacheProfile = cacheSettings.OutputCacheProfiles[cacheProfileName];
            if (this.cacheProfile == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.CacheProfileNotConfigured, cacheProfileName)));
            }

            // Validate the cacheProfile
            if (this.cacheProfile.Location != OutputCacheLocation.None)
            {
                // Duration must be set; Duration default value is -1
                if (this.cacheProfile.Duration == -1)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.CacheProfileValueMissing, this.cacheProfile.Name, "Duration")));
                }
                if (this.cacheProfile.VaryByParam == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.CacheProfileValueMissing, this.cacheProfile.Name, "VaryByParam")));
                }
            }

            if (string.Equals(this.cacheProfile.SqlDependency, "CommandNotification", StringComparison.OrdinalIgnoreCase))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.CommandNotificationSqlDependencyNotSupported));
            }

            if (!string.IsNullOrEmpty(this.cacheProfile.SqlDependency))
            {
                ParseSqlDependencyString(cacheProfile.SqlDependency);
            }
        }

        [Fx.Tag.SecurityNote(Critical = "Handles config objects, which should not be leaked.",
            Safe = "The config object never leaves the CachingParameterInspector.")]
        [SecuritySafeCritical]
        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            if (this.cacheProfile != null &&
                this.cacheProfile.Enabled &&
                OperationContext.Current.IncomingMessage.Version == MessageVersion.None)
            {
                if (DiagnosticUtility.ShouldTraceWarning && !IsAnonymous())
                {
                    TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.AddingAuthenticatedResponseToOutputCache, SR2.GetString(SR2.TraceCodeAddingAuthenticatedResponseToOutputCache, operationName));
                }
                else if (DiagnosticUtility.ShouldTraceInformation)
                {
                    TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.AddingResponseToOutputCache, SR2.GetString(SR2.TraceCodeAddingResponseToOutputCache, operationName));
                }

                SetCacheFromCacheProfile();
            }
        }

        public object BeforeCall(string operationName, object[] inputs)
        {
            return null;
        }

        bool IsAnonymous()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return false;
            }
            else
            {
                if (OperationContext.Current.ServiceSecurityContext == null)
                {
                    return true;
                }
                else
                {
                    return OperationContext.Current.ServiceSecurityContext.IsAnonymous;
                }
            }
        }

        static SqlDependencyInfo[] ParseSqlDependencyString(string sqlDependencyString)
        {
            // The code for this method was taken from private code in 
            // System.Web.SqlCacheDependency.ParseSql7OutputCacheDependency.
            // Alter if only absolutely necessary since we want to reproduce the same ASP.NET caching behavior.

            List<SqlDependencyInfo> dependencyList = new List<SqlDependencyInfo>();
            bool escapeSequenceFlag = false;
            int startIndexForDatabaseName = 0;
            int startIndexForTableName = -1;
            string databaseName = null;

            try
            {
                for (int currentIndex = 0; currentIndex < (sqlDependencyString.Length + 1); currentIndex++)
                {
                    if (escapeSequenceFlag)
                    {
                        escapeSequenceFlag = false;
                    }
                    else if ((currentIndex != sqlDependencyString.Length) &&
                             (sqlDependencyString[currentIndex] == escapeChar))
                    {
                        escapeSequenceFlag = true;
                    }
                    else
                    {
                        int subStringLength;
                        if ((currentIndex == sqlDependencyString.Length) ||
                            (sqlDependencyString[currentIndex] == seperatorChar))
                        {
                            if (databaseName == null)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(invalidSqlDependencyString);
                            }
                            subStringLength = currentIndex - startIndexForTableName;
                            if (subStringLength == 0)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(invalidSqlDependencyString);
                            }
                            string tableName = sqlDependencyString.Substring(startIndexForTableName, subStringLength);
                            SqlDependencyInfo info = new SqlDependencyInfo();
                            info.Database = VerifyAndRemoveEscapeCharacters(databaseName);
                            info.Table = VerifyAndRemoveEscapeCharacters(tableName);
                            dependencyList.Add(info);
                            startIndexForDatabaseName = currentIndex + 1;
                            databaseName = null;
                        }
                        if (currentIndex == sqlDependencyString.Length)
                        {
                            break;
                        }
                        if (sqlDependencyString[currentIndex] == tableDbSeperatorChar)
                        {
                            if (databaseName != null)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(invalidSqlDependencyString);
                            }
                            subStringLength = currentIndex - startIndexForDatabaseName;
                            if (subStringLength == 0)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(invalidSqlDependencyString);
                            }
                            databaseName = sqlDependencyString.Substring(startIndexForDatabaseName, subStringLength);
                            startIndexForTableName = currentIndex + 1;
                        }
                    }
                }
            }
            catch (ArgumentException)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.CacheProfileSqlDependencyIsInvalid, sqlDependencyString)));
            }
            if (dependencyList.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.CacheProfileSqlDependencyIsInvalid, sqlDependencyString)));
            }
            return dependencyList.ToArray();
        }

        static string VerifyAndRemoveEscapeCharacters(string str)
        {
            // The code for this method was taken from private code in 
            // System.Web.SqlCacheDependency.VerifyAndRemoveEscapeCharacters.
            // Alter if only absolutely necessary since we want to reproduce the same ASP.NET caching behavior.

            bool escapeSequenceFlag = false;
            for (int currentIndex = 0; currentIndex < str.Length; currentIndex++)
            {
                if (escapeSequenceFlag)
                {
                    if (((str[currentIndex] != escapeChar) &&
                         (str[currentIndex] != tableDbSeperatorChar)) &&
                         (str[currentIndex] != seperatorChar))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(str);
                    }
                    escapeSequenceFlag = false;
                }
                else if (str[currentIndex] == escapeChar)
                {
                    if ((currentIndex + 1) == str.Length)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(str);
                    }
                    escapeSequenceFlag = true;
                    str = str.Remove(currentIndex, 1);
                    currentIndex--;
                }
            }
            return str;
        }

        CacheDependency CreateSingleCacheDependency(string sqlDependency)
        {
            if (this.cacheDependencyInfoArray == null)
            {
                this.cacheDependencyInfoArray = CachingParameterInspector.ParseSqlDependencyString(sqlDependency);
            }

            // cacheDependencyInfoArray will never have length = 0

            if (this.cacheDependencyInfoArray.Length == 1)
            {
                return new SqlCacheDependency(this.cacheDependencyInfoArray[0].Database, this.cacheDependencyInfoArray[0].Table);
            }

            AggregateCacheDependency cacheDependency = new AggregateCacheDependency();
            foreach (SqlDependencyInfo dependencyInfo in this.cacheDependencyInfoArray)
            {
                cacheDependency.Add(new CacheDependency[] { new SqlCacheDependency(dependencyInfo.Database, dependencyInfo.Table) });
            }
            return cacheDependency;
        }

        [Fx.Tag.SecurityNote(Critical = "Uses config object to set properties of the HttpCachePolicy.",
            Safe = "The config object itself doesn't leak.")]
        [SecuritySafeCritical]
        void SetCacheFromCacheProfile()
        {
            HttpCachePolicy cache = HttpContext.Current.Response.Cache;

            if (this.cacheProfile.NoStore)
            {
                cache.SetNoStore();
            }

            // Location is not required to be set in the config.  The default is Any,
            // but if it is not set in the config the value will be -1.  So must correct for this.
            if ((int)(this.cacheProfile.Location) == -1)
            {
                cache.SetCacheability(HttpCacheability.Public);
            }
            else
            {
                switch (this.cacheProfile.Location)
                {
                    case OutputCacheLocation.Any:
                        cache.SetCacheability(HttpCacheability.Public);
                        break;
                    case OutputCacheLocation.Client:
                        cache.SetCacheability(HttpCacheability.Private);
                        break;
                    case OutputCacheLocation.Downstream:
                        cache.SetCacheability(HttpCacheability.Public);
                        cache.SetNoServerCaching();
                        break;
                    case OutputCacheLocation.None:
                        cache.SetCacheability(HttpCacheability.NoCache);
                        break;
                    case OutputCacheLocation.Server:
                        cache.SetCacheability(HttpCacheability.ServerAndNoCache);
                        break;
                    case OutputCacheLocation.ServerAndClient:
                        cache.SetCacheability(HttpCacheability.ServerAndPrivate);
                        break;
                    default:
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.CacheProfileLocationNotSupported, this.cacheProfile.Location)));
                }
            }

            if (this.cacheProfile.Location != OutputCacheLocation.None)
            {
                cache.SetExpires(HttpContext.Current.Timestamp.AddSeconds((double)this.cacheProfile.Duration));
                cache.SetMaxAge(new TimeSpan(0, 0, this.cacheProfile.Duration));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(HttpContext.Current.Timestamp);

                if (this.cacheProfile.Location != OutputCacheLocation.Client)
                {
                    if (!string.IsNullOrEmpty(this.cacheProfile.VaryByContentEncoding))
                    {
                        foreach (string contentEncoding in this.cacheProfile.VaryByContentEncoding.Split(seperatorChar))
                        {
                            cache.VaryByContentEncodings[contentEncoding.Trim()] = true;
                        }
                    }

                    if (!string.IsNullOrEmpty(this.cacheProfile.VaryByHeader))
                    {
                        foreach (string header in this.cacheProfile.VaryByHeader.Split(seperatorChar))
                        {
                            cache.VaryByHeaders[header.Trim()] = true;
                        }
                    }

                    if (this.cacheProfile.Location != OutputCacheLocation.Downstream)
                    {
                        if (!string.IsNullOrEmpty(this.cacheProfile.VaryByCustom))
                        {
                            cache.SetVaryByCustom(this.cacheProfile.VaryByCustom);
                        }

                        if (!string.IsNullOrEmpty(this.cacheProfile.VaryByParam))
                        {
                            foreach (string parameter in cacheProfile.VaryByParam.Split(seperatorChar))
                            {
                                cache.VaryByParams[parameter.Trim()] = true;
                            }
                        }

                        if (!string.IsNullOrEmpty(this.cacheProfile.SqlDependency))
                        {
                            CacheDependency cacheDependency = this.CreateSingleCacheDependency(cacheProfile.SqlDependency);
                            HttpContext.Current.Response.AddCacheDependency(new CacheDependency[] { cacheDependency });
                        }
                    }
                }
            }
        }

        private struct SqlDependencyInfo
        {
            public string Database;
            public string Table;
        }

    }
}