A slightly more elegant way of dealing with 'item==null' issue
[mono.git] / mcs / class / System.Web / System.Web.UI / SimpleWebHandlerParser.cs
1 //
2 // System.Web.UI.SimpleWebHandlerParser
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System.CodeDom.Compiler;
31 using System.Collections;
32 using System.IO;
33 using System.Reflection;
34 using System.Security.Permissions;
35 using System.Text;
36 using System.Web.Compilation;
37 using System.Web.Configuration;
38 using System.Web.Util;
39
40 namespace System.Web.UI
41 {
42         // CAS
43         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44         [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
45         public abstract class SimpleWebHandlerParser
46         {
47                 HttpContext context;
48                 string vPath;
49                 string physPath;
50                 string className;
51                 bool debug;
52                 string language;
53                 string program;
54                 bool gotDefault;
55                 ArrayList assemblies;
56                 ArrayList dependencies;
57                 Hashtable anames;
58                 string privateBinPath;
59                 string baseDir;
60                 string baseVDir;
61 #if !NET_2_0
62                 CompilationConfiguration compilationConfig;
63 #else
64                 TextReader reader;
65 #endif
66                 int appAssemblyIndex = -1;
67                 Type cachedType;
68
69                 protected SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath)
70                 {
71                         cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
72                         if (cachedType != null)
73                                 return; // We don't need anything else.
74
75                         this.context = context;
76                         this.vPath = virtualPath;
77                         this.physPath = physicalPath;
78                         AddDependency (physicalPath);
79
80                         assemblies = new ArrayList ();
81                         string location = Context.ApplicationInstance.AssemblyLocation;
82                         if (location != typeof (TemplateParser).Assembly.Location)
83                                 appAssemblyIndex = assemblies.Add (location);
84
85 #if NET_2_0
86                         bool addAssembliesInBin = false;
87                         foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
88                                 if (info.Assembly == "*")
89                                         addAssembliesInBin = true;
90                                 else
91                                         AddAssemblyByName (info.Assembly, null);
92                         }
93                         if (addAssembliesInBin)
94                                 AddAssembliesInBin ();
95 #else
96                         assemblies.AddRange (CompilationConfig.Assemblies);
97                         if (CompilationConfig.AssembliesInBin)
98                                 AddAssembliesInBin ();
99 #endif
100
101                         language = CompilationConfig.DefaultLanguage;
102
103                         GetDirectivesAndContent ();
104                 }
105 #if NET_2_0
106                 internal SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath, TextReader reader)
107                         : this (context, virtualPath, physicalPath)
108                 {
109                         this.reader = reader;
110                 }
111 #endif
112
113                 protected Type GetCompiledTypeFromCache ()
114                 {
115                         return cachedType;
116                 }
117
118                 void GetDirectivesAndContent ()
119                 {
120                         string line;
121                         bool directiveFound = false;
122                         bool inDirective = false;
123                         StringBuilder directive = null;
124                         StringBuilder content = new StringBuilder ();
125                         int idxStart, idxEnd, length;                   
126
127                         using (StreamReader reader = new StreamReader (File.OpenRead (physPath))) {
128                                 while ((line = reader.ReadLine ()) != null && cachedType == null) {
129                                         length = line.Length;
130                                         if (length == 0) {
131                                                 content.Append ("\n");
132                                                 continue;
133                                         }
134                                         
135                                         idxStart = line.IndexOf ("<%");
136                                         if (idxStart > -1) {
137                                                 idxEnd = line.IndexOf ("%>");                                           
138                                                 if (idxStart > 0)
139                                                         content.Append (line.Substring (0, idxStart));
140
141                                                 if (directive == null)
142                                                         directive = new StringBuilder ();
143                                                 else
144                                                         directive.Length = 0;
145                                                 
146                                                 if (idxEnd > -1) {
147                                                         directiveFound = true;
148                                                         inDirective = false;
149                                                         directive.Append (line.Substring (idxStart, idxEnd - idxStart + 2));
150                                                         if (idxEnd < length - 2)
151                                                                 content.Append (line.Substring (idxEnd + 2, length - idxEnd - 2));
152                                                 } else {
153                                                         inDirective = true;
154                                                         directiveFound = false;
155                                                         directive.Append (line.Substring (idxStart));
156                                                         continue;
157                                                 }
158                                         }
159
160                                         if (inDirective) {
161                                                 int idx = line.IndexOf ("%>");
162                                                 if (idx > -1) {
163                                                         directive.Append (line.Substring (0, idx + 2));
164                                                         if (idx < length)
165                                                                 content.Append (line.Substring (idx + 2) + "\n");
166                                                         inDirective = false;
167                                                         directiveFound = true;
168                                                 } else {
169                                                         directive.Append (line);
170                                                         continue;
171                                                 }
172                                         }
173                                         
174                                         if (directiveFound) {
175                                                 ParseDirective (directive.ToString ());
176                                                 directiveFound = false;
177                                                 if (gotDefault) {
178                                                         cachedType = CachingCompiler.GetTypeFromCache (physPath);
179                                                         if (cachedType != null)
180                                                                 break;
181                                                 }
182
183                                                 continue;
184                                         }
185
186                                         content.Append (line + "\n");
187                                 }
188                                 directive = null;
189                         }
190
191                         if (!gotDefault)
192                                 throw new ParseException (null, "No @" + DefaultDirectiveName +
193                                                         " directive found");
194
195                         if (cachedType == null)
196                                 this.program = content.ToString ();
197                 }
198
199                 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
200                 {
201                         if (tagtype != System.Web.Compilation.TagType.Directive)
202                                 throw new ParseException (location, "Unexpected tag");
203
204                         if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
205                                 AddDefaultDirective (location, attributes);
206                         } else if (String.Compare (tagid, "Assembly", true) == 0) {
207                                 AddAssemblyDirective (location, attributes);
208                         } else {
209                                 throw new ParseException (location, "Unexpected directive: " + tagid);
210                         }
211                 }
212
213                 void TextParsed (ILocation location, string text)
214                 {
215                         if (text.Trim () != "")
216                                 throw new ParseException (location, "Text not allowed here");
217                 }
218
219                 void ParseError (ILocation location, string message)
220                 {
221                         throw new ParseException (location, message);
222                 }
223
224                 static string GetAndRemove (Hashtable table, string key)
225                 {
226                         string o = table [key] as string;
227                         table.Remove (key);
228                         return o;
229                 }
230                 
231                 void ParseDirective (string line)
232                 {
233                         AspParser parser = new AspParser (physPath, new StringReader (line));
234                         parser.Error += new ParseErrorHandler (ParseError);
235                         parser.TagParsed += new TagParsedHandler (TagParsed);
236                         parser.TextParsed += new TextParsedHandler (TextParsed);
237
238                         parser.Parse ();
239                 }
240
241                 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
242                 {
243                         if (gotDefault)
244                                 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
245
246                         gotDefault = true;
247                         Hashtable attributes = attrs.GetDictionary (null);
248                         className = GetAndRemove (attributes, "class");
249                         if (className == null)
250                                 throw new ParseException (null, "No Class attribute found.");
251                         
252                         string d = GetAndRemove (attributes, "debug");
253                         if (d != null) {
254                                 debug = (String.Compare (d, "true", true) == 0);
255                                 if (debug == false && String.Compare (d, "false", true) != 0)
256                                         throw new ParseException (null, "Invalid value for Debug attribute");
257                         }
258
259                         language = GetAndRemove (attributes, "language");
260                         if (language == null)
261                                 language = CompilationConfig.DefaultLanguage;
262
263                         GetAndRemove (attributes, "codebehind");
264                         if (attributes.Count > 0)
265                                 throw new ParseException (location, "Unrecognized attribute in " +
266                                                           DefaultDirectiveName + " directive");
267                 }
268
269                 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
270                 {
271                         Hashtable tbl = attrs.GetDictionary (null);
272                         string name = GetAndRemove (tbl, "Name");
273                         string src = GetAndRemove (tbl, "Src");
274                         if (name == null && src == null)
275                                 throw new ParseException (location, "You gotta specify Src or Name");
276
277                         if (name != null && src != null)
278                                 throw new ParseException (location, "Src and Name cannot be used together");
279
280                         if (name != null) {
281                                 AddAssemblyByName (name, location);
282                         } else {
283                                 GetAssemblyFromSource (src, location);
284                         }
285
286                         if (tbl.Count > 0)
287                                 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
288                 }
289
290                 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
291                 {
292                         if (anames == null)
293                                 anames = new Hashtable ();
294
295                         string name = assembly.GetName ().Name;
296                         string loc = assembly.Location;
297                         if (fullPath) {
298                                 if (!assemblies.Contains (loc)) {
299                                         assemblies.Add (loc);
300                                 }
301
302                                 anames [name] = loc;
303                                 anames [loc] = assembly;
304                         } else {
305                                 if (!assemblies.Contains (name)) {
306                                         assemblies.Add (name);
307                                 }
308
309                                 anames [name] = assembly;
310                         }
311                 }
312
313                 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
314                 {
315                         if (anames == null)
316                                 anames = new Hashtable ();
317
318                         if (anames.Contains (name)) {
319                                 object o = anames [name];
320                                 if (o is string)
321                                         o = anames [o];
322
323                                 return (Assembly) o;
324                         }
325
326                         Assembly assembly = LoadAssemblyFromBin (name);
327                         if (assembly != null) {
328                                 AddAssembly (assembly, true);
329                                 return assembly;
330                         }
331
332                         try {
333                                 assembly = Assembly.LoadWithPartialName (name);
334                         } catch (Exception e) {
335                                 throw new ParseException (location, "Assembly " + name + " not found", e);
336                         }
337
338                         AddAssembly (assembly, true);
339                         return assembly;
340                 }
341
342                 void AddAssembliesInBin ()
343                 {
344                         foreach (string s in HttpApplication.BinDirectoryAssemblies) {
345                                 try {
346                                         Assembly assembly = Assembly.LoadFrom (s);
347                                         AddAssembly (assembly, true);
348                                 } catch (Exception e) {
349                                         throw new Exception ("Error while loading " + s, e);
350                                 }
351                         }
352                 }
353
354                 Assembly LoadAssemblyFromBin (string name)
355                 {
356                         Assembly assembly = null;
357                         foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
358                                 string fn = Path.GetFileName (dll);
359                                 fn = Path.ChangeExtension (fn, null);
360                                 if (fn != name)
361                                         continue;
362
363                                 assembly = Assembly.LoadFrom (dll);
364                                 return assembly;
365                         }
366                         
367                         return null;
368                 }
369
370                 Assembly GetAssemblyFromSource (string vpath, ILocation location)
371                 {
372                         vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
373                         string realPath = context.Request.MapPath (vpath);
374                         if (!File.Exists (realPath))
375                                 throw new ParseException (location, "File " + vpath + " not found");
376
377                         AddDependency (realPath);
378
379                         CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
380                         if (result.NativeCompilerReturnValue != 0) {
381                                 StreamReader reader = new StreamReader (realPath);
382                                 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
383                         }
384
385                         AddAssembly (result.CompiledAssembly, true);
386                         return result.CompiledAssembly;
387                 }
388                 
389                 internal Type GetTypeFromBin (string typeName)
390                 {
391                         Type result = null;
392                         
393 #if NET_2_0
394                         IList toplevelAssemblies = BuildManager.TopLevelAssemblies;
395                         if (toplevelAssemblies != null && toplevelAssemblies.Count > 0) {
396                                 foreach (Assembly asm in toplevelAssemblies) {
397                                         Type type = asm.GetType (typeName, false);
398                                         if (type != null) {
399                                                 if (result != null)
400                                                         throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
401                                                 result = type;
402                                         }
403                                 }
404                         }
405 #endif
406
407                         foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
408                                 Assembly assembly = Assembly.LoadFrom (dll);
409                                 Type type = assembly.GetType (typeName, false);
410                                 if (type != null) {
411                                         if (result != null) 
412                                                 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
413                                                 
414                                         result = type;
415                                 } 
416                         }
417
418                         
419                         if (result == null)
420                                 throw new HttpException (String.Format ("Type {0} not found.", typeName));
421
422                         return result;
423                 }
424                 
425                 internal virtual void AddDependency (string filename)
426                 {
427                         if (dependencies == null)
428                                 dependencies = new ArrayList ();
429
430                         if (!dependencies.Contains (filename))
431                                 dependencies.Add (filename);
432                 }
433                 
434                 // Properties
435                 protected abstract string DefaultDirectiveName { get; }
436
437                 internal HttpContext Context {
438                         get { return context; }
439                 }
440
441                 internal string VirtualPath {
442                         get { return vPath; }
443                 }
444
445                 internal string PhysicalPath {
446                         get { return physPath; }
447                 }
448
449                 internal string ClassName {
450                         get { return className; }
451                 }
452
453                 internal bool Debug {
454                         get { return debug; }
455                 }
456
457                 internal string Language {
458                         get { return language; }
459                 }
460
461                 internal string Program {
462                         get { return program; }
463                 }
464
465                 internal ArrayList Assemblies {
466                         get {
467                                 if (appAssemblyIndex != -1) {
468                                         object o = assemblies [appAssemblyIndex];
469                                         assemblies.RemoveAt (appAssemblyIndex);
470                                         assemblies.Add (o);
471                                         appAssemblyIndex = -1;
472                                 }
473
474                                 return assemblies;
475                         }
476                 }
477
478                 internal ArrayList Dependencies {
479                         get { return dependencies; }
480                 }
481
482                 internal string BaseDir {
483                         get {
484                                 if (baseDir == null)
485                                         baseDir = context.Request.MapPath (BaseVirtualDir);
486
487                                 return baseDir;
488                         }
489                 }
490
491                 internal virtual string BaseVirtualDir {
492                         get {
493                                 if (baseVDir == null)
494                                         baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
495
496                                 return baseVDir;
497                         }
498                 }
499
500 #if NET_2_0
501                 CompilationSection CompilationConfig {
502                         get {
503                                 return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
504                         }
505                 }
506
507                 internal TextReader Reader {
508                         get { return reader; }
509                         set { reader = value; }
510                 }
511 #else
512                 internal CompilationConfiguration CompilationConfig {
513                         get {
514                                 if (compilationConfig == null)
515                                         compilationConfig = CompilationConfiguration.GetInstance (context);
516
517                                 return compilationConfig;
518                         }
519                 }
520 #endif
521         }
522 }
523