New test.
[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                         StreamReader reader = new StreamReader (File.OpenRead (physPath));
121                         string line;
122                         bool directiveFound = false;
123                         StringBuilder content = new StringBuilder ();
124
125                         while ((line = reader.ReadLine ()) != null && cachedType == null) {
126                                 string trimmed = line.Trim ();
127                                 if (!directiveFound && trimmed == String.Empty)
128                                         continue;
129                                 
130                                 if (trimmed.StartsWith ("<")) {
131                                         ParseDirective (trimmed);
132                                         directiveFound = true;
133                                         if (gotDefault) {
134                                                 cachedType = CachingCompiler.GetTypeFromCache (physPath);
135                                                 if (cachedType != null)
136                                                         break;
137                                         }
138
139                                         continue;
140                                 }
141
142                                 content.Append (line + "\n");
143                                 content.Append (reader.ReadToEnd ());
144                         }
145                         reader.Close ();
146
147                         if (!gotDefault)
148                                 throw new ParseException (null, "No @" + DefaultDirectiveName +
149                                                         " directive found");
150
151                         if (cachedType == null)
152                                 this.program = content.ToString ();
153                 }
154
155                 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
156                 {
157                         if (tagtype != System.Web.Compilation.TagType.Directive)
158                                 throw new ParseException (location, "Unexpected tag");
159
160                         if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
161                                 AddDefaultDirective (location, attributes);
162                         } else if (String.Compare (tagid, "Assembly", true) == 0) {
163                                 AddAssemblyDirective (location, attributes);
164                         } else {
165                                 throw new ParseException (location, "Unexpected directive: " + tagid);
166                         }
167                 }
168
169                 void TextParsed (ILocation location, string text)
170                 {
171                         if (text.Trim () != "")
172                                 throw new ParseException (location, "Text not allowed here");
173                 }
174
175                 void ParseError (ILocation location, string message)
176                 {
177                         throw new ParseException (location, message);
178                 }
179
180                 static string GetAndRemove (Hashtable table, string key)
181                 {
182                         string o = table [key] as string;
183                         table.Remove (key);
184                         return o;
185                 }
186                 
187                 void ParseDirective (string line)
188                 {
189                         AspParser parser = new AspParser (physPath, new StringReader (line));
190                         parser.Error += new ParseErrorHandler (ParseError);
191                         parser.TagParsed += new TagParsedHandler (TagParsed);
192                         parser.TextParsed += new TextParsedHandler (TextParsed);
193
194                         parser.Parse ();
195                 }
196
197                 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
198                 {
199                         if (gotDefault)
200                                 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
201
202                         gotDefault = true;
203                         Hashtable attributes = attrs.GetDictionary (null);
204                         className = GetAndRemove (attributes, "class");
205                         if (className == null)
206                                 throw new ParseException (null, "No Class attribute found.");
207                         
208                         string d = GetAndRemove (attributes, "debug");
209                         if (d != null) {
210                                 debug = (String.Compare (d, "true", true) == 0);
211                                 if (debug == false && String.Compare (d, "false", true) != 0)
212                                         throw new ParseException (null, "Invalid value for Debug attribute");
213                         }
214
215                         language = GetAndRemove (attributes, "language");
216                         if (language == null)
217                                 language = CompilationConfig.DefaultLanguage;
218
219                         GetAndRemove (attributes, "codebehind");
220                         if (attributes.Count > 0)
221                                 throw new ParseException (location, "Unrecognized attribute in " +
222                                                           DefaultDirectiveName + " directive");
223                 }
224
225                 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
226                 {
227                         Hashtable tbl = attrs.GetDictionary (null);
228                         string name = GetAndRemove (tbl, "Name");
229                         string src = GetAndRemove (tbl, "Src");
230                         if (name == null && src == null)
231                                 throw new ParseException (location, "You gotta specify Src or Name");
232
233                         if (name != null && src != null)
234                                 throw new ParseException (location, "Src and Name cannot be used together");
235
236                         if (name != null) {
237                                 AddAssemblyByName (name, location);
238                         } else {
239                                 GetAssemblyFromSource (src, location);
240                         }
241
242                         if (tbl.Count > 0)
243                                 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
244                 }
245
246                 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
247                 {
248                         if (anames == null)
249                                 anames = new Hashtable ();
250
251                         string name = assembly.GetName ().Name;
252                         string loc = assembly.Location;
253                         if (fullPath) {
254                                 if (!assemblies.Contains (loc)) {
255                                         assemblies.Add (loc);
256                                 }
257
258                                 anames [name] = loc;
259                                 anames [loc] = assembly;
260                         } else {
261                                 if (!assemblies.Contains (name)) {
262                                         assemblies.Add (name);
263                                 }
264
265                                 anames [name] = assembly;
266                         }
267                 }
268
269                 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
270                 {
271                         if (anames == null)
272                                 anames = new Hashtable ();
273
274                         if (anames.Contains (name)) {
275                                 object o = anames [name];
276                                 if (o is string)
277                                         o = anames [o];
278
279                                 return (Assembly) o;
280                         }
281
282                         Assembly assembly = LoadAssemblyFromBin (name);
283                         if (assembly != null) {
284                                 AddAssembly (assembly, true);
285                                 return assembly;
286                         }
287
288                         try {
289                                 assembly = Assembly.LoadWithPartialName (name);
290                         } catch (Exception e) {
291                                 throw new ParseException (location, "Assembly " + name + " not found", e);
292                         }
293
294                         AddAssembly (assembly, true);
295                         return assembly;
296                 }
297
298                 void AddAssembliesInBin ()
299                 {
300                         if (!Directory.Exists (PrivateBinPath))
301                                 return;
302
303                         string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
304                         foreach (string dll in binDlls) {
305                                 try {
306                                         Assembly assembly = Assembly.LoadFrom (dll);
307                                         AddAssembly (assembly, true);
308                                 } catch (Exception e) {
309                                         throw new Exception ("Error while loading " + dll, e);
310                                 }
311                         }
312                 }
313
314                 Assembly LoadAssemblyFromBin (string name)
315                 {
316                         Assembly assembly;
317                         if (!Directory.Exists (PrivateBinPath))
318                                 return null;
319
320                         string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
321                         foreach (string dll in binDlls) {
322                                 string fn = Path.GetFileName (dll);
323                                 fn = Path.ChangeExtension (fn, null);
324                                 if (fn != name)
325                                         continue;
326
327                                 assembly = Assembly.LoadFrom (dll);
328                                 return assembly;
329                         }
330
331                         return null;
332                 }
333
334                 Assembly GetAssemblyFromSource (string vpath, ILocation location)
335                 {
336                         vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
337                         string realPath = context.Request.MapPath (vpath);
338                         if (!File.Exists (realPath))
339                                 throw new ParseException (location, "File " + vpath + " not found");
340
341                         AddDependency (realPath);
342
343                         CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
344                         if (result.NativeCompilerReturnValue != 0) {
345                                 StreamReader reader = new StreamReader (realPath);
346                                 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
347                         }
348
349                         AddAssembly (result.CompiledAssembly, true);
350                         return result.CompiledAssembly;
351                 }
352                 
353                 internal Type GetTypeFromBin (string typeName)
354                 {
355                         if (!Directory.Exists (PrivateBinPath))
356                                 throw new HttpException (String.Format ("Type {0} not found.", typeName));
357
358                         string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
359                         Type result = null;
360                         foreach (string dll in binDlls) {
361                                 Assembly assembly = Assembly.LoadFrom (dll);
362                                 Type type = assembly.GetType (typeName, false);
363                                 if (type != null) {
364                                         if (result != null) 
365                                                 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
366
367                                         result = type;
368                                 } 
369                         }
370
371                         if (result == null)
372                                 throw new HttpException (String.Format ("Type {0} not found.", typeName));
373
374                         return result;
375                 }
376                 
377                 internal virtual void AddDependency (string filename)
378                 {
379                         if (dependencies == null)
380                                 dependencies = new ArrayList ();
381
382                         if (!dependencies.Contains (filename))
383                                 dependencies.Add (filename);
384                 }
385                 
386                 // Properties
387                 protected abstract string DefaultDirectiveName { get; }
388
389                 internal HttpContext Context {
390                         get { return context; }
391                 }
392
393                 internal string VirtualPath {
394                         get { return vPath; }
395                 }
396
397                 internal string PhysicalPath {
398                         get { return physPath; }
399                 }
400
401                 internal string ClassName {
402                         get { return className; }
403                 }
404
405                 internal bool Debug {
406                         get { return debug; }
407                 }
408
409                 internal string Language {
410                         get { return language; }
411                 }
412
413                 internal string Program {
414                         get { return program; }
415                 }
416
417                 internal ArrayList Assemblies {
418                         get {
419                                 if (appAssemblyIndex != -1) {
420                                         object o = assemblies [appAssemblyIndex];
421                                         assemblies.RemoveAt (appAssemblyIndex);
422                                         assemblies.Add (o);
423                                         appAssemblyIndex = -1;
424                                 }
425
426                                 return assemblies;
427                         }
428                 }
429
430                 internal ArrayList Dependencies {
431                         get { return dependencies; }
432                 }
433
434                 internal string PrivateBinPath {
435                         get {
436                                 if (privateBinPath != null)
437                                         return privateBinPath;
438
439                                 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
440                                 privateBinPath = setup.PrivateBinPath;
441                                         
442                                 if (!Path.IsPathRooted (privateBinPath)) {
443                                         string appbase = setup.ApplicationBase;
444                                         if (appbase.StartsWith ("file://")) {
445                                                 appbase = appbase.Substring (7);
446                                                 if (Path.DirectorySeparatorChar != '/')
447                                                         appbase = appbase.Replace ('/', Path.DirectorySeparatorChar);
448                                         }
449                                         privateBinPath = Path.Combine (appbase, privateBinPath);
450                                 }
451
452                                 return privateBinPath;
453                         }
454                 }
455
456                 internal string BaseDir {
457                         get {
458                                 if (baseDir == null)
459                                         baseDir = context.Request.MapPath (BaseVirtualDir);
460
461                                 return baseDir;
462                         }
463                 }
464
465                 internal virtual string BaseVirtualDir {
466                         get {
467                                 if (baseVDir == null)
468                                         baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
469
470                                 return baseVDir;
471                         }
472                 }
473
474 #if NET_2_0
475                 CompilationSection CompilationConfig {
476                         get {
477                                 return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
478                         }
479                 }
480
481                 internal TextReader Reader {
482                         get { return reader; }
483                         set { reader = value; }
484                 }
485 #else
486                 internal CompilationConfiguration CompilationConfig {
487                         get {
488                                 if (compilationConfig == null)
489                                         compilationConfig = CompilationConfiguration.GetInstance (context);
490
491                                 return compilationConfig;
492                         }
493                 }
494 #endif
495         }
496 }
497