2007-05-16 Igor Zelmanovich <igorz@mainsoft.com>
[mono.git] / mcs / class / System.Web / System.Web.J2EE / PageMapper.cs
1 //
2 // (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
3 //
4
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the
8 // "Software"), to deal in the Software without restriction, including
9 // without limitation the rights to use, copy, modify, merge, publish,
10 // distribute, sublicense, and/or sell copies of the Software, and to
11 // permit persons to whom the Software is furnished to do so, subject to
12 // the following conditions:
13 //
14 // The above copyright notice and this permission notice shall be
15 // included in all copies or substantial portions of the Software.
16 //
17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 //
25
26 using System;
27 using System.Xml;
28 using System.IO;
29 using System.Collections;
30 using System.Web.Compilation;
31 using System.Collections.Specialized;
32 using System.Threading;
33 using vmw.common;
34 using System.Reflection;
35
36 namespace System.Web.J2EE
37 {
38         /// <summary>
39         /// Class that allows reading assemblies.xml file for getting information about different types.
40         /// </summary>
41         public class PageMapper
42         {
43                 //private static readonly string _fileListName = "/filelist.xml";
44                 private static readonly object LOCK_GETASSEMBLIESCACHEDDOCUMENT = new object();
45                 //private static readonly object LOCK_GETFROMMAPPATHCACHE = new object();
46
47
48                 static Assembly CurrentDomain_AssemblyResolve (object sender, ResolveEventArgs args)
49                 {
50                         Assembly resolvedAssembly = null;
51                         try
52                         {
53                                 resolvedAssembly = GetCachedAssembly (HttpContext.Current, String.Concat (HttpContext.Current.Request.ApplicationPath, "/", args.Name));
54                         }
55                         catch (Exception ex)
56                         {
57 #if DEBUG
58                                 Console.WriteLine (ex.ToString ());
59 #endif
60                                 resolvedAssembly = null;
61                         }
62
63                         return resolvedAssembly;
64                 }
65
66 #if UNUSED
67
68                 public static string GetFromMapPathCache(string key)
69                 {
70                         Hashtable answer = null;
71                         lock(LOCK_GETFROMMAPPATHCACHE)
72                         {
73                                 answer = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.MAP_PATH_CACHE);
74                                 if (answer == null)
75                                 {
76                                         answer = new Hashtable();
77                                         CachedDocumentTypeStorage storage = (CachedDocumentTypeStorage)GetAssembliesCachedDocument();
78                                         IDictionaryEnumerator e = storage.GetEnumerator();
79                                         e.Reset();
80                                         while (e.MoveNext())
81                                         {                                       
82                                                 string currentFile = (string)((DictionaryEntry)e.Current).Key;
83                                                 answer[currentFile]= IAppDomainConfig.WAR_ROOT_SYMBOL + currentFile;
84                                         }
85                                         AppDomain.CurrentDomain.SetData(J2EEConsts.MAP_PATH_CACHE,answer);
86                                 }
87                         }
88                         return (string)answer[key];
89                 }
90
91                 // UNUSED METHOD
92                 //The method was used by runtime to force file names casesensitivity
93                 // problem. The filelist.xml file should contain correct file names,
94                 // but currently it is unused
95                 public static void LoadFileList()
96                 {
97                         Hashtable hashTable = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.FILE_LIST_FILE);
98                         if (hashTable == null)
99                         {
100                                 XmlDocument doc;
101                                 try
102                                 {
103                                         Stream fs = (Stream)IOUtils.getStream(_fileListName);
104                                         if (fs == null)
105                                         {
106                                                 AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
107                                                 return;
108                                         }
109
110                                         doc = new XmlDocument();
111                                         doc.Load(fs);
112                                 }
113                                 catch (Exception)
114                                 {
115 //                                      Console.WriteLine("filelist.xml was not found!!!");
116                                         AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
117                                         return;
118                                 }
119 //                              Console.WriteLine("filelist.xml was found!!!");
120                                 if (doc != null && doc.DocumentElement.HasChildNodes)
121                                 {
122                                         hashTable = CollectionsUtil.CreateCaseInsensitiveHashtable();
123                                         XmlNodeList nodeList = doc.DocumentElement.ChildNodes;
124                                         for (int i = 0;i < nodeList.Count ; i++)
125                                         {
126                                                 string fileName = nodeList.Item(i).InnerText;
127                                                 hashTable.Add(fileName,fileName);
128                                         }
129                                         AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, hashTable);
130                                 }
131                         }
132
133                 }
134 #endif
135                 private static ICachedXmlDoc GetAssembliesCachedDocument(HttpContext context)
136                 {
137                         ICachedXmlDoc doc = (ICachedXmlDoc) AppDomain.CurrentDomain.GetData (J2EEConsts.ASSEMBLIES_FILE);
138
139                         if (doc == null) {
140                                 lock (LOCK_GETASSEMBLIESCACHEDDOCUMENT) {
141                                         doc = (ICachedXmlDoc) AppDomain.CurrentDomain.GetData (J2EEConsts.ASSEMBLIES_FILE);
142                                         if (doc == null) {
143                                                 doc = CreateDocument ();
144                                                 if (doc != null) {
145                                                         AppDomain.CurrentDomain.SetData (J2EEConsts.ASSEMBLIES_FILE, doc);
146
147                                                         AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (CurrentDomain_AssemblyResolve);
148                                                         try {
149                                                                 //Try to load the  global resources
150                                                                 HttpContext.AppGlobalResourcesAssembly = GetCachedAssembly (context,  context.Request.ApplicationPath + "/app_globalresources");
151                                                         }
152                                                         catch (Exception ex) {
153 #if DEBUG
154                                                                 Console.WriteLine (ex.ToString ());
155 #endif
156                                                         }
157                                                 }
158                                         }
159                                 }
160                         }
161
162                         return doc;
163                 }
164
165                 private static String NormalizeName(string url)
166                 {
167 #if NET_2_0
168                         url = System.Web.Util.UrlUtils.RemoveDoubleSlashes(url);
169 #endif 
170                         if (url.StartsWith(IAppDomainConfig.WAR_ROOT_SYMBOL))
171                                 url = url.Substring(IAppDomainConfig.WAR_ROOT_SYMBOL.Length);
172                         return url;
173                 }
174                 private static ICachedXmlDoc CreateDocument()
175                 {
176                         return new CachedDocumentTypeStorage();
177                 }
178
179                 public static Type GetObjectType (HttpContext context, string url)
180                 {
181                         return GetCachedType(context, NormalizeName(url), true);
182                 }
183
184                 public static Type GetObjectType (HttpContext context, string url, bool throwException) {
185                         return GetCachedType (context, NormalizeName (url), throwException);
186                 }
187
188                 public static Assembly GetObjectAssembly (HttpContext context, string url)
189                 {
190                         return GetCachedAssembly (context, NormalizeName (url));
191                 }
192                 public static string GetAssemblyResource (HttpContext context, string url)
193                 {
194                         return GetCachedResource (context, NormalizeName (url));
195                 }
196                 private static string GetCachedResource (HttpContext context, string url)
197                 {
198                         ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);
199                         return doc.GetAssemblyResourceName (context, url);
200                 }
201                 private static Assembly GetCachedAssembly (HttpContext context, string url)
202                 {
203                         ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);
204                         return doc.GetAssembly (context, url);
205                 }
206                 private static Type GetCachedType (HttpContext context, string url) {
207                         return GetCachedType (context, url, true);
208                 }
209                 private static Type GetCachedType (HttpContext context, string url, bool throwException)
210                 {
211                         ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);                                            
212                         Type t = doc.GetType(context, url);
213                         if (t == null && throwException)
214                                 throw new HttpException(404,"The requested resource (" + url + ") is not available.");
215
216                         return t;
217                 }
218
219                 #region ICachedXmlDoc interface
220                 interface ICachedXmlDoc
221                 {
222                         Type GetType (HttpContext context, string key);
223                         Assembly GetAssembly (HttpContext context, string key);
224                         string GetAssemblyResourceName (HttpContext context, string key);
225                 }
226                 #endregion
227
228                 #region CachedDocumentTypeStorage class
229                 class CachedDocumentTypeStorage : ICachedXmlDoc
230                 {
231                         private static readonly object _fuse = new object();
232                         public static readonly ICachedXmlDoc DEFAULT_DOC =
233                                 new CachedDocumentTypeStorage(0);
234
235                         private static readonly int DEFAULT_PAGES_NUMBER = 25;
236
237                         private Hashtable _table;
238
239                         private CachedDocumentTypeStorage(int initTableSize)
240                         {
241                                 _table = Hashtable.Synchronized(new Hashtable(initTableSize));
242                         }
243
244                         public CachedDocumentTypeStorage() :
245                                 this(DEFAULT_PAGES_NUMBER)
246                         {}
247
248                         string ICachedXmlDoc.GetAssemblyResourceName (HttpContext context, string o)
249                         {
250                                 MetaProvider p = GetMetaByURL (context, o);
251                                 if (p == null)
252                                         return null;
253                                 return p.Resource;
254                         }
255                         Type ICachedXmlDoc.GetType (HttpContext context, string o)
256                         {
257                                 MetaProvider p = GetMetaByURL (context, o);
258                                 if (p == null)
259                                         return null;
260                                 return p.Type;
261                         }
262                         Assembly ICachedXmlDoc.GetAssembly (HttpContext context, string o)
263                         {
264                                 MetaProvider p = GetMetaByURL (context, o);
265                                 if (p == null)
266                                         return null;
267                                 return p.Assembly;
268                         }
269
270                         internal IDictionaryEnumerator GetEnumerator()
271                         {
272                                 return _table.GetEnumerator();                          
273                         }       
274
275                         //rewamped for perfomance reasons
276                         //It looks like issue is not important in development mode,
277                         //but only will became important in production mode when dynamyc compilation will be enabled
278                         //Anyway, locking whole table and compiling under lock looks odd
279                         //spivak.December 07 2006
280                         //
281                         //prevent DOS attack. dont cache MetaProvider for not valid resource
282                         //igorz. May 16 2007
283                         public MetaProvider GetMetaByURL(HttpContext context, string url)
284                         {
285                                 string lwUrl = url.ToLowerInvariant ();
286                                 MetaProvider retVal = (MetaProvider) _table [lwUrl];
287                                 if (retVal == null) {
288                                         retVal = PageCompiler.GetCompiler (context, url);
289                                         if (retVal.Type == null && retVal.Assembly == null)
290                                                 return null;
291                                         _table [lwUrl] = retVal;
292                                 }
293
294                                 return retVal;
295                         }
296                 }
297                 
298
299                 #endregion
300         }
301
302         public interface  MetaProvider
303         {
304                 Type Type { get;}
305                 Assembly Assembly {get;}
306                 string Resource { get;}
307         }
308         public class PageCompiler : MetaProvider
309         {
310                 private static readonly string PAGE_XPATH = "preserve";
311                 private static readonly string ASSEM_ATTRIB_NAME = "assem";
312                 private static readonly string TYPE_ATTRIB_NAME = "type";
313                 private static string _parser = null;
314
315                 private Type _type = null;
316                 private string _typeName = null;
317                 private Assembly _assembly = null;
318                 private string _origAssemblyName = null;
319                 private string _xmlDescriptor = null;
320                 private string _url = null;
321                 private string _session = null;
322                 readonly private HttpContext _context;
323
324                 PageCompiler(HttpContext context, string url)
325                 {
326                         _url = url;
327                         _context = context;
328                         _xmlDescriptor = GetDescFromUrl();
329                         _session = DateTime.Now.Ticks.ToString();
330                         LoadTypeAndAssem();
331                 }
332
333                 public static PageCompiler GetCompiler(HttpContext context, string url)
334                 {
335                         return new PageCompiler(context, url);
336                 }
337
338                 Type MetaProvider.Type
339                 {
340                         get{
341                                 return _type;
342                         }
343                 }
344                 Assembly MetaProvider.Assembly
345                 {
346                         get{
347                                 return _assembly;
348                         }
349                 }
350                 string MetaProvider.Resource
351                 {
352                         get
353                         {
354                                 return _origAssemblyName != null ? _origAssemblyName + ".ghres" : "dll.ghres";
355                         }
356                 }
357                 private void LoadTypeAndAssem()
358                 {
359                         if (_assembly == null)
360                         {
361                                 string typeName = GetCachedTypeName();
362 #if DEBUG
363                                 Console.WriteLine ("Loading type:" + typeName);
364 #endif
365                                 if (typeName != null)
366                                 {
367                                         if ((_type = Type.GetType (typeName)) != null)
368                                                 _assembly = _type.Assembly;
369                                         else {
370                                                 if (_origAssemblyName == null)
371                                                         throw new TypeLoadException ("Cannot load type '" + typeName + "'");
372                                                 _assembly = Assembly.Load (_origAssemblyName);
373                                         }
374                                 }
375                         }
376                 }
377                 private bool InternalCompile()
378                 {
379                         string fileName = VirtualPathUtility.GetFileName (_url);
380
381                         string fullFileName = (fileName.ToLower () == "global.asax") ? _url : _context.Request.MapPath (_url);
382 #if DEBUG
383                         Console.WriteLine("fullFileName=" + fullFileName);
384 #endif
385                         //type not found - run aspxparser
386                         if (false/*File.Exists(fullFileName) || Directory.Exists(fullFileName)*/) //dynamic compilation currently is not supported
387                         {
388                                 string[] command = GetParserCmd(fileName.ToLower() == "global.asax");
389                                 if (J2EEUtils.RunProc(command) != 0)
390                                         throw GetCompilerError();
391
392                                 return true;
393                         }
394                         else
395                         {
396                                 return false;
397                                 //string message = "The requested resource (" + _url + ") is not available.";
398                                 //throw new HttpException(404, message);
399                         }
400                 }
401                 private string GetDescriptorPath()
402                 {
403                         return String.Join("/", new string[] { "assemblies", _xmlDescriptor });
404                 }
405                 private string GetTypeNameFromAppFolder()
406                 {
407                         try
408                         {
409                                 using (StreamReader sr = new StreamReader(_context.Request.MapPath("~/" + GetDescriptorPath())))
410                                 {
411                                         return GetTypeFromDescStream(sr.BaseStream);
412                                 }
413                         }
414                         catch (Exception ex)
415                         {
416                                 Console.WriteLine(ex);
417                                 throw ex;
418                         }
419                 }
420                 internal string GetTypeFromResources()
421                 {
422                         string typeName = null;
423
424                         //if the desciptor exists in the war - get the type
425                         string descPath = GetDescriptorPath();
426
427                         try
428                         {
429 #if DEBUG
430                                 Console.WriteLine(descPath);
431 #endif
432                                 using (Stream fs = (Stream)IOUtils.getStreamRecursive("/" + descPath))
433                                 {
434                                         if (fs != null)
435                                         {
436                                                 return GetTypeFromDescStream(fs);
437                                         }
438                                 }
439                         }
440                         catch (Exception ex)
441                         {
442 #if DEBUG
443                                 Console.WriteLine(ex);
444 #endif
445                         }
446                         return null;
447                 }
448                 internal string GetCachedTypeName()
449                 {                       
450                         string typeName = GetTypeFromResources();
451                         if (typeName == null)
452                         {
453                                 //spawn dynamic compilation and lookup typename from created folder
454                                 if (InternalCompile())
455                                         typeName = GetTypeNameFromAppFolder();
456                         }
457                         return typeName;
458                 }
459                 private string GetTypeName()
460                 {
461                         return String.Format("{0}, {1}", _typeName, _origAssemblyName); 
462                 }
463                 private bool LoadMetaFromXmlStream(Stream fs)
464                 {
465                         if (fs != null)
466                         {
467                                 try
468                                 {
469                                         XmlDocument descXml = new XmlDocument();
470                                         descXml.Load(fs);
471                                         _origAssemblyName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[ASSEM_ATTRIB_NAME].Value;
472                                         _typeName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[TYPE_ATTRIB_NAME].Value;
473                                         return true;
474                                 }
475                                 catch
476                                 {
477 #if DEBUG
478                                         Console.WriteLine("Failed to load typename from stream");
479 #endif
480                                 }
481                         }
482                         return false;
483                 }
484
485                 private string GetTypeFromDescStream(Stream fs)
486                 {
487                         if (LoadMetaFromXmlStream(fs))
488                                 return GetTypeName();
489                         return null;
490                 }
491
492                 private string[] GetParserCmd(bool globalAsax)
493                 {
494             string[] cmd = null;                        
495             if (globalAsax)
496             {
497                 cmd = new string[4];
498                 cmd[3] = "/buildglobalasax";
499             }
500             else
501             {
502                 cmd = new string[5];
503                 cmd[3] = "/aspxFiles:" + _url;
504                 cmd[4] = "/compilepages";
505             }
506             cmd[0] = GetParser();
507             cmd[1] = "/session:" + _session;
508             cmd[2] = "/appDir:" + (string)AppDomain.CurrentDomain.GetData(IAppDomainConfig.APP_PHYS_DIR);
509                         return cmd;
510                 }
511
512                 private string GetParser()
513                 {
514                         if (_parser == null)
515                         {
516                                 StreamReader sr =
517                                         File.OpenText (_context.Request.MapPath ("~/AspxParser.params"));
518                                 _parser = sr.ReadLine();
519                                 sr.Close();
520                         }
521
522                         return _parser;
523                 }
524
525                 private string GetDescFromUrl()
526                 {
527                         string fileName = VirtualPathUtility.GetFileName (_url);
528                         
529                         if (fileName.ToLower() == "global.asax")
530                                 return "global.asax.xml";
531
532                         string id = GetIdFromUrl(_url);
533                         string[] descName = new string[3] {fileName, id, ".xml"} ;
534                         return string.Concat(descName).ToLowerInvariant();
535                 }
536
537                 private string GetIdFromUrl(string path)
538                 {
539                         string fileName = VirtualPathUtility.GetFileName(path);
540                         string id = string.Empty;
541
542                         if (VirtualPathUtility.IsAbsolute (path))
543                                 path = path.Substring (_context.Request.ApplicationPath.Length + 1);
544
545                         if (path.Length > fileName.Length)
546                                 id = "." + path.Substring(0,path.Length - fileName.Length).Replace('/','_');
547                         return id;      
548                 }
549
550                 private Exception GetCompilerError()
551                 {
552                         string _errFile = _context.Request.MapPath ("~/" + _session + ".vmwerr");
553                         
554                         if (!File.Exists(_errFile))
555                                 throw new FileNotFoundException("Internal Error",_errFile);
556
557                         StreamReader sr = new StreamReader(_errFile);
558                         string message = string.Empty, line = null, file = null, lineInFile = "0";
559
560                         while ((line = sr.ReadLine()) != null)
561                         {
562                                 if (line.StartsWith("Message: "))
563                                         message = line.Substring("Message: ".Length);
564                                 else if (line.StartsWith("File: "))
565                                         file = line.Substring("File: ".Length);
566                                 else if (line.StartsWith("Line: "))
567                                         lineInFile = line.Substring("Line: ".Length);
568                         }
569
570                         sr.Close();
571
572                         if (file != null)
573                         {
574                                 Location loc = new Location(null);
575                                 loc.Filename = file;
576                                 loc.BeginLine = int.Parse(lineInFile);
577                                 return new ParseException(loc,message);
578                         }
579
580                         if (message.IndexOf(typeof(FileNotFoundException).Name) != -1 &&
581                                 message.IndexOf(_url.Trim('\\','/').Replace('/','\\')) != -1)
582                                 message = "The requested resource (" + _url + ") is not available.";
583                         return new HttpException(404,(message !=  null ? message : string.Empty));
584                 }
585         }
586 }