/
AspGenerator.cs
1471 lines (1244 loc) · 39.8 KB
/
AspGenerator.cs
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// System.Web.Compilation.AspGenerator
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
// Copyright (c) 2004,2006 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.Util;
namespace System.Web.Compilation
{
class BuilderLocation
{
public ControlBuilder Builder;
public ILocation Location;
public BuilderLocation (ControlBuilder builder, ILocation location)
{
this.Builder = builder;
this.Location = location;
}
}
class BuilderLocationStack : Stack
{
public override void Push (object o)
{
if (!(o is BuilderLocation))
throw new InvalidOperationException ();
base.Push (o);
}
public virtual void Push (ControlBuilder builder, ILocation location)
{
BuilderLocation bl = new BuilderLocation (builder, location);
Push (bl);
}
public new BuilderLocation Peek ()
{
return (BuilderLocation) base.Peek ();
}
public new BuilderLocation Pop ()
{
return (BuilderLocation) base.Pop ();
}
public ControlBuilder Builder {
get { return Peek ().Builder; }
}
}
class ParserStack
{
Hashtable files;
Stack parsers;
AspParser current;
public ParserStack ()
{
files = new Hashtable (); // may be this should be case sensitive for windows
parsers = new Stack ();
}
public bool Push (AspParser parser)
{
if (files.Contains (parser.Filename))
return false;
files [parser.Filename] = true;
parsers.Push (parser);
current = parser;
return true;
}
public AspParser Pop ()
{
if (parsers.Count == 0)
return null;
files.Remove (current.Filename);
AspParser result = (AspParser) parsers.Pop ();
if (parsers.Count > 0)
current = (AspParser) parsers.Peek ();
else
current = null;
return result;
}
public int Count {
get { return parsers.Count; }
}
public AspParser Parser {
get { return current; }
}
public string Filename {
get { return current.Filename; }
}
}
class TagStack
{
Stack tags;
public TagStack ()
{
tags = new Stack ();
}
public void Push (string tagid)
{
tags.Push (tagid);
}
public string Pop ()
{
if (tags.Count == 0)
return null;
return (string) tags.Pop ();
}
public bool CompareTo (string tagid)
{
if (tags.Count == 0)
return false;
return 0 == String.Compare (tagid, (string) tags.Peek (), true, CultureInfo.InvariantCulture);
}
public int Count {
get { return tags.Count; }
}
public string Current {
get { return (string) tags.Peek (); }
}
}
class AspGenerator
{
#if NET_2_0
const int READ_BUFFER_SIZE = 8192;
internal static Regex DirectiveRegex = new Regex (@"<%\s*@(\s*(?<attrname>\w[\w:]*(?=\W))(\s*(?<equal>=)\s*""(?<attrval>[^""]*)""|\s*(?<equal>=)\s*'(?<attrval>[^']*)'|\s*(?<equal>=)\s*(?<attrval>[^\s%>]*)|(?<equal>)(?<attrval>\s*?)))*\s*?%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
#endif
ParserStack pstack;
BuilderLocationStack stack;
TemplateParser tparser;
StringBuilder text;
RootBuilder rootBuilder;
bool inScript, javascript, ignore_text;
ILocation location;
bool isApplication;
StringBuilder tagInnerText = new StringBuilder ();
static Hashtable emptyHash = new Hashtable ();
bool inForm;
bool useOtherTags;
TagType lastTag;
#if NET_2_0
AspComponentFoundry componentFoundry;
Stream inputStream;
public AspGenerator (TemplateParser tparser, AspComponentFoundry componentFoundry) : this (tparser)
{
this.componentFoundry = componentFoundry;
}
#endif
public AspGenerator (TemplateParser tparser)
{
this.tparser = tparser;
text = new StringBuilder ();
stack = new BuilderLocationStack ();
#if !NET_2_0
rootBuilder = new RootBuilder (tparser);
tparser.RootBuilder = rootBuilder;
stack.Push (rootBuilder, null);
#endif
pstack = new ParserStack ();
}
public RootBuilder RootBuilder {
get { return rootBuilder; }
}
public AspParser Parser {
get { return pstack.Parser; }
}
public string Filename {
get { return pstack.Filename; }
}
#if NET_2_0
PageParserFilter PageParserFilter {
get {
if (tparser == null)
return null;
return tparser.PageParserFilter;
}
}
// KLUDGE WARNING
//
// The kludge to determine the base type of the to-be-generated ASP.NET class is
// very unfortunate but with our current parser it is, unfortunately, necessary. The
// reason for reading the entire file into memory and parsing it with a regexp is
// that we need to read the main directive (i.e. <%@Page %>, <%@Control %> etc),
// pass it to the page parser filter if it exists, and finally read the inherits
// attribute of the directive to get access to the base type of the class to be
// generated. On that type we check whether it is decorated with the
// FileLevelControlBuilder attribute and, if yes, use the indicated type as the
// RootBuilder. This is necessary for the ASP.NET MVC views using the "generic"
// inherits declaration to work properly. Our current parser is not able to parse
// the input file out of sequence (i.e. directives first, then the rest) so we need
// to do what we do below, alas.
Hashtable GetDirectiveAttributesDictionary (string skipKeyName, CaptureCollection names, CaptureCollection values)
{
var ret = new Hashtable (StringComparer.InvariantCultureIgnoreCase);
int index = 0;
string keyName;
foreach (Capture c in names) {
keyName = c.Value;
if (String.Compare (skipKeyName, keyName, StringComparison.OrdinalIgnoreCase) == 0) {
index++;
continue;
}
ret.Add (c.Value, values [index++].Value);
}
return ret;
}
string GetDirectiveName (CaptureCollection names)
{
string val;
foreach (Capture c in names) {
val = c.Value;
if (Directive.IsDirective (val))
return val;
}
return tparser.DefaultDirectiveName;
}
int GetLineNumberForIndex (string fileContents, int index)
{
int line = 1;
char c;
bool foundCR = false;
for (int pos = 0; pos < index; pos++) {
c = fileContents [pos];
if (c == '\n' || foundCR) {
line++;
foundCR = false;
}
foundCR = (c == '\r');
}
return line;
}
int GetNumberOfLinesForRange (string fileContents, int index, int length)
{
int lines = 0;
int stop = index + length;
char c;
bool foundCR = false;
for (int pos = index; pos < stop; pos++) {
c = fileContents [pos];
if (c == '\n' || foundCR) {
lines++;
foundCR = false;
}
foundCR = (c == '\r');
}
return lines;
}
Type GetInheritedType (string fileContents, string filename)
{
MatchCollection matches = DirectiveRegex.Matches (fileContents);
if (matches == null || matches.Count == 0)
return null;
string wantedDirectiveName = tparser.DefaultDirectiveName.ToLower ();
string directiveName;
GroupCollection groups;
CaptureCollection ccNames;
foreach (Match match in matches) {
groups = match.Groups;
if (groups.Count < 6)
continue;
ccNames = groups [3].Captures;
directiveName = GetDirectiveName (ccNames);
if (String.IsNullOrEmpty (directiveName))
continue;
if (String.Compare (directiveName.ToLower (), wantedDirectiveName, StringComparison.Ordinal) != 0)
continue;
var loc = new Location (null);
int index = match.Index;
loc.Filename = filename;
loc.BeginLine = GetLineNumberForIndex (fileContents, index);
loc.EndLine = loc.BeginLine + GetNumberOfLinesForRange (fileContents, index, match.Length);
tparser.Location = loc;
tparser.allowedMainDirectives = 2;
tparser.AddDirective (wantedDirectiveName, GetDirectiveAttributesDictionary (wantedDirectiveName, ccNames, groups [5].Captures));
return tparser.BaseType;
}
return null;
}
string ReadFileContents (Stream inputStream, string filename)
{
string ret = null;
if (inputStream != null) {
if (inputStream.CanSeek) {
long curPos = inputStream.Position;
inputStream.Seek (0, SeekOrigin.Begin);
Encoding enc = WebEncoding.FileEncoding;
StringBuilder sb = new StringBuilder ();
byte[] buffer = new byte [READ_BUFFER_SIZE];
int nbytes;
while ((nbytes = inputStream.Read (buffer, 0, READ_BUFFER_SIZE)) > 0)
sb.Append (enc.GetString (buffer, 0, nbytes));
inputStream.Seek (curPos, SeekOrigin.Begin);
ret = sb.ToString ();
sb.Length = 0;
sb.Capacity = 0;
} else {
FileStream fs = inputStream as FileStream;
if (fs != null) {
string fname = fs.Name;
try {
if (File.Exists (fname))
ret = File.ReadAllText (fname);
} catch {
// ignore
}
}
}
}
if (ret == null && !String.IsNullOrEmpty (filename) && String.Compare (filename, "@@inner_string@@", StringComparison.Ordinal) != 0) {
try {
if (File.Exists (filename))
ret = File.ReadAllText (filename);
} catch {
// ignore
}
}
return ret;
}
Type GetRootBuilderType (Stream inputStream, string filename)
{
Type ret = null;
string fileContents;
if (tparser != null)
fileContents = ReadFileContents (inputStream, filename);
else
fileContents = null;
if (!String.IsNullOrEmpty (fileContents)) {
Type inheritedType = GetInheritedType (fileContents, filename);
fileContents = null;
if (inheritedType != null) {
FileLevelControlBuilderAttribute attr;
try {
object[] attrs = inheritedType.GetCustomAttributes (typeof (FileLevelControlBuilderAttribute), true);
if (attrs != null && attrs.Length > 0)
attr = attrs [0] as FileLevelControlBuilderAttribute;
else
attr = null;
} catch {
attr = null;
}
ret = attr != null ? attr.BuilderType : null;
}
}
if (ret == null) {
if (tparser is PageParser)
return typeof (FileLevelPageControlBuilder);
else if (tparser is UserControlParser)
return typeof (FileLevelUserControlBuilder);
else
return typeof (RootBuilder);
} else
return ret;
}
void CreateRootBuilder (Stream inputStream, string filename)
{
Type rootBuilderType = GetRootBuilderType (inputStream, filename);
rootBuilder = Activator.CreateInstance (rootBuilderType) as RootBuilder;
if (rootBuilder == null)
throw new HttpException ("Cannot create an instance of file-level control builder.");
rootBuilder.Init (tparser, null, null, null, null, null);
if (componentFoundry != null)
rootBuilder.Foundry = componentFoundry;
stack.Push (rootBuilder, null);
tparser.RootBuilder = rootBuilder;
}
#endif
BaseCompiler GetCompilerFromType ()
{
Type type = tparser.GetType ();
if (type == typeof (PageParser))
return new PageCompiler ((PageParser) tparser);
if (type == typeof (ApplicationFileParser))
return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
if (type == typeof (UserControlParser))
return new UserControlCompiler ((UserControlParser) tparser);
#if NET_2_0
if (type == typeof(MasterPageParser))
return new MasterPageCompiler ((MasterPageParser) tparser);
#endif
throw new Exception ("Got type: " + type);
}
void InitParser (TextReader reader, string filename)
{
AspParser parser = new AspParser (filename, reader);
parser.Error += new ParseErrorHandler (ParseError);
parser.TagParsed += new TagParsedHandler (TagParsed);
parser.TextParsed += new TextParsedHandler (TextParsed);
#if NET_2_0
parser.ParsingComplete += new ParsingCompleteHandler (ParsingCompleted);
tparser.AspGenerator = this;
CreateRootBuilder (inputStream, filename);
#endif
if (!pstack.Push (parser))
throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
if (filename != "@@inner_string@@") {
string arvp = Path.Combine (tparser.BaseVirtualDir, Path.GetFileName (filename));
if (VirtualPathUtility.IsAbsolute (arvp))
arvp = VirtualPathUtility.ToAppRelative (arvp);
tparser.AddDependency (arvp);
}
}
#if NET_2_0
void InitParser (string filename)
{
StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
InitParser (reader, filename);
}
#endif
public void Parse (string file)
{
#if ONLY_1_1
Parse (file, true);
#else
Parse (file, false);
#endif
}
public void Parse (TextReader reader, string filename, bool doInitParser)
{
try {
isApplication = tparser.DefaultDirectiveName == "application";
if (doInitParser)
InitParser (reader, filename);
pstack.Parser.Parse ();
if (text.Length > 0)
FlushText ();
#if NET_2_0
tparser.MD5Checksum = pstack.Parser.MD5Checksum;
#endif
pstack.Pop ();
#if DEBUG
PrintTree (RootBuilder, 0);
#endif
if (stack.Count > 1 && pstack.Count == 0)
throw new ParseException (stack.Builder.Location,
"Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
} finally {
if (reader != null)
reader.Close ();
}
}
public void Parse (Stream stream, string filename, bool doInitParser)
{
#if NET_2_0
inputStream = stream;
#endif
Parse (new StreamReader (stream, WebEncoding.FileEncoding), filename, doInitParser);
}
public void Parse (string filename, bool doInitParser)
{
StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
Parse (reader, filename, doInitParser);
}
public void Parse ()
{
#if NET_2_0
string inputFile = tparser.InputFile;
TextReader inputReader = tparser.Reader;
try {
if (String.IsNullOrEmpty (inputFile)) {
StreamReader sr = inputReader as StreamReader;
if (sr != null) {
FileStream fr = sr.BaseStream as FileStream;
if (fr != null)
inputFile = fr.Name;
}
if (String.IsNullOrEmpty (inputFile))
inputFile = "@@inner_string@@";
}
if (inputReader != null) {
Parse (inputReader, inputFile, true);
} else {
if (String.IsNullOrEmpty (inputFile))
throw new HttpException ("Parser input file is empty, cannot continue.");
inputFile = Path.GetFullPath (inputFile);
InitParser (inputFile);
Parse (inputFile);
}
} finally {
if (inputReader != null)
inputReader.Close ();
}
#else
Parse (Path.GetFullPath (tparser.InputFile));
#endif
}
internal static void AddTypeToCache (ArrayList dependencies, string inputFile, Type type)
{
if (type == null || inputFile == null || inputFile.Length == 0)
return;
if (dependencies != null && dependencies.Count > 0) {
string [] deps = (string []) dependencies.ToArray (typeof (string));
HttpContext ctx = HttpContext.Current;
HttpRequest req = ctx != null ? ctx.Request : null;
if (req == null)
throw new HttpException ("No current context, cannot compile.");
for (int i = 0; i < deps.Length; i++)
deps [i] = req.MapPath (deps [i]);
HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type, new CacheDependency (deps));
} else
HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type);
}
public Type GetCompiledType ()
{
Type type = (Type) HttpRuntime.InternalCache.Get ("@@Type" + tparser.InputFile);
if (type != null) {
return type;
}
Parse ();
BaseCompiler compiler = GetCompilerFromType ();
type = compiler.GetCompiledType ();
AddTypeToCache (tparser.Dependencies, tparser.InputFile, type);
return type;
}
#if DEBUG
static void PrintTree (ControlBuilder builder, int indent)
{
if (builder == null)
return;
string i = new string ('\t', indent);
Console.Write (i);
Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
builder, builder.ID, builder.ControlType, builder.ParentBuilder);
if (builder.Children != null)
foreach (object o in builder.Children) {
if (o is ControlBuilder)
PrintTree ((ControlBuilder) o, indent++);
}
}
static void PrintLocation (ILocation loc)
{
Console.WriteLine ("\tFile name: " + loc.Filename);
Console.WriteLine ("\tBegin line: " + loc.BeginLine);
Console.WriteLine ("\tEnd line: " + loc.EndLine);
Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
Console.WriteLine ("\tEnd column: " + loc.EndColumn);
Console.WriteLine ("\tPlainText: " + loc.PlainText);
Console.WriteLine ();
}
#endif
void ParseError (ILocation location, string message)
{
throw new ParseException (location, message);
}
// KLUDGE WARNING!!
//
// The code below (ProcessTagsInAttributes, ParseAttributeTag) serves the purpose to work
// around a limitation of the current asp.net parser which is unable to parse server
// controls inside client tag attributes. Since the architecture of the current
// parser does not allow for clean solution of this problem, hence the kludge
// below. It will be gone as soon as the parser is rewritten.
//
// The kludge supports only self-closing tags inside attributes.
//
// KLUDGE WARNING!!
static readonly Regex runatServer=new Regex (@"<[\w:\.]+.*?runat=[""']?server[""']?.*?/>",
RegexOptions.Compiled | RegexOptions.Singleline |
RegexOptions.Multiline | RegexOptions.IgnoreCase |
RegexOptions.CultureInvariant);
bool ProcessTagsInAttributes (ILocation location, string tagid, TagAttributes attributes, TagType type)
{
if (attributes == null || attributes.Count == 0)
return false;
Match match;
Group group;
string value;
bool retval = false;
int index, length;
StringBuilder sb = new StringBuilder ();
sb.AppendFormat ("\t<{0}", tagid);
foreach (string key in attributes.Keys) {
value = attributes [key] as string;
if (value == null || value.Length < 16) { // optimization
sb.AppendFormat (" {0}=\"{1}\"", key, value);
continue;
}
match = runatServer.Match (attributes [key] as string);
if (!match.Success) {
sb.AppendFormat (" {0}=\"{1}\"", key, value);
continue;
}
if (sb.Length > 0) {
TextParsed (location, sb.ToString ());
sb.Length = 0;
}
retval = true;
group = match.Groups [0];
index = group.Index;
length = group.Length;
TextParsed (location, String.Format (" {0}=\"{1}", key, index > 0 ? value.Substring (0, index) : String.Empty));;
FlushText ();
ParseAttributeTag (group.Value);
if (index + length < value.Length)
TextParsed (location, value.Substring (index + length) + "\"");
else
TextParsed (location, "\"");
}
if (type == TagType.SelfClosing)
sb.Append ("/>");
else
sb.Append (">");
if (retval && sb.Length > 0)
TextParsed (location, sb.ToString ());
return retval;
}
void ParseAttributeTag (string code)
{
AspParser parser = new AspParser ("@@attribute_tag@@", new StringReader (code));
parser.Error += new ParseErrorHandler (ParseError);
parser.TagParsed += new TagParsedHandler (TagParsed);
parser.TextParsed += new TextParsedHandler (TextParsed);
parser.Parse ();
if (text.Length > 0)
FlushText ();
}
#if NET_2_0
void ParsingCompleted ()
{
PageParserFilter pfilter = PageParserFilter;
if (pfilter == null)
return;
pfilter.ParseComplete (RootBuilder);
}
#endif
void CheckIfIncludeFileIsSecure (string filePath)
{
if (filePath == null || filePath.Length == 0)
return;
// a bit slow, but fully portable
string newdir = null;
Exception exception = null;
try {
string origdir = Directory.GetCurrentDirectory ();
Directory.SetCurrentDirectory (Path.GetDirectoryName (filePath));
newdir = Directory.GetCurrentDirectory ();
Directory.SetCurrentDirectory (origdir);
if (newdir [newdir.Length - 1] != '/')
newdir += "/";
} catch (DirectoryNotFoundException ex) {
return; // will be converted into 404
} catch (FileNotFoundException ex) {
return; // as above
} catch (Exception ex) {
// better safe than sorry
exception = ex;
}
if (exception != null || !StrUtils.StartsWith (newdir, HttpRuntime.AppDomainAppPath))
throw new ParseException (Location, "Files above the application's root directory cannot be included.");
}
void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
{
bool tagIgnored;
this.location = new Location (location);
if (tparser != null)
tparser.Location = location;
if (text.Length != 0)
FlushText (lastTag == TagType.CodeRender);
if (0 == String.Compare (tagid, "script", true, CultureInfo.InvariantCulture)) {
bool in_script = (inScript || ignore_text);
if (in_script) {
if (ProcessScript (tagtype, attributes))
return;
} else
if (ProcessScript (tagtype, attributes))
return;
}
lastTag = tagtype;
switch (tagtype) {
case TagType.Directive:
if (tagid.Length == 0)
tagid = tparser.DefaultDirectiveName;
tparser.AddDirective (tagid, attributes.GetDictionary (null));
break;
case TagType.Tag:
if (ProcessTag (location, tagid, attributes, tagtype, out tagIgnored)) {
if (!tagIgnored)
useOtherTags = true;
break;
}
if (useOtherTags) {
stack.Builder.EnsureOtherTags ();
stack.Builder.OtherTags.Add (tagid);
}
{
string plainText = location.PlainText;
if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.Tag))
TextParsed (location, plainText);
}
break;
case TagType.Close:
bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
if (!notServer && CloseControl (tagid))
break;
TextParsed (location, location.PlainText);
break;
case TagType.SelfClosing:
int count = stack.Count;
if (!ProcessTag (location, tagid, attributes, tagtype, out tagIgnored) && !tagIgnored) {
string plainText = location.PlainText;
if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.SelfClosing))
TextParsed (location, plainText);
} else if (stack.Count != count) {
CloseControl (tagid);
}
break;
case TagType.DataBinding:
goto case TagType.CodeRender;
case TagType.CodeRenderExpression:
goto case TagType.CodeRender;
case TagType.CodeRender:
if (isApplication)
throw new ParseException (location, "Invalid content for application file.");
ProcessCode (tagtype, tagid, location);
break;
case TagType.Include:
if (isApplication)
throw new ParseException (location, "Invalid content for application file.");
string file = attributes ["virtual"] as string;
bool isvirtual = (file != null);
if (!isvirtual)
file = attributes ["file"] as string;
if (isvirtual) {
bool parsed = false;
#if NET_2_0
VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
if (vpp.FileExists (file)) {
VirtualFile vf = vpp.GetFile (file);
if (vf != null) {
Parse (vf.Open (), file, true);
parsed = true;
}
}
#endif
if (!parsed)
Parse (tparser.MapPath (file), true);
} else {
string includeFilePath = GetIncludeFilePath (tparser.ParserDir, file);
CheckIfIncludeFileIsSecure (includeFilePath);
tparser.PushIncludeDir (Path.GetDirectoryName (includeFilePath));
try {
Parse (includeFilePath, true);
} finally {
tparser.PopIncludeDir ();
}
}
break;
default:
break;
}
//PrintLocation (location);
}
static bool TryRemoveTag (string tagid, ArrayList otags)
{
if (otags == null || otags.Count == 0)
return false;
for (int idx = otags.Count - 1; idx >= 0; idx--) {
string otagid = (string) otags [idx];
if (0 == String.Compare (tagid, otagid, true, CultureInfo.InvariantCulture)) {
do {
otags.RemoveAt (idx);
} while (otags.Count - 1 >= idx);
return true;
}
}
return false;
}
static string GetIncludeFilePath (string basedir, string filename)
{
if (Path.DirectorySeparatorChar == '/')
filename = filename.Replace ("\\", "/");
return Path.GetFullPath (Path.Combine (basedir, filename));
}
void TextParsed (ILocation location, string text)
{
if (ignore_text)
return;
// And again... the first one wins - if we have expressions and server-side
// controls together in one block of plain text, tough luck...
if (text.IndexOf ("<%") != -1 && !inScript) {
if (this.text.Length > 0)
FlushText (true);
CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
r.AddChildren (this);
return;
}
int startIndex = 0, index = 0;
Match match;
int textLen = text.Length;
while (index > -1 && startIndex < textLen) {
match = runatServer.Match (text, index);
if (match.Success) {
string value = match.Value;
index = match.Index;
if (index > startIndex)
this.text.Append (text.Substring (startIndex, index - startIndex));
ParseAttributeTag (value);
index += value.Length;
startIndex = index;
} else
break;
if (index < textLen)
index = text.IndexOf ('<', index);
else
break;
}
this.text.Append (text.Substring (startIndex));
//PrintLocation (location);
}
void FlushText ()
{
FlushText (false);
}
void FlushText (bool ignoreEmptyString)
{
string t = text.ToString ();
text.Length = 0;