2008-04-15 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / class / System.Web / System.Web.Hosting / ApplicationHost.cs
1 //
2 // System.Web.Hosting.ApplicationHost.cs 
3 // 
4 // Author:
5 //      Miguel de Icaza (miguel@novell.com)
6 //
7 //
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System.IO;
31 using System.Security.Permissions;
32 using System.Security.Policy;
33 using System.Text;
34
35 namespace System.Web.Hosting {
36
37         // CAS - no InheritanceDemand here as the class is sealed
38         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
39         public sealed class ApplicationHost {
40                 internal static readonly string MonoHostedDataKey = ".:!MonoAspNetHostedApp!:.";
41                 internal static string [] WebConfigFileNames = { "Web.config", "Web.Config", "web.config" };
42
43                 private ApplicationHost ()
44                 {
45                 }
46
47                 static string FindWebConfig (string basedir)
48                 {
49                         string r = null;
50                                 
51                         foreach (string s in WebConfigFileNames){
52                                 r = Path.Combine (basedir, s);
53
54                                 if (File.Exists (r))
55                                         return r;
56                         }
57                         // default: return the last one
58                         return r;
59                 }
60
61 #if NET_2_0
62                 static object create_dir = new object ();
63 #endif
64
65                 internal static bool ClearDynamicBaseDirectory (string directory)
66                 {
67                         string[] entries = null;
68                         
69                         try {
70                                 entries = Directory.GetDirectories (directory);
71                         } catch {
72                                 // ignore
73                         }
74
75                         bool dirEmpty = true;
76                         if (entries != null && entries.Length > 0) {
77                                 foreach (string e in entries) {
78                                         if (ClearDynamicBaseDirectory (e)) {
79                                                 try {
80                                                         Directory.Delete (e);
81                                                 } catch {
82                                                         dirEmpty = false;
83                                                 }
84                                         }
85                                 }
86                         }
87
88                         try {
89                                 entries = Directory.GetFiles (directory);
90                         } catch {
91                                 entries = null;
92                         }
93
94                         if (entries != null && entries.Length > 0) {
95                                 foreach (string e in entries) {
96                                         try {
97                                                 File.Delete (e);
98                                         } catch {
99                                                 dirEmpty = false;
100                                         }
101                                 }
102                         }
103
104                         return dirEmpty;
105                 }
106                 
107                 static bool CreateDirectory (string directory)
108                 {
109 #if NET_2_0
110                         lock (create_dir) {
111 #endif
112                                 if (!Directory.Exists (directory)) {
113                                         Directory.CreateDirectory (directory);
114                                         return false;
115                                 } else
116                                         return true;
117 #if NET_2_0
118                         }
119 #endif
120                 }
121
122                 static string BuildPrivateBinPath (string physicalPath, string[] dirs)
123                 {
124 #if NET_2_0
125                         int len = dirs.Length;
126                         string[] ret = new string [len];
127                         for (int i = 0; i < len; i++)
128                                 ret [i] = Path.Combine (physicalPath, dirs [i]);
129                         return String.Join (";", ret);
130 #else
131                         return String.Join (";", dirs);
132 #endif
133                 }
134                 
135                 //
136                 // For further details see `Hosting the ASP.NET runtime'
137                 //
138                 //    http://www.west-wind.com/presentations/aspnetruntime/aspnetruntime.asp
139                 // 
140 #if TARGET_JVM
141                 [MonoNotSupported ("")]
142 #endif
143                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
144                 public static object CreateApplicationHost (Type hostType, string virtualDir, string physicalDir)
145                 {
146                         if (physicalDir == null)
147                                 throw new NullReferenceException ();
148
149                         // Make sure physicalDir has file system semantics
150                         // and not uri semantics ( '\' and not '/' ).
151                         physicalDir = Path.GetFullPath (physicalDir);
152
153                         if (hostType == null)
154                                 throw new ArgumentException ("hostType can't be null");
155
156                         if (virtualDir == null)
157                                 throw new ArgumentNullException ("virtualDir");
158
159                         Evidence evidence = new Evidence (AppDomain.CurrentDomain.Evidence);
160                         
161                         //
162                         // Setup
163                         //
164                         AppDomainSetup setup = new AppDomainSetup ();
165
166                         setup.ApplicationBase = physicalDir;
167
168                         setup.CachePath = null;
169                         setup.ConfigurationFile = FindWebConfig (physicalDir);
170                         setup.DisallowCodeDownload = true;
171
172                         string[] bindirPath = new string [1] {
173 #if NET_2_0
174                                 Path.Combine (physicalDir, "bin")
175 #else
176                                 "bin"
177 #endif
178                         };
179                         string bindir;
180
181                         foreach (string dir in HttpApplication.BinDirs) {
182                                 bindir = Path.Combine (physicalDir, dir);
183                         
184                                 if (Directory.Exists (bindir)) {
185 #if NET_2_0
186                                         bindirPath [0] = bindir;
187 #else
188                                         bindirPath [0] = dir;
189 #endif
190                                         break;
191                                 }
192                         }
193
194                         setup.PrivateBinPath = BuildPrivateBinPath (physicalDir, HttpApplication.BinDirs);
195                         setup.PrivateBinPathProbe = "*";
196                         setup.ShadowCopyFiles = "true";
197                         setup.ShadowCopyDirectories = setup.PrivateBinPath;
198
199                         string dynamic_dir = null;
200                         string user = Environment.UserName;
201                         int tempDirTag = 0;
202                         string dirPrefix = String.Concat (user, "-temp-aspnet-");
203                         
204                         for (int i = 0; ; i++){
205                                 string d = Path.Combine (Path.GetTempPath (), String.Concat (dirPrefix, i.ToString ("x")));
206                         
207                                 try {
208                                         CreateDirectory (d);
209                                         string stamp = Path.Combine (d, "stamp");
210                                         CreateDirectory (stamp);
211                                         dynamic_dir = d;
212                                         try {
213                                                 Directory.Delete (stamp);
214                                         } catch (Exception) {
215                                                 // ignore
216                                         }
217                                         
218                                         tempDirTag = i.GetHashCode ();
219                                         break;
220                                 } catch (UnauthorizedAccessException){
221                                         continue;
222                                 }
223                         }
224                         // 
225                         // Unique Domain ID
226                         //
227                         string domain_id = (virtualDir.GetHashCode () + 1 ^ physicalDir.GetHashCode () + 2 ^ tempDirTag).ToString ("x");
228
229                         setup.ApplicationName = domain_id;
230                         setup.DynamicBase = dynamic_dir;
231
232                         string dynamic_base = setup.DynamicBase;
233                         if (CreateDirectory (dynamic_base) && (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") == null))
234                                 ClearDynamicBaseDirectory (dynamic_base);
235
236                         //
237                         // Create app domain
238                         //
239                         AppDomain appdomain;
240                         appdomain = AppDomain.CreateDomain (domain_id, evidence, setup);
241
242                         //
243                         // Populate with the AppDomain data keys expected, Mono only uses a
244                         // few, but third party apps might use others:
245                         //
246                         appdomain.SetData (".appDomain", "*");
247                         int l = physicalDir.Length;
248                         if (physicalDir [l - 1] != Path.DirectorySeparatorChar)
249                                 physicalDir += Path.DirectorySeparatorChar;
250                         appdomain.SetData (".appPath", physicalDir);
251                         appdomain.SetData (".appVPath", virtualDir);
252                         appdomain.SetData (".domainId", domain_id);
253                         appdomain.SetData (".hostingVirtualPath", virtualDir);
254                         appdomain.SetData (".hostingInstallDir", Path.GetDirectoryName (typeof (Object).Assembly.CodeBase));
255 #if NET_2_0
256                         appdomain.SetData ("DataDirectory", Path.Combine (physicalDir, "App_Data"));
257 #endif
258                         appdomain.SetData (MonoHostedDataKey, "yes");
259                         
260                         return appdomain.CreateInstanceAndUnwrap (hostType.Module.Assembly.FullName, hostType.FullName);
261                 }
262         }
263 }