New tests, message update
[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                         throw new NotImplementedException ();
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.net.URL url = cl.getResource ("META-INF/web.config");
132                                         if (url == null)
133                                                 return null;
134
135                                         return "/META-INF/web.config";
136                                 }
137 #else
138                                         mdir = Path.GetDirectoryName (System.Runtime.InteropServices.RuntimeEnvironment.SystemConfigurationFile);
139 #endif
140                                 else
141                                         mdir = Path.GetDirectoryName (map.MachineConfigFilename);
142
143                                 return GetWebConfigFileName (mdir);
144                         }
145                         
146                         string dir = MapPath (configPath);
147                         return GetWebConfigFileName (dir);
148                 }
149                 
150                 public virtual string GetStreamNameForConfigSource (string streamName, string configSource)
151                 {
152                         throw new NotImplementedException ();
153                 }
154                 
155                 public virtual object GetStreamVersion (string streamName)
156                 {
157                         throw new NotImplementedException ();
158                 }
159                 
160                 public virtual IDisposable Impersonate ()
161                 {
162                         throw new NotImplementedException ();
163                 }
164                 
165                 public virtual void Init (IInternalConfigRoot root, params object[] hostInitParams)
166                 {
167                 }
168                 
169                 public virtual void InitForConfiguration (ref string locationSubPath, out string configPath,
170                                                           out string locationConfigPath, IInternalConfigRoot root,
171                                                           params object[] hostInitConfigurationParams)
172                 {
173                         string fullPath = (string) hostInitConfigurationParams [1];
174                         map = (WebConfigurationFileMap) hostInitConfigurationParams [0];
175
176                         if (locationSubPath == MachineWebPath) {
177                                 locationSubPath = MachinePath;
178                                 configPath = MachineWebPath;
179                                 locationConfigPath = null;
180                         } else if (locationSubPath == MachinePath) {
181                                 locationSubPath = null;
182                                 configPath = MachinePath;
183                                 locationConfigPath = null;
184                         } else {
185                                 int i;
186                                 if (locationSubPath == null)
187                                 {
188                                         configPath = fullPath;
189                                         if (configPath.Length > 1)
190                                                 configPath = VirtualPathUtility.RemoveTrailingSlash (configPath);
191                                 }
192                                 else
193                                         configPath = locationSubPath;
194
195                                 if (configPath == HttpRuntime.AppDomainAppVirtualPath
196                                     || configPath == "/")
197                                         i = -1;
198                                 else
199                                         i = configPath.LastIndexOf ("/");
200
201                                 if (i != -1) {
202                                         locationConfigPath = configPath.Substring (i+1);
203                                         
204                                         if (i == 0)
205                                                 locationSubPath = "/";
206                                         else
207                                                 locationSubPath = fullPath.Substring (0, i);
208                                 } else {
209                                         locationSubPath = MachineWebPath;
210                                         locationConfigPath = null;
211                                 }
212                         }
213                 }
214                 
215                 public string MapPath (string virtualPath)
216                 {
217                         if (map != null)
218                                 return MapPathFromMapper (virtualPath);
219                         else if (HttpContext.Current != null && HttpContext.Current.Request != null)
220                                 return HttpContext.Current.Request.MapPath (virtualPath);
221                         else if (HttpRuntime.AppDomainAppVirtualPath != null &&
222                                  virtualPath.StartsWith (HttpRuntime.AppDomainAppVirtualPath)) {
223                                 if (virtualPath == HttpRuntime.AppDomainAppVirtualPath)
224                                         return HttpRuntime.AppDomainAppPath;
225                                 return UrlUtils.Combine (HttpRuntime.AppDomainAppPath,
226                                                          virtualPath.Substring (HttpRuntime.AppDomainAppVirtualPath.Length));
227                         }
228                         
229                         return virtualPath;
230                 }
231                 
232                 public string NormalizeVirtualPath (string virtualPath)
233                 {
234                         if (virtualPath == null || virtualPath.Length == 0)
235                                 virtualPath = ".";
236                         else
237                                 virtualPath = virtualPath.Trim ();
238
239                         if (virtualPath [0] == '~' && virtualPath.Length > 2 && virtualPath [1] == '/')
240                                 virtualPath = virtualPath.Substring (1);
241                                 
242                         if (System.IO.Path.DirectorySeparatorChar != '/')
243                                 virtualPath = virtualPath.Replace (System.IO.Path.DirectorySeparatorChar, '/');
244
245                         if (UrlUtils.IsRooted (virtualPath)) {
246                                 virtualPath = UrlUtils.Canonic (virtualPath);
247                         } else {
248                                 if (map.VirtualDirectories.Count > 0) {
249                                         string root = map.VirtualDirectories [0].VirtualDirectory;
250                                         virtualPath = UrlUtils.Combine (root, virtualPath);
251                                         virtualPath = UrlUtils.Canonic (virtualPath);
252                                 }
253                         }
254                         return virtualPath;
255                 }
256
257                 public string MapPathFromMapper (string virtualPath)
258                 {
259                         string path = NormalizeVirtualPath (virtualPath);
260                         
261                         foreach (VirtualDirectoryMapping mapping in map.VirtualDirectories) {
262                                 if (path.StartsWith (mapping.VirtualDirectory)) {
263                                         int i = mapping.VirtualDirectory.Length;
264                                         if (path.Length == i) {
265                                                 return mapping.PhysicalDirectory;
266                                         }
267                                         else if (path [i] == '/') {
268                                                 string pathPart = path.Substring (i + 1).Replace ('/', Path.DirectorySeparatorChar);
269                                                 return Path.Combine (mapping.PhysicalDirectory, pathPart);
270                                         }
271                                 }
272                         }
273                         throw new HttpException ("Invalid virtual directory: " + virtualPath);
274                 }
275
276                 string GetWebConfigFileName (string dir)
277                 {
278 #if TARGET_J2EE
279                         DirectoryInfo d = GetCaseSensitiveExistingDirectory (new DirectoryInfo (dir));
280                         if (d == null)
281                                 return null;
282
283                         FileInfo file = (FileInfo) FindByName ("web.config", d.GetFiles ("W*"));
284                         if (file == null)
285                                 file = (FileInfo) FindByName ("web.config", d.GetFiles ("w*"));
286
287                         if (file != null)
288                                 return file.FullName;
289 #else
290                         AppDomain domain = AppDomain.CurrentDomain;
291                         bool hosted = (domain.GetData (ApplicationHost.MonoHostedDataKey) as string) == "yes";
292
293                         if (hosted) {
294                                 foreach (string fn in ApplicationHost.WebConfigFileNames) {
295                                         string file = Path.Combine (dir, fn);
296                                         if (File.Exists (file))
297                                                 return file;
298                                 }
299                         } else {
300                                 Assembly asm = Assembly.GetEntryAssembly () ?? Assembly.GetCallingAssembly ();
301                                 string name = Path.GetFileName (asm.Location);
302                                 string[] fileNames = new string[] {name + ".config", name + ".Config"};
303                                 string appDir = domain.BaseDirectory;
304                                 string file;
305
306                                 foreach (string fn in fileNames) {
307                                         file = Path.Combine (appDir, fn);
308                                         if (File.Exists (file))
309                                                 return file;
310                                 }
311                         }
312 #endif                  
313                         return null;
314                 }
315 #if TARGET_J2EE
316                 static DirectoryInfo GetCaseSensitiveExistingDirectory (DirectoryInfo dir) {
317                         if (dir == null)
318                                 return null;
319                         if (dir.Exists)
320                                 return dir;
321
322                         DirectoryInfo parent = GetCaseSensitiveExistingDirectory (dir.Parent);
323                         if (parent == null)
324                                 return null;
325
326                         return (DirectoryInfo) FindByName (dir.Name, parent.GetDirectories ());
327                 }
328                 
329                 static FileSystemInfo FindByName (string name, FileSystemInfo [] infos)
330                 {
331                         for (int i = 0; i < infos.Length; i++) {
332                                 if (String.Compare (name, infos [i].Name, StringComparison.OrdinalIgnoreCase) == 0)
333                                         return infos [i];
334                         }
335                         return null;
336                 }
337 #endif
338                 public virtual bool IsAboveApplication (string configPath)
339                 {
340                         throw new NotImplementedException ();
341                 }
342                 
343                 public virtual bool IsConfigRecordRequired (string configPath)
344                 {
345                         throw new NotImplementedException ();
346                 }
347                 
348                 public virtual bool IsDefinitionAllowed (string configPath, ConfigurationAllowDefinition allowDefinition,
349                                                          ConfigurationAllowExeDefinition allowExeDefinition)
350                 {
351                         switch (allowDefinition) {
352                                 case ConfigurationAllowDefinition.MachineOnly:
353                                         return configPath == MachinePath || configPath == MachineWebPath;
354                                 case ConfigurationAllowDefinition.MachineToWebRoot:
355                                 case ConfigurationAllowDefinition.MachineToApplication:
356                                         return configPath == MachinePath || configPath == MachineWebPath || configPath == "/" ||
357                                                 configPath == HttpRuntime.AppDomainAppVirtualPath;
358                                 default:
359                                         return true;
360                         }
361                 }
362                 
363                 public virtual bool IsFile (string streamName)
364                 {
365                         throw new NotImplementedException ();
366                 }
367                 
368                 public virtual bool IsLocationApplicable (string configPath)
369                 {
370                         throw new NotImplementedException ();
371                 }
372                 
373                 public virtual Stream OpenStreamForRead (string streamName)
374                 {
375                         if (!File.Exists (streamName)) {
376 #if TARGET_J2EE
377                                 if (streamName != null && (streamName.EndsWith ("machine.config") ||
378                                                            streamName.EndsWith ("web.config"))) {
379                                         if (streamName.StartsWith ("/"))
380                                                 streamName = streamName.Substring (1);
381                                         java.lang.ClassLoader cl = (java.lang.ClassLoader) AppDomain.CurrentDomain.GetData ("GH_ContextClassLoader");
382                                         if (cl != null) {
383                                                 java.io.InputStream inputStream = cl.getResourceAsStream (streamName);
384                                                 return (Stream) vmw.common.IOUtils.getStream (inputStream);
385                                         }
386                                 }
387 #endif
388                                 throw new ConfigurationException ("File '" + streamName + "' not found");
389                         }
390                                 
391                         return new FileStream (streamName, FileMode.Open, FileAccess.Read);
392                 }
393
394                 [MonoTODO ("Not implemented")]
395                 public virtual Stream OpenStreamForRead (string streamName, bool assertPermissions)
396                 {
397                         throw new NotImplementedException ();
398                 }
399
400                 public virtual Stream OpenStreamForWrite (string streamName, string templateStreamName, ref object writeContext)
401                 {
402                         return new FileStream (streamName, FileMode.Create, FileAccess.Write);
403                 }
404
405                 [MonoTODO ("Not implemented")]
406                 public virtual Stream OpenStreamForWrite (string streamName, string templateStreamName, ref object writeContext,
407                                                           bool assertPermissions)
408                 {
409                         throw new NotImplementedException ();
410                 }
411                 
412                 public virtual bool PrefetchAll (string configPath, string streamName)
413                 {
414                         throw new NotImplementedException ();
415                 }
416                 
417                 public virtual bool PrefetchSection (string sectionGroupName, string sectionName)
418                 {
419                         throw new NotImplementedException ();
420                 }
421
422                 [MonoTODO ("Not implemented")]
423                 public virtual void RequireCompleteInit (IInternalConfigRecord configRecord)
424                 {
425                         throw new NotImplementedException ();
426                 }
427
428                 public virtual object StartMonitoringStreamForChanges (string streamName, StreamChangeCallback callback)
429                 {
430                         throw new NotImplementedException ();
431                 }
432                 
433                 public virtual void StopMonitoringStreamForChanges (string streamName, StreamChangeCallback callback)
434                 {
435                         throw new NotImplementedException ();
436                 }
437                 
438                 public virtual void VerifyDefinitionAllowed (string configPath, ConfigurationAllowDefinition allowDefinition,
439                                                              ConfigurationAllowExeDefinition allowExeDefinition,
440                                                              IConfigErrorInfo errorInfo)
441                 {
442                         if (!IsDefinitionAllowed (configPath, allowDefinition, allowExeDefinition))
443                                 throw new ConfigurationErrorsException ("The section can't be defined in this file (the allowed definition context is '" + allowDefinition + "').", errorInfo.Filename, errorInfo.LineNumber);
444                 }
445                 
446                 [MonoTODO("Does nothing")]
447                 public virtual void WriteCompleted (string streamName, bool success, object writeContext)
448                 {
449                 }
450                 
451                 [MonoTODO("Does nothing")]
452                 public virtual void WriteCompleted (string streamName, bool success, object writeContext, bool assertPermissions)
453                 {
454                 }
455
456                 public virtual bool SupportsChangeNotifications {
457                         get { return false; }
458                 }
459                 
460                 public virtual bool SupportsLocation {
461                         get { return false; }
462                 }
463                 
464                 public virtual bool SupportsPath {
465                         get { return false; }
466                 }
467                 
468                 public virtual bool SupportsRefresh {
469                         get { return false; }
470                 }
471
472                 [MonoTODO("Always returns false")]
473                 public virtual bool IsRemote {
474                         get { return false; }
475                 }
476
477                 [MonoTODO ("Not implemented")]
478                 public virtual bool IsFullTrustSectionWithoutAptcaAllowed (IInternalConfigRecord configRecord)
479                 {
480                         throw new NotImplementedException ();
481                 }
482
483                 [MonoTODO ("Not implemented")]
484                 public virtual bool IsInitDelayed (IInternalConfigRecord configRecord)
485                 {
486                         throw new NotImplementedException ();
487                 }
488
489                 [MonoTODO ("Not implemented")]
490                 public virtual bool IsSecondaryRoot (string configPath)
491                 {
492                         throw new NotImplementedException ();
493                 }
494
495                 [MonoTODO ("Not implemented")]
496                 public virtual bool IsTrustedConfigPath (string configPath)
497                 {
498                         throw new NotImplementedException ();
499                 }
500         }
501 }
502
503 #endif