2005-01-24 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mcs / class / corlib / System / Environment.cs
1 //------------------------------------------------------------------------------
2 // 
3 // System.Environment.cs 
4 //
5 // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
6 // 
7 // Author:         Jim Richardson, develop@wtfo-guru.com
8 //                 Dan Lewis (dihlewis@yahoo.co.uk)
9 // Created:        Saturday, August 11, 2001 
10 //
11 //------------------------------------------------------------------------------
12 //
13 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34
35 using System.IO;
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38 using System.Security;
39 using System.Security.Permissions;
40 using System.Text;
41
42 namespace System {
43
44 #if NET_2_0
45         public static class Environment {
46 #else
47         public sealed class Environment {
48
49                 private Environment ()
50                 {
51                 }
52 #endif
53                 /*
54                  * This is the version number of the corlib-runtime interface. When
55                  * making changes to this interface (by changing the layout
56                  * of classes the runtime knows about, changing icall semantics etc),
57                  * increment this variable. Also increment the
58                  * pair of this variable in the runtime in metadata/appdomain.c.
59                  * Changes which are already detected at runtime, like the addition
60                  * of icalls, do not require an increment.
61                  */
62                 private const int mono_corlib_version = 32;
63                
64                 [MonoTODO]
65                 public enum SpecialFolder
66                 {       // TODO: Determine if these windoze style folder identifiers 
67                         //       have unix/linux counterparts
68 #if NET_2_0
69                         MyDocuments = 0x05,
70 #endif
71 #if NET_1_1
72                         Desktop = 0x00,
73                         MyComputer = 0x11,
74 #endif
75                         Programs = 0x02,
76                         Personal = 0x05,
77                         Favorites = 0x06,
78                         Startup = 0x07,
79                         Recent = 0x08,
80                         SendTo = 0x09,
81                         StartMenu = 0x0b,
82                         MyMusic = 0x0d,
83                         DesktopDirectory = 0x10,
84                         Templates = 0x15,
85                         ApplicationData = 0x1a,
86                         LocalApplicationData = 0x1c,
87                         InternetCache = 0x20,
88                         Cookies = 0x21,
89                         History = 0x22,
90                         CommonApplicationData   = 0x23,
91                         System = 0x25,
92                         ProgramFiles = 0x26,
93                         MyPictures = 0x27,
94                         CommonProgramFiles = 0x2b,
95                 }
96
97                 /// <summary>
98                 /// Gets the command line for this process
99                 /// </summary>
100                 public static string CommandLine {
101                         // note: security demand inherited from calling GetCommandLineArgs
102                         get {
103                                 // FIXME: we may need to quote, but any sane person
104                                 // should use GetCommandLineArgs () instead.
105                                 return String.Join (" ", GetCommandLineArgs ());
106                         }
107                 }
108
109                 /// <summary>
110                 /// Gets or sets the current directory. Actually this is supposed to get
111                 /// and/or set the process start directory acording to the documentation
112                 /// but actually test revealed at beta2 it is just Getting/Setting the CurrentDirectory
113                 /// </summary>
114                 public static string CurrentDirectory
115                 {
116                         get {
117                                 return Directory.GetCurrentDirectory ();
118                         }
119                         set {
120                                 Directory.SetCurrentDirectory (value);
121                         }
122                 }
123
124                 /// <summary>
125                 /// Gets or sets the exit code of this process
126                 /// </summary>
127                 public extern static int ExitCode
128                 {       
129                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
130                         get;
131                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
132                         set;
133                 }
134
135 #if NET_1_1
136                 static
137 #endif
138                 public extern bool HasShutdownStarted
139                 {
140                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
141                         get;
142                 }
143                 
144
145                 /// <summary>
146                 /// Gets the name of the local computer
147                 /// </summary>
148                 public extern static string MachineName {
149                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
150                         [EnvironmentPermission (SecurityAction.Demand, Read="COMPUTERNAME")]
151                         [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
152                         get;
153                 }
154
155                 /// <summary>
156                 /// Gets the standard new line value
157                 /// </summary>
158                 public extern static string NewLine {
159                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
160                         get;
161                 }
162
163                 //
164                 // Support methods and fields for OSVersion property
165                 //
166                 static OperatingSystem os;
167
168                 internal static extern PlatformID Platform {
169                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
170                         get;
171                 }
172
173                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
174                 internal static extern string GetOSVersionString ();
175
176                 /// <summary>
177                 /// Gets the current OS version information
178                 /// </summary>
179                 public static OperatingSystem OSVersion {
180                         get {
181                                 if (os == null) {
182                                         Version v = Version.CreateFromString (GetOSVersionString ());
183                                         os = new OperatingSystem (Platform, v);
184                                 }
185                                 return os;
186                         }
187                 }
188
189                 /// <summary>
190                 /// Get StackTrace
191                 /// </summary>
192                 public static string StackTrace {
193                         [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
194                         get {
195                                 System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace (1);
196                                 return trace.ToString ();
197                         }
198                 }
199
200                 /// <summary>
201                 /// Get a fully qualified path to the system directory
202                 /// </summary>
203                 public static string SystemDirectory {
204                         get {
205                                 return GetFolderPath (SpecialFolder.System);
206                         }
207                 }
208
209                 /// <summary>
210                 /// Get the number of milliseconds that have elapsed since the system was booted
211                 /// </summary>
212                 public extern static int TickCount {
213                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
214                         get;
215                 }
216
217                 /// <summary>
218                 /// Get UserDomainName
219                 /// </summary>
220                 public static string UserDomainName {
221                         // FIXME: this variable doesn't exist (at least not on WinXP) - reported to MS as FDBK20562
222                         [EnvironmentPermission (SecurityAction.Demand, Read="USERDOMAINNAME")]
223                         get {
224                                 return MachineName;
225                         }
226                 }
227
228                 /// <summary>
229                 /// Gets a flag indicating whether the process is in interactive mode
230                 /// </summary>
231                 [MonoTODO]
232                 public static bool UserInteractive {
233                         get {
234                                 return false;
235                         }
236                 }
237
238                 /// <summary>
239                 /// Get the user name of current process is running under
240                 /// </summary>
241                 public extern static string UserName {
242                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
243                         [EnvironmentPermission (SecurityAction.Demand, Read="USERNAME;USER")]
244                         get;
245                 }
246
247                 /// <summary>
248                 /// Get the version of the common language runtime 
249                 /// </summary>
250                 public static Version Version {
251                         get {
252 #if NET_2_0
253                                 // FIXME: this is the version number for MS.NET 2.0 beta1. 
254                                 // It must be changed when the final version is released.
255                                 return new Version (2, 0, 40607, 16);
256 #elif NET_1_1                               
257                                 return new Version (1, 1, 4322, 573);
258 #else
259                                 return new Version (1, 0, 3705, 288);
260 #endif
261                         }
262                 }
263
264                 /// <summary>
265                 /// Get the amount of physical memory mapped to process
266                 /// </summary>
267                 [MonoTODO]
268                 public static long WorkingSet {
269                         [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
270                         get { return 0; }
271                 }
272
273                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
274                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
275                 public extern static void Exit (int exitCode);
276
277                 /// <summary>
278                 /// Substitute environment variables in the argument "name"
279                 /// </summary>
280                 public static string ExpandEnvironmentVariables (string name)
281                 {
282                         if (name == null)
283                                 throw new ArgumentNullException ("name");
284
285                         int off1 = name.IndexOf ('%');
286                         if (off1 == -1)
287                                 return name;
288
289                         int len = name.Length;
290                         int off2 = 0;
291                         if (off1 == len - 1 || (off2 = name.IndexOf ('%', off1 + 1)) == -1)
292                                 return name;
293
294                         PlatformID platform = Platform;
295                         StringBuilder result = new StringBuilder ();
296                         result.Append (name, 0, off1);
297                         Hashtable tbl = null;
298                         do {
299                                 string var = name.Substring (off1 + 1, off2 - off1 - 1);
300                                 string value = GetEnvironmentVariable (var);
301                                 if (value == null && (int) platform != 128) {
302                                         // On windows, env. vars. are case insensitive
303                                         if (tbl == null)
304                                                 tbl = GetEnvironmentVariablesNoCase ();
305
306                                         value = tbl [var] as string;
307                                 }
308                                 
309                                 // If value not found, add %FOO to stream,
310                                 //  and use the closing % for the next iteration.
311                                 // If value found, expand it in place of %FOO%
312                                 if (value == null) {
313                                         result.Append ('%');
314                                         result.Append (var);
315                                         off2--;
316                                 } else {
317                                         result.Append (value);
318                                 }
319                                 int oldOff2 = off2;
320                                 off1 = name.IndexOf ('%', off2 + 1);
321                                 // If no % found for off1, don't look for one for off2
322                                 off2 = (off1 == -1 || off2 > len-1)? -1 :name.IndexOf ('%', off1 + 1);
323                                 // textLen is the length of text between the closing % of current iteration
324                                 //  and the starting % of the next iteration if any. This text is added to output
325                                 int textLen;
326                                 // If no new % found, use all the remaining text
327                                 if (off1 == -1 || off2 == -1)
328                                         textLen = len - oldOff2 - 1;
329                                 // If value found in current iteration, use text after current closing % and next %
330                                 else if(value != null)
331                                         textLen = off1 - oldOff2 - 1;
332                                 // If value not found in current iteration, but a % was found for next iteration,
333                                 //  use text from current closing % to the next %.
334                                 else
335                                         textLen = off1 - oldOff2;
336                                 if(off1 >= oldOff2 || off1 == -1)
337                                         result.Append (name.Substring (oldOff2+1, textLen));
338                         } while (off2 > -1 && off2 < len);
339                                 
340                         return result.ToString ();
341
342                 }
343
344                 /// <summary>
345                 /// Return an array of the command line arguments of the current process
346                 /// </summary>
347                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
348                 [EnvironmentPermissionAttribute (SecurityAction.Demand, Read = "PATH")]
349                 public extern static string[] GetCommandLineArgs ();
350
351                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
352                 internal extern static string internalGetEnvironmentVariable (string name);
353
354                 /// <summary>
355                 /// Return a string containing the value of the environment
356                 /// variable identifed by parameter "variable"
357                 /// </summary>
358                 public static string GetEnvironmentVariable (string name)
359                 {
360                         if (SecurityManager.SecurityEnabled) {
361                                 new EnvironmentPermission (EnvironmentPermissionAccess.Read, name).Demand ();
362                         }
363                         return internalGetEnvironmentVariable (name);
364                 }
365
366                 static Hashtable GetEnvironmentVariablesNoCase ()
367                 {
368                         Hashtable vars = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
369                                                         CaseInsensitiveComparer.Default);
370
371                         foreach (string name in GetEnvironmentVariableNames ()) {
372                                 vars [name] = internalGetEnvironmentVariable (name);
373                         }
374
375                         return vars;
376                 }
377
378                 /// <summary>
379                 /// Return a set of all environment variables and their values
380                 /// </summary>
381            
382                 public static IDictionary GetEnvironmentVariables ()
383                 {
384                         StringBuilder sb = null;
385                         if (SecurityManager.SecurityEnabled) {
386                                 // we must have access to each variable to get the lot
387                                 sb = new StringBuilder ();
388                                 // but (performance-wise) we do not want a stack-walk
389                                 // for each of them so we concatenate them
390                         }
391
392                         Hashtable vars = new Hashtable ();
393                         foreach (string name in GetEnvironmentVariableNames ()) {
394                                 vars [name] = internalGetEnvironmentVariable (name);
395                                 if (sb != null) {
396                                         sb.Append (name);
397                                         sb.Append (";");
398                                 }
399                         }
400
401                         if (sb != null) {
402                                 new EnvironmentPermission (EnvironmentPermissionAccess.Read, sb.ToString ()).Demand ();
403                         }
404                         return vars;
405                 }
406
407
408                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
409                 private extern static string GetWindowsFolderPath (int folder);
410
411                 /// <summary>
412                 /// Returns the fully qualified path of the
413                 /// folder specified by the "folder" parameter
414                 /// </summary>
415                 public static string GetFolderPath (SpecialFolder folder)
416                 {
417                         string dir = null;
418
419                         if ((int) Platform != 128) {
420                                 dir = GetWindowsFolderPath ((int) folder);
421                         } else {
422                                 dir = InternalGetFolderPath (folder);
423                         }
424
425                         if ((dir != null) && (dir.Length > 0) && SecurityManager.SecurityEnabled) {
426                                 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dir).Demand ();
427                         }
428                         return dir;
429                 }
430
431                 // the security runtime (and maybe other parts of corlib) needs the
432                 // information to initialize themselves before permissions can be checked
433                 internal static string InternalGetFolderPath (SpecialFolder folder)
434                 {
435                         string home = internalGetHome ();
436
437                         // http://freedesktop.org/Standards/basedir-spec/basedir-spec-0.6.html
438
439                         // note: skip security check for environment variables
440                         string data = internalGetEnvironmentVariable ("XDG_DATA_HOME");
441                         if ((data == null) || (data == String.Empty)) {
442                                 data = Path.Combine (home, ".local");
443                                 data = Path.Combine (data, "share");
444                         }
445
446                         // note: skip security check for environment variables
447                         string config = internalGetEnvironmentVariable ("XDG_CONFIG_HOME");
448                         if ((config == null) || (config == String.Empty)) {
449                                 config = Path.Combine (home, ".config");
450                         }
451
452                         switch (folder) {
453 #if NET_1_1
454                         // MyComputer is a virtual directory
455                         case SpecialFolder.MyComputer:
456                                 return String.Empty;
457 #endif
458                         // personal == ~
459                         case SpecialFolder.Personal:
460                                 return home;
461                         // use FDO's CONFIG_HOME. This data will be synced across a network like the windows counterpart.
462                         case SpecialFolder.ApplicationData:
463                                 return config;
464                         //use FDO's DATA_HOME. This is *NOT* synced
465                         case SpecialFolder.LocalApplicationData:
466                                 return data;
467 #if NET_1_1
468                         case SpecialFolder.Desktop:
469 #endif
470                         case SpecialFolder.DesktopDirectory:
471                                 return Path.Combine (home, "Desktop");
472                         
473                         // these simply dont exist on Linux
474                         // The spec says if a folder doesnt exist, we
475                         // should return ""
476                         case SpecialFolder.Favorites:
477                         case SpecialFolder.Programs:
478                         case SpecialFolder.SendTo:
479                         case SpecialFolder.StartMenu:
480                         case SpecialFolder.Startup:
481                         case SpecialFolder.MyMusic:
482                         case SpecialFolder.MyPictures:
483                         case SpecialFolder.Templates:
484                         case SpecialFolder.Cookies:
485                         case SpecialFolder.History:
486                         case SpecialFolder.InternetCache:
487                         case SpecialFolder.Recent:
488                         case SpecialFolder.CommonProgramFiles:
489                         case SpecialFolder.ProgramFiles:
490                         case SpecialFolder.System:
491                                 return String.Empty;
492                         // This is where data common to all users goes
493                         case SpecialFolder.CommonApplicationData:
494                                 return "/usr/share";
495                         default:
496                                 throw new ArgumentException ("Invalid SpecialFolder");
497                         }
498                 }
499
500                 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
501                 public static string[] GetLogicalDrives ()
502                 {
503                         return GetLogicalDrivesInternal ();
504                 }
505
506                 // FIXME: Anyone using this anywhere ?
507                 static internal string GetResourceString (string s) { return ""; }
508
509                 
510 #if NET_2_0
511                 [MonoTODO ("Machine and User targets aren't supported")]
512                 public static string GetEnvironmentVariable (string variable, EnvironmentVariableTarget target)
513                 {
514                         switch (target) {
515                         case EnvironmentVariableTarget.Process:
516                                 return GetEnvironmentVariable (variable);
517                         case EnvironmentVariableTarget.Machine:
518                                 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
519                                 // under Windows this reads the LOCAL_MACHINE registry key for env vars
520                                 throw new NotImplementedException ();
521                         case EnvironmentVariableTarget.User:
522                                 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
523                                 // under Windows this reads the CURRENT_USER registry key for env vars
524                                 throw new NotImplementedException ();
525                         default:
526                                 throw new ArgumentException ("target");
527                         }
528                 }
529
530                 [MonoTODO ("Machine and User targets aren't supported")]
531                 public static IDictionary GetEnvironmentVariables (EnvironmentVariableTarget target)
532                 {
533                         switch (target) {
534                         case EnvironmentVariableTarget.Process:
535                                 return GetEnvironmentVariables ();
536                         case EnvironmentVariableTarget.Machine:
537                                 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
538                                 // under Windows this reads the LOCAL_MACHINE registry key for env vars
539                                 throw new NotImplementedException ();
540                         case EnvironmentVariableTarget.User:
541                                 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
542                                 // under Windows this reads the CURRENT_USER registry key for env vars
543                                 throw new NotImplementedException ();
544                         default:
545                                 throw new ArgumentException ("target");
546                         }
547                 }
548
549                 [MonoTODO]
550                 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
551                 public static void SetEnvironmentVariable (string variable, string value)
552                 {
553                         InternalSetEnvironmentVariable (variable, value);
554                 }
555
556                 [MonoTODO]
557                 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
558                 public static void SetEnvironmentVariable (string variable, string value, EnvironmentVariableTarget target)
559                 {
560                         switch (target) {
561                         case EnvironmentVariableTarget.Process:
562                                 InternalSetEnvironmentVariable (variable, value);
563                                 break;
564                         case EnvironmentVariableTarget.Machine:
565                                 // under Windows this reads the LOCAL_MACHINE registry key for env vars
566                                 throw new NotImplementedException ();
567                         case EnvironmentVariableTarget.User:
568                                 // under Windows this reads the CURRENT_USER registry key for env vars
569                                 throw new NotImplementedException ();
570                         default:
571                                 throw new ArgumentException ("target");
572                         }
573                 }
574
575                 // FIXME: to be changed as an icall when implemented
576                 internal static void InternalSetEnvironmentVariable (string variable, string value)
577                 {
578                         throw new NotImplementedException ();
579                 }
580
581                 [MonoTODO]
582                 public static int ProcessorCount {
583                         [EnvironmentPermission (SecurityAction.Demand, Read="NUMBER_OF_PROCESSORS")]
584                         get {
585                                 // note: Changes to the NUMBER_OF_PROCESSORS environment variable
586                                 // under Windows doesn't affect the (good) value returned.
587                                 throw new NotImplementedException ();
588                         }
589                 }
590
591                 [MonoTODO ("not much documented")]
592                 // FIXME: doesn't seems to have any protection ?!? reported as FDBK20543
593                 public static void FailFast (string message)
594                 {
595                         throw new NotImplementedException ();
596                 }
597 #endif                
598                 
599                 // private methods
600
601                 private static string GacPath {
602                         get {
603                                 if ((int) Platform != 128) {
604                                         /* On windows, we don't know the path where mscorlib.dll will be installed */
605                                         string corlibDir = new DirectoryInfo (Path.GetDirectoryName (typeof (int).Assembly.Location)).Parent.Parent.FullName;
606                                         return Path.Combine (Path.Combine (corlibDir, "mono"), "gac");
607                                 }
608
609                                 return Path.Combine (Path.Combine (internalGetGacPath (), "mono"), "gac");
610                         }
611                 }
612
613                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
614                 private extern static string [] GetLogicalDrivesInternal ();
615
616                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
617                 private extern static string [] GetEnvironmentVariableNames ();
618
619                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
620                 internal extern static string GetMachineConfigPath ();
621
622                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
623                 internal extern static string internalGetGacPath ();
624
625                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
626                 internal extern static string internalGetHome ();
627         }
628 }
629