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