File: HttpCapabilitiesEvaluator.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 (405 lines) | stat: -rw-r--r-- 15,003 bytes parent folder | download | duplicates (6)
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//------------------------------------------------------------------------------
// <copyright file="HttpCapabilitiesEvaluator.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.Configuration {
    
    using System.Collections;
    using System.Collections.Specialized;
    using System.Diagnostics;
    using System.Globalization;
    using System.Reflection;
    using System.Security;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Web.Caching;
    using System.Web.Compilation;
    using System.Web.Hosting;
    using System.Security.Permissions;

    public abstract class HttpCapabilitiesProvider {
        public abstract HttpBrowserCapabilities GetBrowserCapabilities(HttpRequest request);
    }

    //
    // CapabilitiesEvaluator encapabilitiesulates a set of rules for deducing
    // a capabilities object from an HttpRequest
    //
    public class HttpCapabilitiesDefaultProvider : HttpCapabilitiesProvider {

        internal CapabilitiesRule _rule;
        internal Hashtable _variables;
        internal Type _resultType;
        internal TimeSpan _cachetime;
        internal string _cacheKeyPrefix;

        private int _userAgentCacheKeyLength;
        private static int _idCounter;
        private const string _isMobileDeviceCapKey = "isMobileDevice";
        private static object _disableOptimisticCachingSingleton = new object();
        private const int _defaultUserAgentCacheKeyLength = 64;
        private string _browserCapabilitiesProviderType = null;
        private HttpCapabilitiesProvider _browserCapabilitiesProvider = null;

        public int UserAgentCacheKeyLength {
            get {
                return _userAgentCacheKeyLength;
            }
            set {
                _userAgentCacheKeyLength = value;
            }
        }

        public Type ResultType {
            get {
                return _resultType;
            }
            set {
                _resultType = value;
            }
        }

        public TimeSpan CacheTime {
            get {
                return _cachetime;
            }
            set {
                _cachetime = value;
            }
        }

        internal string BrowserCapabilitiesProviderType {
            get {
                return _browserCapabilitiesProviderType;
            }
            set {
                _browserCapabilitiesProviderType = value;
            }
        }

        internal HttpCapabilitiesProvider BrowserCapabilitiesProvider {
            get {
                if (_browserCapabilitiesProvider == null) {
                    if (BrowserCapabilitiesProviderType != null) {
                        Type t = System.Type.GetType(BrowserCapabilitiesProviderType, true, true);
                        _browserCapabilitiesProvider = (HttpCapabilitiesProvider)Activator.CreateInstance(t);
                    }
                }
                return _browserCapabilitiesProvider;
            }
            set {
                _browserCapabilitiesProvider = value;
            }
        }

        public HttpCapabilitiesDefaultProvider() : this(RuntimeConfig.GetAppConfig().BrowserCaps){
            if (RuntimeConfig.GetAppConfig().BrowserCaps != null) {
                _userAgentCacheKeyLength = RuntimeConfig.GetAppConfig().BrowserCaps.UserAgentCacheKeyLength;
            }
            if (_userAgentCacheKeyLength == 0) {
                _userAgentCacheKeyLength = _defaultUserAgentCacheKeyLength;
            }
        }

        //
        // internal constructor; inherit from parent
        //
        public HttpCapabilitiesDefaultProvider(HttpCapabilitiesDefaultProvider parent) {
            int id = Interlocked.Increment(ref _idCounter);
            // don't do id.ToString() on every request, do it here
            _cacheKeyPrefix = CacheInternal.PrefixHttpCapabilities + id.ToString(CultureInfo.InvariantCulture);

            if (parent == null) {
                ClearParent();
            }
            else {
                _rule = parent._rule;

                if (parent._variables == null)
                    _variables = null;
                else
                    _variables = new Hashtable(parent._variables);

                _cachetime = parent._cachetime;
                _resultType = parent._resultType;
            }
            //
            AddDependency(String.Empty);
        }

        internal BrowserCapabilitiesFactoryBase BrowserCapFactory {
            get {
                return BrowserCapabilitiesCompiler.BrowserCapabilitiesFactory;
            }
        }

        //
        // remove inheritance for <result inherit="false" />
        //
        internal void ClearParent() {
            _rule = null;
            _cachetime = TimeSpan.FromSeconds(60); // one minute default expiry
            _variables = new Hashtable();
            _resultType = typeof(HttpCapabilitiesBase);
        }

        //
        // add a dependency when we encounter a <use var="HTTP_ACCEPT_LANGUAGE" as="lang" />
        //
        public void AddDependency(String variable) {
            if (variable.Equals("HTTP_USER_AGENT"))
                variable = String.Empty;

            _variables[variable] = true;
        }

        //
        // sets the set of rules
        //
        public virtual void AddRuleList(ArrayList ruleList) {
            if (ruleList.Count == 0)
                return;

            if (_rule != null)
                ruleList.Insert(0, _rule);

            _rule = new CapabilitiesSection(CapabilitiesRule.Filter, null, null, ruleList);
        }

        internal static string GetUserAgent(HttpRequest request) {
            string userAgent;

            if (request.ClientTarget.Length > 0) {
                userAgent = GetUserAgentFromClientTarget(
                    request.Context.ConfigurationPath, request.ClientTarget);
            }
            else {
                userAgent = request.UserAgent;
            }

            // Protect against attacks with long User-Agent headers
            if (userAgent != null && userAgent.Length > 512) {
                userAgent = userAgent.Substring(0, 512);
            }

            return userAgent;
        }

        internal static string GetUserAgentFromClientTarget(VirtualPath configPath, string clientTarget) {

            // Lookup ClientTarget section in config.
            ClientTargetSection clientTargetConfig = RuntimeConfig.GetConfig(configPath).ClientTarget;

            string userAgent = null;

            if ( clientTargetConfig.ClientTargets[ clientTarget ] != null )
            {
                userAgent = clientTargetConfig.ClientTargets[ clientTarget ].UserAgent;
            }

            if ( userAgent == null )
            {
                throw new HttpException(SR.GetString(SR.Invalid_client_target, clientTarget));
            }

            return userAgent;
        }

        private void CacheBrowserCapResult(ref HttpCapabilitiesBase result) {
            // Use the previously cached browserCap object if an identical
            // browserCap is found.
            CacheStoreProvider cacheInternal = System.Web.HttpRuntime.Cache.InternalCache;

            if (result.Capabilities == null) {
                return;
            }

            string hashKey = CacheInternal.PrefixBrowserCapsHash;
            StringBuilder builder = new StringBuilder();
            foreach (string attribute in result.Capabilities.Keys) {
                // Ignore useragent that is stored with empty key.
                if (String.IsNullOrEmpty(attribute)) {
                    continue;
                }

                string value = (String)result.Capabilities[attribute];
                if (value != null) {
                    builder.Append(attribute);
                    builder.Append("$");
                    builder.Append(value);
                    builder.Append("$");
                }
            }
            hashKey += builder.ToString().GetHashCode().ToString(CultureInfo.InvariantCulture);

            HttpCapabilitiesBase newResult = cacheInternal.Get(hashKey) as HttpCapabilitiesBase;
            if (newResult != null) {
                result = newResult;
            }
            else {
                // cache it and respect cachetime
                cacheInternal.Insert(hashKey, result, new CacheInsertOptions() { SlidingExpiration = _cachetime });
            }
        }

        public override HttpBrowserCapabilities GetBrowserCapabilities(HttpRequest request) {
            return (HttpBrowserCapabilities)Evaluate(request);
        }

        //
        // Actually computes the browser capabilities
        //
        internal HttpCapabilitiesBase Evaluate(HttpRequest request) {

            HttpCapabilitiesBase result;
            CacheStoreProvider cacheInternal = System.Web.HttpRuntime.Cache.InternalCache;

            //
            // 1) grab UA and do optimistic cache lookup (if UA is in dependency list) 
            //
            string userAgent = GetUserAgent(request);
            string userAgentCacheKey = userAgent;

            // Use the shorten userAgent as the cache key.
            Debug.Assert(UserAgentCacheKeyLength != 0);
            // Trim the useragent string based on <browserCaps> config
            if (userAgentCacheKey != null && userAgentCacheKey.Length > UserAgentCacheKeyLength) {
                userAgentCacheKey = userAgentCacheKey.Substring(0, UserAgentCacheKeyLength);
            }

            bool doFullCacheKeyLookup = false;
            string optimisticCacheKey = _cacheKeyPrefix + userAgentCacheKey;
            object optimisticCacheResult = cacheInternal.Get(optimisticCacheKey);

            // optimize for common case (desktop browser)
            result = optimisticCacheResult as HttpCapabilitiesBase;
            if (result != null) {
                return result;
            }

            //
            // 1.1) optimistic cache entry could tell us to do full cache lookup
            // 
            if (optimisticCacheResult == _disableOptimisticCachingSingleton) {
                doFullCacheKeyLookup = true;
            }
            else {
                // cache it and respect _cachetime
                result = EvaluateFinal(request, true);

                // Optimized cache key is disabled if the request matches any headers defined within identifications.
                if (result.UseOptimizedCacheKey) {

                    // Use the same browserCap result if one with the same capabilities can be found in the cache.
                    // This is to reduce the number of identical browserCap instances being cached.
                    CacheBrowserCapResult(ref result);

                    // Cache the result using the optimisicCacheKey
                    cacheInternal.Insert(optimisticCacheKey, result, new CacheInsertOptions() { SlidingExpiration = _cachetime });

                    return result;
                }
            }

            //
            // 2) either:
            //
            //      We've never seen the UA before (parse all headers to 
            //          determine if the new UA also carries modile device
            //          httpheaders).
            //
            //      It's a mobile UA (so parse all headers) and do full 
            //          cache lookup
            //
            //      UA isn't in dependency list (customer custom caps section)
            //

            IDictionaryEnumerator de = _variables.GetEnumerator();
            StringBuilder sb = new StringBuilder(_cacheKeyPrefix);

            InternalSecurityPermissions.AspNetHostingPermissionLevelLow.Assert();

            while (de.MoveNext()) {
                string key = (string)de.Key;
                string value;

                if (key.Length == 0) {
                    value = userAgent;
                }
                else {
                    value = request.ServerVariables[key];
                }

                if (value != null) {
                    sb.Append(value);
                }    
            }

            CodeAccessPermission.RevertAssert();

            sb.Append(BrowserCapabilitiesFactoryBase.GetBrowserCapKey(BrowserCapFactory.InternalGetMatchedHeaders(), request));
            string fullCacheKey = sb.ToString();

            //
            // Only do full cache lookup if the optimistic cache 
            // result was _disableOptimisticCachingSingleton or 
            // if UserAgent wasn't in the cap var list.
            //
            if (userAgent == null || doFullCacheKeyLookup) {

                result = cacheInternal.Get(fullCacheKey) as HttpCapabilitiesBase;

                if (result != null)
                    return result;
            }

            result = EvaluateFinal(request, false);

            // Use the same browserCap result if one with the same matched nodes can be found in the cache.
            // This is to reduce the number of identical browserCap instances being cached.
            CacheBrowserCapResult(ref result);

             // cache it and respect _cachetime
            cacheInternal.Insert(fullCacheKey, result, new CacheInsertOptions() { SlidingExpiration = _cachetime });
            if(optimisticCacheKey != null) {
                cacheInternal.Insert(optimisticCacheKey, _disableOptimisticCachingSingleton, new CacheInsertOptions() { SlidingExpiration = _cachetime });
            }

            return result;
        }

        internal HttpCapabilitiesBase EvaluateFinal(HttpRequest request, bool onlyEvaluateUserAgent) {
            HttpBrowserCapabilities browserCaps = BrowserCapFactory.GetHttpBrowserCapabilities(request);
            CapabilitiesState state = new CapabilitiesState(request, browserCaps.Capabilities);
            if (onlyEvaluateUserAgent) {
                state.EvaluateOnlyUserAgent = true;
            }

            if(_rule != null) {
                string oldIsMobileDevice = browserCaps[_isMobileDeviceCapKey];
                browserCaps.Capabilities[_isMobileDeviceCapKey] = null;

                _rule.Evaluate(state);

                string newIsMobileDevice = browserCaps[_isMobileDeviceCapKey];
                if (newIsMobileDevice == null) {
                    browserCaps.Capabilities[_isMobileDeviceCapKey] = oldIsMobileDevice;
                }
                else if (newIsMobileDevice.Equals("true")) {
                    browserCaps.DisableOptimizedCacheKey();
                }
            }

            // create the new type
            // 
            HttpCapabilitiesBase result = (HttpCapabilitiesBase)HttpRuntime.CreateNonPublicInstance(_resultType);
            result.InitInternal(browserCaps);
            
            return result;
        }

    }
}