2007-05-17 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 == null)
302                                 return null;
303                         if (dir.Exists)
304                                 return dir;
305
306                         DirectoryInfo parent = GetCaseSensitiveExistingDirectory (dir.Parent);
307                         if (parent == null)
308                                 return null;
309
310                         return (DirectoryInfo) FindByName (dir.Name, parent.GetDirectories ());
311                 }
312                 
313                 static FileSystemInfo FindByName (string name, FileSystemInfo [] infos)
314                 {
315                         for (int i = 0; i < infos.Length; i++) {
316                                 if (String.Compare (name, infos [i].Name, StringComparison.OrdinalIgnoreCase) == 0)
317                                         return infos [i];
318                         }
319                         return null;
320                 }
321 #endif
322                 public virtual bool IsAboveApplication (string configPath)
323                 {
324                         throw new NotImplementedException ();
325                 }
326                 
327                 public virtual bool IsConfigRecordRequired (string configPath)
328                 {
329                         throw new NotImplementedException ();
330                 }
331                 
332                 public virtual bool IsDefinitionAllowed (string configPath, ConfigurationAllowDefinition allowDefinition,
333                                                          ConfigurationAllowExeDefinition allowExeDefinition)
334                 {
335                         switch (allowDefinition) {
336                                 case ConfigurationAllowDefinition.MachineOnly:
337                                         return configPath == MachinePath || configPath == MachineWebPath;
338                                 case ConfigurationAllowDefinition.MachineToWebRoot:
339                                 case ConfigurationAllowDefinition.MachineToApplication:
340                                         return configPath == MachinePath || configPath == MachineWebPath || configPath == "/" ||
341                                                 configPath == HttpRuntime.AppDomainAppVirtualPath;
342                                 default:
343                                         return true;
344                         }
345                 }
346                 
347                 public virtual bool IsFile (string streamName)
348                 {
349                         throw new NotImplementedException ();
350                 }
351                 
352                 public virtual bool IsLocationApplicable (string configPath)
353                 {
354                         throw new NotImplementedException ();
355                 }
356                 
357                 public virtual Stream OpenStreamForRead (string streamName)
358                 {
359                         if (!File.Exists (streamName)) {
360 #if TARGET_J2EE
361                                 if (streamName != null && (streamName.EndsWith ("machine.config") ||
362                                                            streamName.EndsWith ("web.config"))) {
363                                         if (streamName.StartsWith ("/"))
364                                                 streamName = streamName.Substring (1);
365                                         java.lang.ClassLoader cl = (java.lang.ClassLoader) AppDomain.CurrentDomain.GetData ("GH_ContextClassLoader");
366                                         if (cl != null) {
367                                                 java.io.InputStream inputStream = cl.getResourceAsStream (streamName);
368                                                 return (Stream) vmw.common.IOUtils.getStream (inputStream);
369                                         }
370                                 }
371 #endif
372                                 throw new ConfigurationException ("File '" + streamName + "' not found");
373                         }
374                                 
375                         return new FileStream (streamName, FileMode.Open, FileAccess.Read);
376                 }
377
378                 [MonoTODO ("Not implemented")]
379                 public virtual Stream OpenStreamForRead (string streamName, bool assertPermissions)
380                 {
381                         throw new NotImplementedException ();
382                 }
383
384                 public virtual Stream OpenStreamForWrite (string streamName, string templateStreamName, ref object writeContext)
385                 {
386                         return new FileStream (streamName, FileMode.Create, FileAccess.Write);
387                 }
388
389                 [MonoTODO ("Not implemented")]
390                 public virtual Stream OpenStreamForWrite (string streamName, string templateStreamName, ref object writeContext,
391                                                           bool assertPermissions)
392                 {
393                         throw new NotImplementedException ();
394                 }
395                 
396                 public virtual bool PrefetchAll (string configPath, string streamName)
397                 {
398                         throw new NotImplementedException ();
399                 }
400                 
401                 public virtual bool PrefetchSection (string sectionGroupName, string sectionName)
402                 {
403                         throw new NotImplementedException ();
404                 }
405
406                 [MonoTODO ("Not implemented")]
407                 public virtual void RequireCompleteInit (IInternalConfigRecord configRecord)
408                 {
409                         throw new NotImplementedException ();
410                 }
411
412                 public virtual object StartMonitoringStreamForChanges (string streamName, StreamChangeCallback callback)
413                 {
414                         throw new NotImplementedException ();
415                 }
416                 
417                 public virtual void StopMonitoringStreamForChanges (string streamName, StreamChangeCallback callback)
418                 {
419                         throw new NotImplementedException ();
420                 }
421                 
422                 public virtual void VerifyDefinitionAllowed (string configPath, ConfigurationAllowDefinition allowDefinition,
423                                                              ConfigurationAllowExeDefinition allowExeDefinition,
424                                                              IConfigErrorInfo errorInfo)
425                 {
426                         if (!IsDefinitionAllowed (configPath, allowDefinition, allowExeDefinition))
427                                 throw new ConfigurationErrorsException ("The section can't be defined in this file (the allowed definition context is '" + allowDefinition + "').", errorInfo.Filename, errorInfo.LineNumber);
428                 }
429                 
430                 [MonoTODO("Does nothing")]
431                 public virtual void WriteCompleted (string streamName, bool success, object writeContext)
432                 {
433                 }
434                 
435                 [MonoTODO("Does nothing")]
436                 public virtual void WriteCompleted (string streamName, bool success, object writeContext, bool assertPermissions)
437                 {
438                 }
439
440                 public virtual bool SupportsChangeNotifications {
441                         get { return false; }
442                 }
443                 
444                 public virtual bool SupportsLocation {
445                         get { return false; }
446                 }
447                 
448                 public virtual bool SupportsPath {
449                         get { return false; }
450                 }
451                 
452                 public virtual bool SupportsRefresh {
453                         get { return false; }
454                 }
455
456                 [MonoTODO("Always returns false")]
457                 public virtual bool IsRemote {
458                         get { return false; }
459                 }
460
461                 [MonoTODO ("Not implemented")]
462                 public virtual bool IsFullTrustSectionWithoutAptcaAllowed (IInternalConfigRecord configRecord)
463                 {
464                         throw new NotImplementedException ();
465                 }
466
467                 [MonoTODO ("Not implemented")]
468                 public virtual bool IsInitDelayed (IInternalConfigRecord configRecord)
469                 {
470                         throw new NotImplementedException ();
471                 }
472
473                 [MonoTODO ("Not implemented")]
474                 public virtual bool IsSecondaryRoot (string configPath)
475                 {
476                         throw new NotImplementedException ();
477                 }
478
479                 [MonoTODO ("Not implemented")]
480                 public virtual bool IsTrustedConfigPath (string configPath)
481                 {
482                         throw new NotImplementedException ();
483                 }
484         }
485 }
486
487 #endif