2009-06-12 Bill Holmes <billholmes54@gmail.com>
[mono.git] / mcs / class / System.Web / System.Web.Configuration_2.0 / WebConfigurationHost.cs
1 //
2 // System.Web.Configuration.WebConfigurationHost.cs
3 //
4 // Authors:
5 //  Lluis Sanchez Gual (lluis@novell.com)
6 //
7 // Permission is hereby granted, free of charge, to any person obtaining
8 // a copy of this software and associated documentation files (the
9 // "Software"), to deal in the Software without restriction, including
10 // without limitation the rights to use, copy, modify, merge, publish,
11 // distribute, sublicense, and/or sell copies of the Software, and to
12 // permit persons to whom the Software is furnished to do so, subject to
13 // the following conditions:
14 // 
15 // The above copyright notice and this permission notice shall be
16 // included in all copies or substantial portions of the Software.
17 // 
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 //
26 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
27 //
28
29 #if NET_2_0
30
31 using System;
32 using System.Collections;
33 using System.IO;
34 using System.Security;
35 using System.Configuration;
36 using System.Configuration.Internal;
37 using System.Web.Hosting;
38 using System.Web.Util;
39 using System.Reflection;
40
41 /*
42  * this class needs to be rewritten to support usage of the
43  * IRemoteWebConfigurationHostServer interface.  Once that's done, we
44  * need an implementation of that interface that talks (through a web
45  * service?) to a remote site..
46  *
47  * for now, though, just implement it as we do
48  * System.Configuration.InternalConfigurationHost, i.e. the local
49  * case.
50  */
51 namespace System.Web.Configuration
52 {
53         class WebConfigurationHost: IInternalConfigHost
54         {
55                 WebConfigurationFileMap map;
56                 const string MachinePath = ":machine:";
57                 const string MachineWebPath = ":web:";
58                 
59                 public virtual object CreateConfigurationContext (string configPath, string locationSubPath)
60                 {
61                         return new WebContext (WebApplicationLevel.AtApplication /* XXX */,
62                                                "" /* site XXX */,
63                                                "" /* application path XXX */,
64                                                configPath,
65                                                locationSubPath);
66                 }
67                 
68                 public virtual object CreateDeprecatedConfigContext (string configPath)
69                 {
70                         return new HttpConfigurationContext(configPath);
71                 }
72                 
73                 public virtual string DecryptSection (string encryptedXml, ProtectedConfigurationProvider protectionProvider,
74                                                       ProtectedConfigurationSection protectedSection)
75                 {
76                         throw new NotImplementedException ();
77                 }
78                 
79                 public virtual void DeleteStream (string streamName)
80                 {
81                         File.Delete (streamName);
82                 }
83                 
84                 public virtual string EncryptSection (string encryptedXml, ProtectedConfigurationProvider protectionProvider,
85                                                       ProtectedConfigurationSection protectedSection)
86                 {
87                         throw new NotImplementedException ();
88                 }
89                 
90                 public virtual string GetConfigPathFromLocationSubPath (string configPath, string locatinSubPath)
91                 {
92                         return configPath + "/" + locatinSubPath;
93                 }
94                 
95                 public virtual Type GetConfigType (string typeName, bool throwOnError)
96                 {
97                         Type type = HttpApplication.LoadType (typeName);
98                         if (type == null && throwOnError)
99                                 throw new ConfigurationErrorsException ("Type not found: '" + typeName + "'");
100                         return type;
101                 }
102                 
103                 public virtual string GetConfigTypeName (Type t)
104                 {
105                         return t.AssemblyQualifiedName;
106                 }
107                 
108                 public virtual void GetRestrictedPermissions (IInternalConfigRecord configRecord, out PermissionSet permissionSet,
109                                                               out bool isHostReady)
110                 {
111                         throw new NotImplementedException ();
112                 }
113                 
114                 public virtual string GetStreamName (string configPath)
115                 {
116                         if (configPath == MachinePath) {
117                                 if (map == null)
118                                         return System.Runtime.InteropServices.RuntimeEnvironment.SystemConfigurationFile;
119                                 else
120                                         return map.MachineConfigFilename;
121                         } else if (configPath == MachineWebPath) {
122                                 string mdir;
123
124                                 if (map == null)
125 #if TARGET_J2EE
126                                 {
127                                         // check META-INF/web.config exists
128                                         java.lang.ClassLoader cl = (java.lang.ClassLoader) AppDomain.CurrentDomain.GetData ("GH_ContextClassLoader");
129                                         if (cl == null)
130                                                 return null;
131                                         java.io.InputStream wcs = cl.getResourceAsStream ("META-INF/web.config");
132                                         if (wcs == null)
133                                                 return null;
134
135                                         wcs.close ();
136
137                                         return "/META-INF/web.config";
138                                 }
139 #else
140                                         mdir = Path.GetDirectoryName (System.Runtime.InteropServices.RuntimeEnvironment.SystemConfigurationFile);
141 #endif
142                                 else
143                                         mdir = Path.GetDirectoryName (map.MachineConfigFilename);
144
145                                 return GetWebConfigFileName (mdir);
146                         }
147                         
148                         string dir = MapPath (configPath);
149                         return GetWebConfigFileName (dir);
150                 }
151                 
152                 public virtual string GetStreamNameForConfigSource (string streamName, string configSource)
153                 {
154                         throw new NotImplementedException ();
155                 }
156                 
157                 public virtual object GetStreamVersion (string streamName)
158                 {
159                         throw new NotImplementedException ();
160                 }
161                 
162                 public virtual IDisposable Impersonate ()
163                 {
164                         throw new NotImplementedException ();
165                 }
166                 
167                 public virtual void Init (IInternalConfigRoot root, params object[] hostInitParams)
168                 {
169                 }
170                 
171                 public virtual void InitForConfiguration (ref string locationSubPath, out string configPath,
172                                                           out string locationConfigPath, IInternalConfigRoot root,
173                                                           params object[] hostInitConfigurationParams)
174                 {
175                         string fullPath = (string) hostInitConfigurationParams [1];
176                         map = (WebConfigurationFileMap) hostInitConfigurationParams [0];
177
178                         if (locationSubPath == MachineWebPath) {
179                                 locationSubPath = MachinePath;
180                                 configPath = MachineWebPath;
181                                 locationConfigPath = null;
182                         } else if (locationSubPath == MachinePath) {
183                                 locationSubPath = null;
184                                 configPath = MachinePath;
185                                 locationConfigPath = null;
186                         } else {
187                                 int i;
188                                 if (locationSubPath == null)
189                                 {
190                                         configPath = fullPath;
191                                         if (configPath.Length > 1)
192                                                 configPath = VirtualPathUtility.RemoveTrailingSlash (configPath);
193                                 }
194                                 else
195                                         configPath = locationSubPath;
196
197                                 if (configPath == HttpRuntime.AppDomainAppVirtualPath
198                                     || configPath == "/")
199                                         i = -1;
200                                 else
201                                         i = configPath.LastIndexOf ("/");
202
203                                 if (i != -1) {
204                                         locationConfigPath = configPath.Substring (i+1);
205                                         
206                                         if (i == 0)
207                                                 locationSubPath = "/";
208                                         else
209                                                 locationSubPath = fullPath.Substring (0, i);
210                                 } else {
211                                         locationSubPath = MachineWebPath;
212                                         locationConfigPath = null;
213                                 }
214                         }
215                 }
216                 
217                 public string MapPath (string virtualPath)
218                 {
219                         if (!String.IsNullOrEmpty (virtualPath)) {
220                                 if (virtualPath.StartsWith (System.Web.Compilation.BuildManager.FAKE_VIRTUAL_PATH_PREFIX, StringComparison.Ordinal))
221                                         return HttpRuntime.AppDomainAppPath;
222                         }
223                         
224                         if (map != null)
225                                 return MapPathFromMapper (virtualPath);
226                         else if (HttpContext.Current != null && HttpContext.Current.Request != null)
227                                 return HttpContext.Current.Request.MapPath (virtualPath);
228                         else if (HttpRuntime.AppDomainAppVirtualPath != null &&
229                                  virtualPath.StartsWith (HttpRuntime.AppDomainAppVirtualPath)) {
230                                 if (virtualPath == HttpRuntime.AppDomainAppVirtualPath)
231                                         return HttpRuntime.AppDomainAppPath;
232                                 return UrlUtils.Combine (HttpRuntime.AppDomainAppPath,
233                                                          virtualPath.Substring (HttpRuntime.AppDomainAppVirtualPath.Length));
234                         }
235                         
236                         return virtualPath;
237                 }
238                 
239                 public string NormalizeVirtualPath (string virtualPath)
240                 {
241                         if (virtualPath == null || virtualPath.Length == 0)
242                                 virtualPath = ".";
243                         else
244                                 virtualPath = virtualPath.Trim ();
245
246                         if (virtualPath [0] == '~' && virtualPath.Length > 2 && virtualPath [1] == '/')
247                                 virtualPath = virtualPath.Substring (1);
248                                 
249                         if (System.IO.Path.DirectorySeparatorChar != '/')
250                                 virtualPath = virtualPath.Replace (System.IO.Path.DirectorySeparatorChar, '/');
251
252                         if (UrlUtils.IsRooted (virtualPath)) {
253                                 virtualPath = UrlUtils.Canonic (virtualPath);
254                         } else {
255                                 if (map.VirtualDirectories.Count > 0) {
256                                         string root = map.VirtualDirectories [0].VirtualDirectory;
257                                         virtualPath = UrlUtils.Combine (root, virtualPath);
258                                         virtualPath = UrlUtils.Canonic (virtualPath);
259                                 }
260                         }
261                         return virtualPath;
262                 }
263
264                 public string MapPathFromMapper (string virtualPath)
265                 {
266                         string path = NormalizeVirtualPath (virtualPath);
267                         
268                         foreach (VirtualDirectoryMapping mapping in map.VirtualDirectories) {
269                                 if (path.StartsWith (mapping.VirtualDirectory)) {
270                                         int i = mapping.VirtualDirectory.Length;
271                                         if (path.Length == i) {
272                                                 return mapping.PhysicalDirectory;
273                                         }
274                                         else if (path [i] == '/') {
275                                                 string pathPart = path.Substring (i + 1).Replace ('/', Path.DirectorySeparatorChar);
276                                                 return Path.Combine (mapping.PhysicalDirectory, pathPart);
277                                         }
278                                 }
279                         }
280                         throw new HttpException ("Invalid virtual directory: " + virtualPath);
281                 }
282
283                 internal static string GetWebConfigFileName (string dir)
284                 {
285 #if TARGET_J2EE
286                         DirectoryInfo d = GetCaseSensitiveExistingDirectory (new DirectoryInfo (dir));
287                         if (d == null)
288                                 return null;
289
290                         FileInfo file = (FileInfo) FindByName ("web.config", d.GetFiles ("W*"));
291                         if (file == null)
292                                 file = (FileInfo) FindByName ("web.config", d.GetFiles ("w*"));
293
294                         if (file != null)
295                                 return file.FullName;
296 #else
297                         AppDomain domain = AppDomain.CurrentDomain;
298                         bool hosted = (domain.GetData (ApplicationHost.MonoHostedDataKey) as string) == "yes";
299
300                         if (hosted) {
301                                 foreach (string fn in ApplicationHost.WebConfigFileNames) {
302                                         string file = Path.Combine (dir, fn);
303                                         if (File.Exists (file))
304                                                 return file;
305                                 }
306                         } else {
307                                 Assembly asm = Assembly.GetEntryAssembly () ?? Assembly.GetCallingAssembly ();
308                                 string name = Path.GetFileName (asm.Location);
309                                 string[] fileNames = new string[] {name + ".config", name + ".Config"};
310                                 string appDir = domain.BaseDirectory;
311                                 string file;
312
313                                 foreach (string fn in fileNames) {
314                                         file = Path.Combine (appDir, fn);
315                                         if (File.Exists (file))
316                                                 return file;
317                                 }
318                         }
319 #endif                  
320                         return null;
321                 }
322 #if TARGET_J2EE
323                 static DirectoryInfo GetCaseSensitiveExistingDirectory (DirectoryInfo dir) {
324                         if (dir == null)
325                                 return null;
326                         if (dir.Exists)
327                                 return dir;
328
329                         DirectoryInfo parent = GetCaseSensitiveExistingDirectory (dir.Parent);
330                         if (parent == null)
331                                 return null;
332
333                         return (DirectoryInfo) FindByName (dir.Name, parent.GetDirectories ());
334                 }
335                 
336                 static FileSystemInfo FindByName (string name, FileSystemInfo [] infos)
337                 {
338                         for (int i = 0; i < infos.Length; i++) {
339                                 if (String.Compare (name, infos [i].Name, StringComparison.OrdinalIgnoreCase) == 0)
340                                         return infos [i];
341                         }
342                         return null;
343                 }
344 #endif
345                 public virtual bool IsAboveApplication (string configPath)
346                 {
347                         throw new NotImplementedException ();
348                 }
349                 
350                 public virtual bool IsConfigRecordRequired (string configPath)
351                 {
352                         throw new NotImplementedException ();
353                 }
354                 
355                 public virtual bool IsDefinitionAllowed (string configPath, ConfigurationAllowDefinition allowDefinition,
356                                                          ConfigurationAllowExeDefinition allowExeDefinition)
357                 {
358                         switch (allowDefinition) {
359                                 case ConfigurationAllowDefinition.MachineOnly:
360                                         return configPath == MachinePath || configPath == MachineWebPath;
361                                 case ConfigurationAllowDefinition.MachineToWebRoot:
362                                 case ConfigurationAllowDefinition.MachineToApplication:
363                                         return (String.Compare (configPath, MachinePath, StringComparison.Ordinal) == 0) ||
364                                                 (String.Compare (configPath, MachineWebPath, StringComparison.Ordinal) == 0) ||
365                                                 (String.Compare (configPath, "/", StringComparison.Ordinal) == 0) ||
366                                                 (String.Compare (configPath, "~", StringComparison.Ordinal) == 0) ||
367                                                 (String.Compare (configPath, HttpRuntime.AppDomainAppVirtualPath) == 0);
368                                 default:
369                                         return true;
370                         }
371                 }
372                 
373                 public virtual bool IsFile (string streamName)
374                 {
375                         throw new NotImplementedException ();
376                 }
377                 
378                 public virtual bool IsLocationApplicable (string configPath)
379                 {
380                         throw new NotImplementedException ();
381                 }
382                 
383                 public virtual Stream OpenStreamForRead (string streamName)
384                 {
385                         if (!File.Exists (streamName)) {
386 #if TARGET_J2EE
387                                 if (streamName != null && (streamName.EndsWith ("machine.config") ||
388                                                            streamName.EndsWith ("web.config"))) {
389                                         if (streamName.StartsWith ("/"))
390                                                 streamName = streamName.Substring (1);
391                                         java.lang.ClassLoader cl = (java.lang.ClassLoader) AppDomain.CurrentDomain.GetData ("GH_ContextClassLoader");
392                                         if (cl != null) {
393                                                 java.io.InputStream inputStream = cl.getResourceAsStream (streamName);
394                                                 return new System.Web.J2EE.J2EEUtils.InputStreamWrapper (inputStream);
395                                         }
396                                 }
397 #endif
398                                 throw new ConfigurationException ("File '" + streamName + "' not found");
399                         }
400                                 
401                         return new FileStream (streamName, FileMode.Open, FileAccess.Read);
402                 }
403
404                 [MonoTODO ("Not implemented")]
405                 public virtual Stream OpenStreamForRead (string streamName, bool assertPermissions)
406                 {
407                         throw new NotImplementedException ();
408                 }
409
410                 public virtual Stream OpenStreamForWrite (string streamName, string templateStreamName, ref object writeContext)
411                 {
412                         return new FileStream (streamName, FileMode.Create, FileAccess.Write);
413                 }
414
415                 [MonoTODO ("Not implemented")]
416                 public virtual Stream OpenStreamForWrite (string streamName, string templateStreamName, ref object writeContext,
417                                                           bool assertPermissions)
418                 {
419                         throw new NotImplementedException ();
420                 }
421                 
422                 public virtual bool PrefetchAll (string configPath, string streamName)
423                 {
424                         throw new NotImplementedException ();
425                 }
426                 
427                 public virtual bool PrefetchSection (string sectionGroupName, string sectionName)
428                 {
429                         throw new NotImplementedException ();
430                 }
431
432                 [MonoTODO ("Not implemented")]
433                 public virtual void RequireCompleteInit (IInternalConfigRecord configRecord)
434                 {
435                         throw new NotImplementedException ();
436                 }
437
438                 public virtual object StartMonitoringStreamForChanges (string streamName, StreamChangeCallback callback)
439                 {
440                         throw new NotImplementedException ();
441                 }
442                 
443                 public virtual void StopMonitoringStreamForChanges (string streamName, StreamChangeCallback callback)
444                 {
445                         throw new NotImplementedException ();
446                 }
447                 
448                 public virtual void VerifyDefinitionAllowed (string configPath, ConfigurationAllowDefinition allowDefinition,
449                                                              ConfigurationAllowExeDefinition allowExeDefinition,
450                                                              IConfigErrorInfo errorInfo)
451                 {
452                         if (!IsDefinitionAllowed (configPath, allowDefinition, allowExeDefinition))
453                                 throw new ConfigurationErrorsException ("The section can't be defined in this file (the allowed definition context is '" + allowDefinition + "').", errorInfo.Filename, errorInfo.LineNumber);
454                 }
455                 
456                 [MonoTODO("Does nothing")]
457                 public virtual void WriteCompleted (string streamName, bool success, object writeContext)
458                 {
459                 }
460                 
461                 [MonoTODO("Does nothing")]
462                 public virtual void WriteCompleted (string streamName, bool success, object writeContext, bool assertPermissions)
463                 {
464                 }
465
466                 public virtual bool SupportsChangeNotifications {
467                         get { return false; }
468                 }
469                 
470                 public virtual bool SupportsLocation {
471                         get { return false; }
472                 }
473                 
474                 public virtual bool SupportsPath {
475                         get { return false; }
476                 }
477                 
478                 public virtual bool SupportsRefresh {
479                         get { return false; }
480                 }
481
482                 [MonoTODO("Always returns false")]
483                 public virtual bool IsRemote {
484                         get { return false; }
485                 }
486
487                 [MonoTODO ("Not implemented")]
488                 public virtual bool IsFullTrustSectionWithoutAptcaAllowed (IInternalConfigRecord configRecord)
489                 {
490                         throw new NotImplementedException ();
491                 }
492
493                 [MonoTODO ("Not implemented")]
494                 public virtual bool IsInitDelayed (IInternalConfigRecord configRecord)
495                 {
496                         throw new NotImplementedException ();
497                 }
498
499                 [MonoTODO ("Not implemented")]
500                 public virtual bool IsSecondaryRoot (string configPath)
501                 {
502                         throw new NotImplementedException ();
503                 }
504
505                 [MonoTODO ("Not implemented")]
506                 public virtual bool IsTrustedConfigPath (string configPath)
507                 {
508                         throw new NotImplementedException ();
509                 }
510         }
511 }
512
513 #endif