File: SimpleWebHandlerParser.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (561 lines) | stat: -rw-r--r-- 17,977 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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//------------------------------------------------------------------------------
// <copyright file="SimpleWebHandlerParser.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

/*
 * Implements the parser for simple web handler files
 *
 * Copyright (c) 2000 Microsoft Corporation
 */

namespace System.Web.UI {

using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Runtime.Serialization;

using System;
using System.Reflection;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.CodeDom.Compiler;
using System.Web;
using System.Web.Hosting;
using System.Web.Caching;
using System.Web.Compilation;
using System.CodeDom;
using System.Web.Util;
using Debug=System.Web.Util.Debug;
using System.Web.RegularExpressions;
using System.Globalization;
using System.Security.Permissions;


/// <internalonly/>
/// <devdoc>
///    <para>[To be supplied.]</para>
/// </devdoc>
public abstract class SimpleWebHandlerParser  : IAssemblyDependencyParser {
    private readonly static Regex directiveRegex = new SimpleDirectiveRegex();

    private SimpleHandlerBuildProvider _buildProvider;

    private TextReader _reader;

    private VirtualPath _virtualPath;

    // The line number in file currently being parsed
    private int _lineNumber;

    // The column number in file currently being parsed
    private int _startColumn;

    private bool _fFoundMainDirective;

    private string _typeName;
    internal string TypeName { 
        get { return _typeName; } 
    }

    private CompilerType _compilerType;

    // The string containing the code to be compiled
    private string _sourceString;

    // Assemblies to be linked with
    private AssemblySet _linkedAssemblies;

    // The set of assemblies that the build system is telling us we will be linked with
    private ICollection _referencedAssemblies;

    private static char[] s_newlineChars = new char[] { '\r', '\n' };

    private bool _ignoreParseErrors;
    internal bool IgnoreParseErrors {
        get { return _ignoreParseErrors; }
        set { _ignoreParseErrors = value; }
    }

    internal void SetBuildProvider(SimpleHandlerBuildProvider buildProvider) {
        _buildProvider = buildProvider;
    }


    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>

    // Only allowed in full trust (ASURT 124397)
    [SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
    protected SimpleWebHandlerParser(HttpContext context, string virtualPath, string physicalPath) {

        // These obsolete parameters should never be set
        Debug.Assert(context == null);
        Debug.Assert(physicalPath == null);

        Debug.Assert(virtualPath != null);

        _virtualPath = VirtualPath.Create(virtualPath);
    }

    /*
     * Compile a web handler file into a Type.  Result is cached.
     */

    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    protected Type GetCompiledTypeFromCache() {

        //
        // This method is practically useless, but cannot be removed to avoid a breaking change
        //

        BuildResultCompiledType result = (BuildResultCompiledType) BuildManager.GetVPathBuildResult(_virtualPath);

        return result.ResultType;
    }

    internal void Parse(ICollection referencedAssemblies) {

        _referencedAssemblies = referencedAssemblies;

        AddSourceDependency(_virtualPath);

        // Open a TextReader for the virtualPath we're parsing
        using (_reader = _buildProvider.OpenReaderInternal()) {
            ParseReader();
        }
    }

    internal CompilerType CompilerType { get { return _compilerType; } }

    internal ICollection AssemblyDependencies { get { return _linkedAssemblies; } }
    private StringSet _sourceDependencies;
    internal ICollection SourceDependencies { get { return _sourceDependencies; } }

    internal CodeCompileUnit GetCodeModel() {

        // Do we have something to compile?
        if (_sourceString == null)
            return null;

        CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(_sourceString);

        // Put in some context so that the file can be debugged.
        snippetCompileUnit.LinePragma = BaseCodeDomTreeGenerator.CreateCodeLinePragmaHelper(
            _virtualPath.VirtualPathString, _lineNumber);

        return snippetCompileUnit;
    }

    internal IDictionary GetLinePragmasTable() {
        LinePragmaCodeInfo codeInfo = new LinePragmaCodeInfo();
        codeInfo._startLine = _lineNumber;
        codeInfo._startColumn = _startColumn;
        codeInfo._startGeneratedColumn = 1;
        codeInfo._codeLength = -1;
        codeInfo._isCodeNugget = false;
    
        IDictionary linePragmasTable = new Hashtable();
        linePragmasTable[_lineNumber] = codeInfo;
    
        return linePragmasTable;
    }

    internal bool HasInlineCode { get { return (_sourceString != null); } } 

    internal Type GetTypeToCache(Assembly builtAssembly) {
        Type t = null;

        // First, try to get the type from the assembly that has been built (if any)
        if (builtAssembly != null)
            t = builtAssembly.GetType(_typeName);

        // If not, try to get it from other assemblies
        if (t == null)
            t = GetType(_typeName);

        // Make sure the type derives from what we expect
        try {
            ValidateBaseType(t);
        }
        catch (Exception e) {
            throw new HttpParseException(e.Message, e, _virtualPath, _sourceString, _lineNumber);
        }

        return t;
    }

    internal virtual void ValidateBaseType(Type t) {
        // No restriction on the base type by default
    }

    /*
     * Parse the contents of the TextReader
     */
    private void ParseReader() {
        string s = _reader.ReadToEnd();

        try {
            ParseString(s);
        }
        catch (Exception e) {
            throw new HttpParseException(e.Message, e, _virtualPath, s, _lineNumber);
        }
    }

    /*
     * Parse the contents of the string
     */
    private void ParseString(string text) {
        int textPos = 0;
        Match match;
        _lineNumber = 1;

        // First, parse all the <%@ ... %> directives
        for (;;) {
            match = directiveRegex.Match(text, textPos);

            // Done with the directives?
            if (!match.Success)
                break;

            _lineNumber += Util.LineCount(text, textPos, match.Index);
            textPos = match.Index;

            // Get all the directives into a bag
            IDictionary directive = CollectionsUtil.CreateCaseInsensitiveSortedList();
            string directiveName = ProcessAttributes(match, directive);

            ProcessDirective(directiveName, directive);

            _lineNumber += Util.LineCount(text, textPos, match.Index + match.Length);
            textPos = match.Index + match.Length;

            int newlineIndex = text.LastIndexOfAny(s_newlineChars, textPos-1);
            _startColumn = textPos - newlineIndex;
        }

        if (!_fFoundMainDirective && !IgnoreParseErrors) {
            throw new HttpException(
                SR.GetString(SR.Missing_directive, DefaultDirectiveName));
        }

        // skip the directive
        string remainingText = text.Substring(textPos);

        // If there is something else in the file, it needs to be compiled
        if (!Util.IsWhiteSpaceString(remainingText))
            _sourceString = remainingText;
    }

    private string ProcessAttributes(Match match, IDictionary attribs) {
        string ret = String.Empty;
        CaptureCollection attrnames = match.Groups["attrname"].Captures;
        CaptureCollection attrvalues = match.Groups["attrval"].Captures;
        CaptureCollection equalsign = null;
        equalsign = match.Groups["equal"].Captures;

        for (int i = 0; i < attrnames.Count; i++) {
            string attribName = attrnames[i].ToString();
            string attribValue = attrvalues[i].ToString();

            // Check if there is an equal sign.
            bool fHasEqual = (equalsign[i].ToString().Length > 0);

            if (attribName != null) {
                // A <%@ %> block can have two formats:
                // <%@ directive foo=1 bar=hello %>
                // <%@ foo=1 bar=hello %>
                // Check if we have the first format
                if (!fHasEqual && i==0) {
                    ret = attribName;
                    continue;
                }

                try {
                    if (attribs != null)
                        attribs.Add(attribName, attribValue);
                }
                catch (ArgumentException) {

                    // Ignore the duplicate attributes when called from CBM
                    if (IgnoreParseErrors) continue;

                    throw new HttpException(
                        SR.GetString(SR.Duplicate_attr_in_tag, attribName));
                }
            }
        }

        return ret;
    }


    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    protected abstract string DefaultDirectiveName { get; }

    private static void ProcessCompilationParams(IDictionary directive, CompilerParameters compilParams) {
        bool fDebug = false;
        if (Util.GetAndRemoveBooleanAttribute(directive, "debug", ref fDebug))
            compilParams.IncludeDebugInformation = fDebug;

        if (compilParams.IncludeDebugInformation &&
            !HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) {
            throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "debug"));
        }

        int warningLevel=0;
        if (Util.GetAndRemoveNonNegativeIntegerAttribute(directive, "warninglevel", ref warningLevel)) {
            compilParams.WarningLevel = warningLevel;
            if (warningLevel > 0)
                compilParams.TreatWarningsAsErrors = true;
        }

        string compilerOptions = Util.GetAndRemoveNonEmptyAttribute(
            directive, "compileroptions");
        if (compilerOptions != null) {
            CompilationUtil.CheckCompilerOptionsAllowed(compilerOptions, false /*config*/, null, 0);
            compilParams.CompilerOptions = compilerOptions;
        }
    }

    /*
     * Process a <%@ %> block
     */
    internal virtual void ProcessDirective(string directiveName, IDictionary directive) {

        // Empty means default
        if (directiveName.Length == 0)
            directiveName = DefaultDirectiveName;

        // Check for the main directive
        if (IsMainDirective(directiveName)) {

            // Make sure the main directive was not already specified
            if (_fFoundMainDirective && !IgnoreParseErrors) {
                throw new HttpException(
                    SR.GetString(SR.Only_one_directive_allowed, DefaultDirectiveName));
            }

            _fFoundMainDirective = true;

            // Since description is a no op, just remove it if it's there
            directive.Remove("description");

            // Similarily, ignore 'codebehind' attribute (ASURT 4591)
            directive.Remove("codebehind");

            string language = Util.GetAndRemoveNonEmptyAttribute(directive, "language");

            // Get the compiler for the specified language (if any)
            if (language != null) {
                _compilerType = _buildProvider.GetDefaultCompilerTypeForLanguageInternal(language);
            }
            else {
                // Get a default from config
                _compilerType = _buildProvider.GetDefaultCompilerTypeInternal();
            }

            _typeName = Util.GetAndRemoveRequiredAttribute(directive, "class");

            if (_compilerType.CompilerParameters != null)
                ProcessCompilationParams(directive, _compilerType.CompilerParameters);
        }
        else if (StringUtil.EqualsIgnoreCase(directiveName, "assembly")) {
            // Assembly directive

            // Remove the attributes as we get them from the dictionary
            string assemblyName = Util.GetAndRemoveNonEmptyAttribute(directive, "name");
            VirtualPath src = Util.GetAndRemoveVirtualPathAttribute(directive, "src");

            if (assemblyName != null && src != null && !IgnoreParseErrors) {
                throw new HttpException(
                    SR.GetString(SR.Attributes_mutually_exclusive, "Name", "Src"));
            }

            if (assemblyName != null) {
                AddAssemblyDependency(assemblyName);
            }
            // Is it a source file that needs to be compiled on the fly
            else if (src != null) {
                ImportSourceFile(src);
            }
            else if (!IgnoreParseErrors) {
                throw new HttpException(SR.GetString(SR.Missing_attr, "name"));
            }
        }
        else if (!IgnoreParseErrors) {
            throw new HttpException(
                SR.GetString(SR.Unknown_directive, directiveName));
        }

        // If there are some attributes left, fail
        Util.CheckUnknownDirectiveAttributes(directiveName, directive);
    }

    internal virtual bool IsMainDirective(string directiveName) {
        return (string.Compare(directiveName, DefaultDirectiveName,
            StringComparison.OrdinalIgnoreCase) == 0);
    }

    /*
     * Compile a source file into an assembly, and import it
     */
    private void ImportSourceFile(VirtualPath virtualPath) {

        // Get a full path to the source file
        VirtualPath baseVirtualDir = _virtualPath.Parent;
        VirtualPath fullVirtualPath = baseVirtualDir.Combine(virtualPath);

        // Add the source file to the list of files we depend on
        AddSourceDependency(fullVirtualPath);

        // 

        CompilationUtil.GetCompilerInfoFromVirtualPath(fullVirtualPath);

        // Compile it into an assembly

        BuildResultCompiledAssembly result = (BuildResultCompiledAssembly) BuildManager.GetVPathBuildResult(
            fullVirtualPath);
        Assembly a = result.ResultAssembly;

        // Add a dependency to the assembly
        AddAssemblyDependency(a);
    }

    /*
     * Add a file as a dependency for the DLL we're building
     */
    internal void AddSourceDependency(VirtualPath fileName) {
        if (_sourceDependencies == null)
            _sourceDependencies = new CaseInsensitiveStringSet();

        _sourceDependencies.Add(fileName.VirtualPathString);
    }

    private void AddAssemblyDependency(string assemblyName) {

        // Load and keep track of the assembly
        Assembly a = Assembly.Load(assemblyName);

        AddAssemblyDependency(a);
    }

    private void AddAssemblyDependency(Assembly assembly) {

        if (_linkedAssemblies == null)
            _linkedAssemblies = new AssemblySet();
        _linkedAssemblies.Add(assembly);
    }

    /*
     * Look for a type by name in the assemblies available to this page
     */
    private Type GetType(string typeName) {

        Type t;

        // If it contains an assembly name, just call Type.GetType (ASURT 53589)
        if (Util.TypeNameContainsAssembly(typeName)) {
            try {
                t = Type.GetType(typeName, true);
            }
            catch (Exception e) {
                throw new HttpParseException(null, e, _virtualPath, _sourceString, _lineNumber);
            }

            return t;
        }

        t = Util.GetTypeFromAssemblies(_referencedAssemblies, typeName, false /*ignoreCase*/);
        if (t != null)
            return t;

        t = Util.GetTypeFromAssemblies(_linkedAssemblies, typeName, false /*ignoreCase*/);
        if (t != null)
            return t;

        throw new HttpParseException(
            SR.GetString(SR.Could_not_create_type, typeName),
            null, _virtualPath, _sourceString, _lineNumber);
    }


    /// <internalonly/>
    ICollection IAssemblyDependencyParser.AssemblyDependencies {
        get {
            return AssemblyDependencies;
        }
    }
}


/// <internalonly/>
/// <devdoc>
///    <para>[To be supplied.]</para>
/// </devdoc>
internal class WebHandlerParser: SimpleWebHandlerParser {

    internal WebHandlerParser(string virtualPath)
        : base(null /*context*/, virtualPath, null /*physicalPath*/) {}


    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    protected override string DefaultDirectiveName {
        get { return "webhandler"; }
    }

    internal override void ValidateBaseType(Type t) {
        // Make sure the type has the correct base class
        Util.CheckAssignableType(typeof(IHttpHandler), t);
    }
}


/// <internalonly/>
/// <devdoc>
///    <para>[To be supplied.]</para>
/// </devdoc>
public class WebServiceParser: SimpleWebHandlerParser {


    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>

    // Only allowed in full trust (ASURT 123890)
    [SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
    public static Type GetCompiledType(string inputFile, HttpContext context) {

        // NOTE: the inputFile parameter should be named virtualPath, but cannot be changed
        // as it would be a minor breaking change! (VSWhidbey 80997).
        BuildResultCompiledType result = (BuildResultCompiledType) BuildManager.GetVPathBuildResult(
            context, VirtualPath.Create(inputFile));

        return result.ResultType;
    }

    internal WebServiceParser(string virtualPath)
        : base(null /*context*/, virtualPath, null /*physicalPath*/) { }


    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    protected override string DefaultDirectiveName {
        get { return "webservice"; }
    }
}

}