correctly remove the ApplicationPath from url
[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, 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                                 return GetMetaByURL(context, o).Resource;
251                         }
252                         Type ICachedXmlDoc.GetType (HttpContext context, string o)
253                         {
254                                 return GetMetaByURL(context, o).Type;
255                         }
256                         Assembly ICachedXmlDoc.GetAssembly (HttpContext context, string o)
257                         {
258                                 return GetMetaByURL(context, o).Assembly;
259                         }
260
261                         internal IDictionaryEnumerator GetEnumerator()
262                         {
263                                 return _table.GetEnumerator();                          
264                         }       
265
266                         //rewamped for perfomance reasons
267                         //It looks like issue is not important in development mode,
268                         //but only will became important in production mode when dynamyc compilation will be enabled
269                         //Anyway, locking whole table and compiling under lock looks odd
270                         //spivak.December 07 2006
271                         public MetaProvider GetMetaByURL(HttpContext context, string url)
272                         {
273
274 #if !NO_GLOBAL_LOCK_ON_COMPILE
275                                 string lwUrl = url.ToLowerInvariant();
276                                 lock (_table)
277                                 {
278                                         object retVal = _table[lwUrl];
279                                         if (retVal == null)
280                                         {
281                                                 retVal = PageCompiler.GetCompiler(context, url);
282                                                 _table[lwUrl] = retVal;
283                                         }
284                                 
285                                         return (MetaProvider)retVal;
286                                 }
287
288 #else
289                                 string lwUrl = url.ToLower();
290                                 if (!_table.ContainsKey(lwUrl))
291                                 {
292                                         lock (_table.SyncRoot)
293                                         {
294                                                 if (_table.ContainsKey(lwUrl))
295                                                         goto Fused;
296                                                 _table[lwUrl] = _fuse;
297                                         }
298                                         try
299                                         {
300                                                 MetaProvider meta = PageCompiler.GetCompiler(url);
301                                                 lock (_table.SyncRoot)
302                                                 {
303                                                         return (MetaProvider)(_table[lwUrl] = meta);
304                                                 }
305                                         }
306                                         catch(Exception e)
307                                         {
308                                                 _table.Remove(lwUrl);
309                                         }
310                                 }                               
311                         Fused:
312                                 
313                                 while (_table[lwUrl] == _fuse) 
314                                         Thread.Sleep(10);
315
316                                 return !_table.ContainsKey(lwUrl)? PageCompiler.Error: (MetaProvider)_table[lwUrl];
317 #endif
318                         }
319                 }
320                 
321
322                 #endregion
323         }
324
325         public interface  MetaProvider
326         {
327                 Type Type { get;}
328                 Assembly Assembly {get;}
329                 string Resource { get;}
330         }
331         public class PageCompiler : MetaProvider
332         {
333                 private static readonly string PAGE_XPATH = "preserve";
334                 private static readonly string ASSEM_ATTRIB_NAME = "assem";
335                 private static readonly string TYPE_ATTRIB_NAME = "type";
336                 private static string _parser = null;
337
338                 private Type _type = null;
339                 private string _typeName = null;
340                 private Assembly _assembly = null;
341                 private string _origAssemblyName = null;
342                 private string _xmlDescriptor = null;
343                 private string _url = null;
344                 private string _session = null;
345                 readonly private HttpContext _context;
346
347                 PageCompiler(HttpContext context, string url)
348                 {
349                         _url = url;
350                         _context = context;
351                         _xmlDescriptor = GetDescFromUrl();
352                         _session = DateTime.Now.Ticks.ToString();
353                         LoadTypeAndAssem();
354                 }
355
356                 public static PageCompiler GetCompiler(HttpContext context, string url)
357                 {
358                         return new PageCompiler(context, url);
359                 }
360
361                 Type MetaProvider.Type
362                 {
363                         get{
364                                 return _type;
365                         }
366                 }
367                 Assembly MetaProvider.Assembly
368                 {
369                         get{
370                                 return _assembly;
371                         }
372                 }
373                 string MetaProvider.Resource
374                 {
375                         get
376                         {
377                                 return _origAssemblyName != null ? _origAssemblyName + ".ghres" : "dll.ghres";
378                         }
379                 }
380                 private void LoadTypeAndAssem()
381                 {
382                         if (_assembly == null)
383                         {
384                                 string typeName = GetCachedTypeName();
385                                 if (typeName != null)
386                                 {
387                                         if ((_type = Type.GetType(typeName)) != null)
388                                                 _assembly = _type.Assembly;
389                                         else
390                                                 _assembly = Assembly.Load(_origAssemblyName);
391                                 }
392                         }
393                 }
394                 private bool InternalCompile()
395                 {
396                         string fileName = VirtualPathUtility.GetFileName (_url);
397
398                         string fullFileName = (fileName.ToLower () == "global.asax") ? _url : _context.Request.MapPath (_url);
399 #if DEBUG
400                         Console.WriteLine("fullFileName=" + fullFileName);
401 #endif
402                         //type not found - run aspxparser
403                         if (File.Exists(fullFileName) || Directory.Exists(fullFileName))
404                         {
405                                 string[] command = GetParserCmd(fileName.ToLower() == "global.asax");
406                                 if (J2EEUtils.RunProc(command) != 0)
407                                         throw GetCompilerError();
408
409                                 return true;
410                         }
411                         else
412                         {
413                                 return false;
414                                 //string message = "The requested resource (" + _url + ") is not available.";
415                                 //throw new HttpException(404, message);
416                         }
417                 }
418                 private string GetDescriptorPath()
419                 {
420                         return String.Join("/", new string[] { "assemblies", _xmlDescriptor });
421                 }
422                 private string GetTypeNameFromAppFolder()
423                 {
424                         try
425                         {
426                                 using (StreamReader sr = new StreamReader(_context.Request.MapPath("~/" + GetDescriptorPath())))
427                                 {
428                                         return GetTypeFromDescStream(sr.BaseStream);
429                                 }
430                         }
431                         catch (Exception ex)
432                         {
433                                 Console.WriteLine(ex);
434                                 throw ex;
435                         }
436                 }
437                 internal string GetTypeFromResources()
438                 {
439                         string typeName = null;
440
441                         //if the desciptor exists in the war - get the type
442                         string descPath = GetDescriptorPath();
443
444                         try
445                         {
446 #if DEBUG
447                                 Console.WriteLine(descPath);
448 #endif
449                                 using (Stream fs = (Stream)IOUtils.getStreamRecursive("/" + descPath))
450                                 {
451                                         if (fs != null)
452                                         {
453                                                 return GetTypeFromDescStream(fs);
454                                         }
455                                 }
456                         }
457                         catch (Exception ex)
458                         {
459 #if DEBUG
460                                 Console.WriteLine(ex);
461 #endif
462                         }
463                         return null;
464                 }
465                 internal string GetCachedTypeName()
466                 {                       
467                         string typeName = GetTypeFromResources();
468                         if (typeName == null)
469                         {
470                                 //spawn dynamic compilation and lookup typename from created folder
471                                 if (InternalCompile())
472                                         typeName = GetTypeNameFromAppFolder();
473                         }
474                         return typeName;
475                 }
476                 private string GetTypeName()
477                 {
478                         return String.Format("{0}, {1}", _typeName, _origAssemblyName); 
479                 }
480                 private bool LoadMetaFromXmlStream(Stream fs)
481                 {
482                         if (fs != null)
483                         {
484                                 try
485                                 {
486                                         XmlDocument descXml = new XmlDocument();
487                                         descXml.Load(fs);
488                                         _origAssemblyName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[ASSEM_ATTRIB_NAME].Value;
489                                         _typeName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[TYPE_ATTRIB_NAME].Value;
490                                         return true;
491                                 }
492                                 catch
493                                 {
494 #if DEBUG
495                                         Console.WriteLine("Failed to load typename from stream");
496 #endif
497                                 }
498                         }
499                         return false;
500                 }
501
502                 private string GetTypeFromDescStream(Stream fs)
503                 {
504                         if (LoadMetaFromXmlStream(fs))
505                                 return GetTypeName();
506                         return null;
507                 }
508
509                 private string[] GetParserCmd(bool globalAsax)
510                 {
511             string[] cmd = null;                        
512             if (globalAsax)
513             {
514                 cmd = new string[4];
515                 cmd[3] = "/buildglobalasax";
516             }
517             else
518             {
519                 cmd = new string[5];
520                 cmd[3] = "/aspxFiles:" + _url;
521                 cmd[4] = "/compilepages";
522             }
523             cmd[0] = GetParser();
524             cmd[1] = "/session:" + _session;
525             cmd[2] = "/appDir:" + (string)AppDomain.CurrentDomain.GetData(IAppDomainConfig.APP_PHYS_DIR);
526                         return cmd;
527                 }
528
529                 private string GetParser()
530                 {
531                         if (_parser == null)
532                         {
533                                 StreamReader sr =
534                                         File.OpenText (_context.Request.MapPath ("~/AspxParser.params"));
535                                 _parser = sr.ReadLine();
536                                 sr.Close();
537                         }
538
539                         return _parser;
540                 }
541
542                 private string GetDescFromUrl()
543                 {
544                         string fileName = VirtualPathUtility.GetFileName (_url);
545                         
546                         if (fileName.ToLower() == "global.asax")
547                                 return "global.asax.xml";
548
549                         string id = GetIdFromUrl(_url);
550                         string[] descName = new string[3] {fileName, id, ".xml"} ;
551                         return string.Concat(descName).ToLower();
552                 }
553
554                 private string GetIdFromUrl(string path)
555                 {
556                         string fileName = VirtualPathUtility.GetFileName(path);
557                         string id = string.Empty;
558
559                         if (VirtualPathUtility.IsAbsolute (path))
560                                 path = path.Substring (_context.Request.ApplicationPath.Length + 1);
561
562                         if (path.Length > fileName.Length)
563                                 id = "." + path.Substring(0,path.Length - fileName.Length).Replace('/','_');
564                         return id;      
565                 }
566
567                 private Exception GetCompilerError()
568                 {
569                         string _errFile = _context.Request.MapPath ("~/" + _session + ".vmwerr");
570                         
571                         if (!File.Exists(_errFile))
572                                 throw new FileNotFoundException("Internal Error",_errFile);
573
574                         StreamReader sr = new StreamReader(_errFile);
575                         string message = string.Empty, line = null, file = null, lineInFile = "0";
576
577                         while ((line = sr.ReadLine()) != null)
578                         {
579                                 if (line.StartsWith("Message: "))
580                                         message = line.Substring("Message: ".Length);
581                                 else if (line.StartsWith("File: "))
582                                         file = line.Substring("File: ".Length);
583                                 else if (line.StartsWith("Line: "))
584                                         lineInFile = line.Substring("Line: ".Length);
585                         }
586
587                         sr.Close();
588
589                         if (file != null)
590                         {
591                                 Location loc = new Location(null);
592                                 loc.Filename = file;
593                                 loc.BeginLine = int.Parse(lineInFile);
594                                 return new ParseException(loc,message);
595                         }
596
597                         if (message.IndexOf(typeof(FileNotFoundException).Name) != -1 &&
598                                 message.IndexOf(_url.Trim('\\','/').Replace('/','\\')) != -1)
599                                 message = "The requested resource (" + _url + ") is not available.";
600                         return new HttpException(404,(message !=  null ? message : string.Empty));
601                 }
602         }
603 }