2007-05-15 Igor Zelmanovich <igorz@mainsoft.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.Util;
38 using System.Reflection;
39
40 /*
41  * this class needs to be rewritten to support usage of the
42  * IRemoteWebConfigurationHostServer interface.  Once that's done, we
43  * need an implementation of that interface that talks (through a web
44  * service?) to a remote site..
45  *
46  * for now, though, just implement it as we do
47  * System.Configuration.InternalConfigurationHost, i.e. the local
48  * case.
49  */
50 namespace System.Web.Configuration
51 {
52         class WebConfigurationHost: IInternalConfigHost
53         {
54                 WebConfigurationFileMap map;
55                 const string MachinePath = ":machine:";
56                 const string MachineWebPath = ":web:";
57                 
58                 public virtual object CreateConfigurationContext (string configPath, string locationSubPath)
59                 {
60                         return new WebContext (WebApplicationLevel.AtApplication /* XXX */,
61                                                "" /* site XXX */,
62                                                "" /* application path XXX */,
63                                                configPath,
64                                                locationSubPath);
65                 }
66                 
67                 public virtual object CreateDeprecatedConfigContext (string configPath)
68                 {
69                         throw new NotImplementedException ();
70                 }
71                 
72                 public virtual string DecryptSection (string encryptedXml, ProtectedConfigurationProvider protectionProvider,
73                                                       ProtectedConfigurationSection protectedSection)
74                 {
75                         throw new NotImplementedException ();
76                 }
77                 
78                 public virtual void DeleteStream (string streamName)
79                 {
80                         File.Delete (streamName);
81                 }
82                 
83                 public virtual string EncryptSection (string encryptedXml, ProtectedConfigurationProvider protectionProvider,
84                                                       ProtectedConfigurationSection protectedSection)
85                 {
86                         throw new NotImplementedException ();
87                 }
88                 
89                 public virtual string GetConfigPathFromLocationSubPath (string configPath, string locatinSubPath)
90                 {
91                         return configPath + "/" + locatinSubPath;
92                 }
93                 
94                 public virtual Type GetConfigType (string typeName, bool throwOnError)
95                 {
96                         Type type = HttpApplication.LoadType (typeName);
97                         if (type == null && throwOnError)
98                                 throw new ConfigurationErrorsException ("Type not found: '" + typeName + "'");
99                         return type;
100                 }
101                 
102                 public virtual string GetConfigTypeName (Type t)
103                 {
104                         return t.AssemblyQualifiedName;
105                 }
106                 
107                 public virtual void GetRestrictedPermissions (IInternalConfigRecord configRecord, out PermissionSet permissionSet,
108                                                               out bool isHostReady)
109                 {
110                         throw new NotImplementedException ();
111                 }
112                 
113                 public virtual string GetStreamName (string configPath)
114                 {
115                         if (configPath == MachinePath) {
116                                 if (map == null)
117                                         return System.Runtime.InteropServices.RuntimeEnvironment.SystemConfigurationFile;
118                                 else
119                                         return map.MachineConfigFilename;
120                         } else if (configPath == MachineWebPath) {
121                                 string mdir;
122
123                                 if (map == null)
124 #if TARGET_J2EE
125                                 {
126                                         // check META-INF/web.config exists
127                                         java.lang.ClassLoader cl = (java.lang.ClassLoader) AppDomain.CurrentDomain.GetData ("GH_ContextClassLoader");
128                                         if (cl == null)
129                                                 return null;
130                                         java.net.URL url = cl.getResource ("META-INF/web.config");
131                                         if (url == null)
132                                                 return null;
133
134                                         return "/META-INF/web.config";
135                                 }
136 #else
137                                         mdir = Path.GetDirectoryName (System.Runtime.InteropServices.RuntimeEnvironment.SystemConfigurationFile);
138 #endif
139                                 else
140                                         mdir = Path.GetDirectoryName (map.MachineConfigFilename);
141
142                                 return GetWebConfigFileName (mdir);
143                         }
144                         
145                         string dir = MapPath (configPath);
146                         return GetWebConfigFileName (dir);
147                 }
148                 
149                 public virtual string GetStreamNameForConfigSource (string streamName, string configSource)
150                 {
151                         throw new NotImplementedException ();
152                 }
153                 
154                 public virtual object GetStreamVersion (string streamName)
155                 {
156                         throw new NotImplementedException ();
157                 }
158                 
159                 public virtual IDisposable Impersonate ()
160                 {
161                         throw new NotImplementedException ();
162                 }
163                 
164                 public virtual void Init (IInternalConfigRoot root, params object[] hostInitParams)
165                 {
166                 }
167                 
168                 public virtual void InitForConfiguration (ref string locationSubPath, out string configPath,
169                                                           out string locationConfigPath, IInternalConfigRoot root,
170                                                           params object[] hostInitConfigurationParams)
171                 {
172                         string fullPath = (string) hostInitConfigurationParams [1];
173                         map = (WebConfigurationFileMap) hostInitConfigurationParams [0];
174
175                         if (locationSubPath == MachineWebPath) {
176                                 locationSubPath = MachinePath;
177                                 configPath = MachineWebPath;
178                                 locationConfigPath = null;
179                         } else if (locationSubPath == MachinePath) {
180                                 locationSubPath = null;
181                                 configPath = MachinePath;
182                                 locationConfigPath = null;
183                         } else {
184                                 int i;
185                                 if (locationSubPath == null)
186                                 {
187                                         configPath = fullPath;
188                                         if (configPath.Length > 1)
189                                                 configPath = VirtualPathUtility.RemoveTrailingSlash (configPath);
190                                 }
191                                 else
192                                         configPath = locationSubPath;
193
194                                 if (configPath == HttpRuntime.AppDomainAppVirtualPath
195                                     || configPath == "/")
196                                         i = -1;
197                                 else
198                                         i = configPath.LastIndexOf ("/");
199
200                                 if (i != -1) {
201                                         locationConfigPath = configPath.Substring (i+1);
202                                         
203                                         if (i == 0)
204                                                 locationSubPath = "/";
205                                         else
206                                                 locationSubPath = fullPath.Substring (0, i);
207                                 } else {
208                                         locationSubPath = MachineWebPath;
209                                         locationConfigPath = null;
210                                 }
211                         }
212                 }
213                 
214                 public string MapPath (string virtualPath)
215                 {
216                         if (map != null)
217                                 return MapPathFromMapper (virtualPath);
218                         else if (HttpContext.Current != null && HttpContext.Current.Request != null)
219                                 return HttpContext.Current.Request.MapPath (virtualPath);
220                         else if (HttpRuntime.AppDomainAppVirtualPath != null &&
221                                  virtualPath.StartsWith (HttpRuntime.AppDomainAppVirtualPath)) {
222                                 if (virtualPath == HttpRuntime.AppDomainAppVirtualPath)
223                                         return HttpRuntime.AppDomainAppPath;
224                                 return UrlUtils.Combine (HttpRuntime.AppDomainAppPath,
225                                                          virtualPath.Substring (HttpRuntime.AppDomainAppVirtualPath.Length));
226                         }
227                         
228                         return virtualPath;
229                 }
230                 
231                 public string NormalizeVirtualPath (string virtualPath)
232                 {
233                         if (virtualPath == null || virtualPath.Length == 0)
234                                 virtualPath = ".";
235                         else
236                                 virtualPath = virtualPath.Trim ();
237
238                         if (virtualPath [0] == '~' && virtualPath.Length > 2 && virtualPath [1] == '/')
239                                 virtualPath = virtualPath.Substring (1);
240                                 
241                         if (System.IO.Path.DirectorySeparatorChar != '/')
242                                 virtualPath = virtualPath.Replace (System.IO.Path.DirectorySeparatorChar, '/');
243
244                         if (UrlUtils.IsRooted (virtualPath)) {
245                                 virtualPath = UrlUtils.Canonic (virtualPath);
246                         } else {
247                                 if (map.VirtualDirectories.Count > 0) {
248                                         string root = map.VirtualDirectories [0].VirtualDirectory;
249                                         virtualPath = UrlUtils.Combine (root, virtualPath);
250                                         virtualPath = UrlUtils.Canonic (virtualPath);
251                                 }
252                         }
253                         return virtualPath;
254                 }
255
256                 public string MapPathFromMapper (string virtualPath)
257                 {
258                         string path = NormalizeVirtualPath (virtualPath);
259                         
260                         foreach (VirtualDirectoryMapping mapping in map.VirtualDirectories) {
261                                 if (path.StartsWith (mapping.VirtualDirectory)) {
262                                         int i = mapping.VirtualDirectory.Length;
263                                         if (path.Length == i) {
264                                                 return mapping.PhysicalDirectory;
265                                         }
266                                         else if (path [i] == '/') {
267                                                 string pathPart = path.Substring (i + 1).Replace ('/', Path.DirectorySeparatorChar);
268                                                 return Path.Combine (mapping.PhysicalDirectory, pathPart);
269                                         }
270                                 }
271                         }
272                         throw new HttpException ("Invalid virtual directory: " + virtualPath);
273                 }
274
275                 string GetWebConfigFileName (string dir)
276                 {
277 #if TARGET_J2EE
278                         DirectoryInfo d = GetCaseSensitiveExistingDirectory (new DirectoryInfo (dir));
279                         if (d == null)
280                                 return null;
281
282                         FileInfo file = (FileInfo) FindByName ("web.config", d.GetFiles ("W*"));
283                         if (file == null)
284                                 file = (FileInfo) FindByName ("web.config", d.GetFiles ("w*"));
285
286                         if (file != null)
287                                 return file.FullName;
288 #else
289                         string[] filenames = new string[] {"Web.Config", "Web.config", "web.config" };
290
291                         foreach (string fn in filenames) {
292                                 string file = Path.Combine (dir, fn);
293                                 if (File.Exists (file))
294                                         return file;
295                         }
296 #endif
297                         return null;
298                 }
299 #if TARGET_J2EE
300                 static DirectoryInfo GetCaseSensitiveExistingDirectory (DirectoryInfo dir) {
301                         if (dir.Exists)
302                                 return dir;
303
304                         DirectoryInfo parent = GetCaseSensitiveExistingDirectory (dir.Parent);
305                         if (parent == null)
306                                 return null;
307
308                         return (DirectoryInfo) FindByName (dir.Name, parent.GetDirectories ());
309                 }
310                 
311                 static FileSystemInfo FindByName (string name, FileSystemInfo [] infos)
312                 {
313                         for (int i = 0; i < infos.Length; i++) {
314                                 if (String.Compare (name, infos [i].Name, StringComparison.OrdinalIgnoreCase) == 0)
315                                         return infos [i];
316                         }
317                         return null;
318                 }
319 #endif
320                 public virtual bool IsAboveApplication (string configPath)
321                 {
322                         throw new NotImplementedException ();
323                 }
324                 
325                 public virtual bool IsConfigRecordRequired (string configPath)
326                 {
327                         throw new NotImplementedException ();
328                 }
329                 
330                 public virtual bool IsDefinitionAllowed (string configPath, ConfigurationAllowDefinition allowDefinition,
331                                                          ConfigurationAllowExeDefinition allowExeDefinition)
332                 {
333                         switch (allowDefinition) {
334                                 case ConfigurationAllowDefinition.MachineOnly:
335                                         return configPath == MachinePath || configPath == MachineWebPath;
336                                 case ConfigurationAllowDefinition.MachineToWebRoot:
337                                 case ConfigurationAllowDefinition.MachineToApplication:
338                                         return configPath == MachinePath || configPath == MachineWebPath || configPath == "/" ||
339                                                 configPath == HttpRuntime.AppDomainAppVirtualPath;
340                                 default:
341                                         return true;
342                         }
343                 }
344                 
345                 public virtual bool IsFile (string streamName)
346                 {
347                         throw new NotImplementedException ();
348                 }
349                 
350                 public virtual bool IsLocationApplicable (string configPath)
351                 {
352                         throw new NotImplementedException ();
353                 }
354                 
355                 public virtual Stream OpenStreamForRead (string streamName)
356                 {
357                         if (!File.Exists (streamName)) {
358 #if TARGET_J2EE
359                                 if (streamName != null && (streamName.EndsWith ("machine.config") ||
360                                                            streamName.EndsWith ("web.config"))) {
361                                         if (streamName.StartsWith ("/"))
362                                                 streamName = streamName.Substring (1);
363                                         java.lang.ClassLoader cl = (java.lang.ClassLoader) AppDomain.CurrentDomain.GetData ("GH_ContextClassLoader");
364                                         if (cl != null) {
365                                                 java.io.InputStream inputStream = cl.getResourceAsStream (streamName);
366                                                 return (Stream) vmw.common.IOUtils.getStream (inputStream);
367                                         }
368                                 }
369 #endif
370                                 throw new ConfigurationException ("File '" + streamName + "' not found");
371                         }
372                                 
373                         return new FileStream (streamName, FileMode.Open, FileAccess.Read);
374                 }
375
376                 [MonoTODO ("Not implemented")]
377                 public virtual Stream OpenStreamForRead (string streamName, bool assertPermissions)
378                 {
379                         throw new NotImplementedException ();
380                 }
381
382                 public virtual Stream OpenStreamForWrite (string streamName, string templateStreamName, ref object writeContext)
383                 {
384                         return new FileStream (streamName, FileMode.Create, FileAccess.Write);
385                 }
386
387                 [MonoTODO ("Not implemented")]
388                 public virtual Stream OpenStreamForWrite (string streamName, string templateStreamName, ref object writeContext,
389                                                           bool assertPermissions)
390                 {
391                         throw new NotImplementedException ();
392                 }
393                 
394                 public virtual bool PrefetchAll (string configPath, string streamName)
395                 {
396                         throw new NotImplementedException ();
397                 }
398                 
399                 public virtual bool PrefetchSection (string sectionGroupName, string sectionName)
400                 {
401                         throw new NotImplementedException ();
402                 }
403
404                 [MonoTODO ("Not implemented")]
405                 public virtual void RequireCompleteInit (IInternalConfigRecord configRecord)
406                 {
407                         throw new NotImplementedException ();
408                 }
409
410                 public virtual object StartMonitoringStreamForChanges (string streamName, StreamChangeCallback callback)
411                 {
412                         throw new NotImplementedException ();
413                 }
414                 
415                 public virtual void StopMonitoringStreamForChanges (string streamName, StreamChangeCallback callback)
416                 {
417                         throw new NotImplementedException ();
418                 }
419                 
420                 public virtual void VerifyDefinitionAllowed (string configPath, ConfigurationAllowDefinition allowDefinition,
421                                                              ConfigurationAllowExeDefinition allowExeDefinition,
422                                                              IConfigErrorInfo errorInfo)
423                 {
424                         if (!IsDefinitionAllowed (configPath, allowDefinition, allowExeDefinition))
425                                 throw new ConfigurationErrorsException ("The section can't be defined in this file (the allowed definition context is '" + allowDefinition + "').", errorInfo.Filename, errorInfo.LineNumber);
426                 }
427                 
428                 [MonoTODO("Does nothing")]
429                 public virtual void WriteCompleted (string streamName, bool success, object writeContext)
430                 {
431                 }
432                 
433                 [MonoTODO("Does nothing")]
434                 public virtual void WriteCompleted (string streamName, bool success, object writeContext, bool assertPermissions)
435                 {
436                 }
437
438                 public virtual bool SupportsChangeNotifications {
439                         get { return false; }
440                 }
441                 
442                 public virtual bool SupportsLocation {
443                         get { return false; }
444                 }
445                 
446                 public virtual bool SupportsPath {
447                         get { return false; }
448                 }
449                 
450                 public virtual bool SupportsRefresh {
451                         get { return false; }
452                 }
453
454                 [MonoTODO("Always returns false")]
455                 public virtual bool IsRemote {
456                         get { return false; }
457                 }
458
459                 [MonoTODO ("Not implemented")]
460                 public virtual bool IsFullTrustSectionWithoutAptcaAllowed (IInternalConfigRecord configRecord)
461                 {
462                         throw new NotImplementedException ();
463                 }
464
465                 [MonoTODO ("Not implemented")]
466                 public virtual bool IsInitDelayed (IInternalConfigRecord configRecord)
467                 {
468                         throw new NotImplementedException ();
469                 }
470
471                 [MonoTODO ("Not implemented")]
472                 public virtual bool IsSecondaryRoot (string configPath)
473                 {
474                         throw new NotImplementedException ();
475                 }
476
477                 [MonoTODO ("Not implemented")]
478                 public virtual bool IsTrustedConfigPath (string configPath)
479                 {
480                         throw new NotImplementedException ();
481                 }
482         }
483 }
484
485 #endif