Environment.Unix.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Reflection;
  9. using System.Runtime.InteropServices;
  10. using System.Text;
  11. using System.Threading;
  12. namespace System
  13. {
  14. public static partial class Environment
  15. {
  16. private static Func<string, object>? s_directoryCreateDirectory;
  17. private static string CurrentDirectoryCore
  18. {
  19. get => Interop.Sys.GetCwd();
  20. set => Interop.CheckIo(Interop.Sys.ChDir(value), value, isDirectory: true);
  21. }
  22. private static string ExpandEnvironmentVariablesCore(string name)
  23. {
  24. var result = new ValueStringBuilder(stackalloc char[128]);
  25. int lastPos = 0, pos;
  26. while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0)
  27. {
  28. if (name[lastPos] == '%')
  29. {
  30. string key = name.Substring(lastPos + 1, pos - lastPos - 1);
  31. string? value = GetEnvironmentVariable(key);
  32. if (value != null)
  33. {
  34. result.Append(value);
  35. lastPos = pos + 1;
  36. continue;
  37. }
  38. }
  39. result.Append(name.AsSpan(lastPos, pos - lastPos));
  40. lastPos = pos;
  41. }
  42. result.Append(name.AsSpan(lastPos));
  43. return result.ToString();
  44. }
  45. private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option)
  46. {
  47. // Get the path for the SpecialFolder
  48. string path = GetFolderPathCoreWithoutValidation(folder);
  49. Debug.Assert(path != null);
  50. // If we didn't get one, or if we got one but we're not supposed to verify it,
  51. // or if we're supposed to verify it and it passes verification, return the path.
  52. if (path.Length == 0 ||
  53. option == SpecialFolderOption.DoNotVerify ||
  54. Interop.Sys.Access(path, Interop.Sys.AccessMode.R_OK) == 0)
  55. {
  56. return path;
  57. }
  58. // Failed verification. If None, then we're supposed to return an empty string.
  59. // If Create, we're supposed to create it and then return the path.
  60. if (option == SpecialFolderOption.None)
  61. {
  62. return string.Empty;
  63. }
  64. else
  65. {
  66. Debug.Assert(option == SpecialFolderOption.Create);
  67. // TODO #11151: Replace with Directory.CreateDirectory once we have access to System.IO.FileSystem here.
  68. Func<string, object> createDirectory = LazyInitializer.EnsureInitialized(ref s_directoryCreateDirectory, () =>
  69. {
  70. Type dirType = Type.GetType("System.IO.Directory, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: true)!;
  71. MethodInfo mi = dirType.GetTypeInfo().GetDeclaredMethod("CreateDirectory")!;
  72. return (Func<string, object>)mi.CreateDelegate(typeof(Func<string, object>));
  73. });
  74. createDirectory(path);
  75. return path;
  76. }
  77. }
  78. private static string GetFolderPathCoreWithoutValidation(SpecialFolder folder)
  79. {
  80. // First handle any paths that involve only static paths, avoiding the overheads of getting user-local paths.
  81. // https://www.freedesktop.org/software/systemd/man/file-hierarchy.html
  82. switch (folder)
  83. {
  84. case SpecialFolder.CommonApplicationData: return "/usr/share";
  85. case SpecialFolder.CommonTemplates: return "/usr/share/templates";
  86. #if PLATFORM_OSX
  87. case SpecialFolder.ProgramFiles: return "/Applications";
  88. case SpecialFolder.System: return "/System";
  89. #endif
  90. }
  91. // All other paths are based on the XDG Base Directory Specification:
  92. // https://specifications.freedesktop.org/basedir-spec/latest/
  93. string? home = null;
  94. try
  95. {
  96. home = PersistedFiles.GetHomeDirectory();
  97. }
  98. catch (Exception exc)
  99. {
  100. Debug.Fail($"Unable to get home directory: {exc}");
  101. }
  102. // Fall back to '/' when we can't determine the home directory.
  103. // This location isn't writable by non-root users which provides some safeguard
  104. // that the application doesn't write data which is meant to be private.
  105. if (string.IsNullOrEmpty(home))
  106. {
  107. home = "/";
  108. }
  109. // TODO: Consider caching (or precomputing and caching) all subsequent results.
  110. // This would significantly improve performance for repeated access, at the expense
  111. // of not being responsive to changes in the underlying environment variables,
  112. // configuration files, etc.
  113. switch (folder)
  114. {
  115. case SpecialFolder.UserProfile:
  116. case SpecialFolder.MyDocuments: // same value as Personal
  117. return home;
  118. case SpecialFolder.ApplicationData:
  119. return GetXdgConfig(home);
  120. case SpecialFolder.LocalApplicationData:
  121. // "$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored."
  122. // "If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used."
  123. string? data = GetEnvironmentVariable("XDG_DATA_HOME");
  124. if (string.IsNullOrEmpty(data) || data[0] != '/')
  125. {
  126. data = Path.Combine(home, ".local", "share");
  127. }
  128. return data;
  129. case SpecialFolder.Desktop:
  130. case SpecialFolder.DesktopDirectory:
  131. return ReadXdgDirectory(home, "XDG_DESKTOP_DIR", "Desktop");
  132. case SpecialFolder.Templates:
  133. return ReadXdgDirectory(home, "XDG_TEMPLATES_DIR", "Templates");
  134. case SpecialFolder.MyVideos:
  135. return ReadXdgDirectory(home, "XDG_VIDEOS_DIR", "Videos");
  136. #if PLATFORM_OSX
  137. case SpecialFolder.MyMusic:
  138. return Path.Combine(home, "Music");
  139. case SpecialFolder.MyPictures:
  140. return Path.Combine(home, "Pictures");
  141. case SpecialFolder.Fonts:
  142. return Path.Combine(home, "Library", "Fonts");
  143. case SpecialFolder.Favorites:
  144. return Path.Combine(home, "Library", "Favorites");
  145. case SpecialFolder.InternetCache:
  146. return Path.Combine(home, "Library", "Caches");
  147. #else
  148. case SpecialFolder.MyMusic:
  149. return ReadXdgDirectory(home, "XDG_MUSIC_DIR", "Music");
  150. case SpecialFolder.MyPictures:
  151. return ReadXdgDirectory(home, "XDG_PICTURES_DIR", "Pictures");
  152. case SpecialFolder.Fonts:
  153. return Path.Combine(home, ".fonts");
  154. #endif
  155. }
  156. // No known path for the SpecialFolder
  157. return string.Empty;
  158. }
  159. private static string GetXdgConfig(string home)
  160. {
  161. // "$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored."
  162. // "If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used."
  163. string? config = GetEnvironmentVariable("XDG_CONFIG_HOME");
  164. if (string.IsNullOrEmpty(config) || config[0] != '/')
  165. {
  166. config = Path.Combine(home, ".config");
  167. }
  168. return config;
  169. }
  170. private static string ReadXdgDirectory(string homeDir, string key, string fallback)
  171. {
  172. Debug.Assert(!string.IsNullOrEmpty(homeDir), $"Expected non-empty homeDir");
  173. Debug.Assert(!string.IsNullOrEmpty(key), $"Expected non-empty key");
  174. Debug.Assert(!string.IsNullOrEmpty(fallback), $"Expected non-empty fallback");
  175. string? envPath = GetEnvironmentVariable(key);
  176. if (!string.IsNullOrEmpty(envPath) && envPath[0] == '/')
  177. {
  178. return envPath;
  179. }
  180. // Use the user-dirs.dirs file to look up the right config.
  181. // Note that the docs also highlight a list of directories in which to look for this file:
  182. // "$XDG_CONFIG_DIRS defines the preference-ordered set of base directories to search for configuration files in addition
  183. // to the $XDG_CONFIG_HOME base directory. The directories in $XDG_CONFIG_DIRS should be separated with a colon ':'. If
  184. // $XDG_CONFIG_DIRS is either not set or empty, a value equal to / etc / xdg should be used."
  185. // For simplicity, we don't currently do that. We can add it if/when necessary.
  186. string userDirsPath = Path.Combine(GetXdgConfig(homeDir), "user-dirs.dirs");
  187. if (Interop.Sys.Access(userDirsPath, Interop.Sys.AccessMode.R_OK) == 0)
  188. {
  189. try
  190. {
  191. using (var reader = new StreamReader(userDirsPath))
  192. {
  193. string? line;
  194. while ((line = reader.ReadLine()) != null)
  195. {
  196. // Example lines:
  197. // XDG_DESKTOP_DIR="$HOME/Desktop"
  198. // XDG_PICTURES_DIR = "/absolute/path"
  199. // Skip past whitespace at beginning of line
  200. int pos = 0;
  201. SkipWhitespace(line, ref pos);
  202. if (pos >= line.Length) continue;
  203. // Skip past requested key name
  204. if (string.CompareOrdinal(line, pos, key, 0, key.Length) != 0) continue;
  205. pos += key.Length;
  206. // Skip past whitespace and past '='
  207. SkipWhitespace(line, ref pos);
  208. if (pos >= line.Length - 4 || line[pos] != '=') continue; // 4 for ="" and at least one char between quotes
  209. pos++; // skip past '='
  210. // Skip past whitespace and past first quote
  211. SkipWhitespace(line, ref pos);
  212. if (pos >= line.Length - 3 || line[pos] != '"') continue; // 3 for "" and at least one char between quotes
  213. pos++; // skip past opening '"'
  214. // Skip past relative prefix if one exists
  215. bool relativeToHome = false;
  216. const string RelativeToHomePrefix = "$HOME/";
  217. if (string.CompareOrdinal(line, pos, RelativeToHomePrefix, 0, RelativeToHomePrefix.Length) == 0)
  218. {
  219. relativeToHome = true;
  220. pos += RelativeToHomePrefix.Length;
  221. }
  222. else if (line[pos] != '/') // if not relative to home, must be absolute path
  223. {
  224. continue;
  225. }
  226. // Find end of path
  227. int endPos = line.IndexOf('"', pos);
  228. if (endPos <= pos) continue;
  229. // Got we need. Now extract it.
  230. string path = line.Substring(pos, endPos - pos);
  231. return relativeToHome ?
  232. Path.Combine(homeDir, path) :
  233. path;
  234. }
  235. }
  236. }
  237. catch (Exception exc)
  238. {
  239. // assembly not found, file not found, errors reading file, etc. Just eat everything.
  240. Debug.Fail($"Failed reading {userDirsPath}: {exc}");
  241. }
  242. }
  243. return Path.Combine(homeDir, fallback);
  244. }
  245. private static void SkipWhitespace(string line, ref int pos)
  246. {
  247. while (pos < line.Length && char.IsWhiteSpace(line[pos])) pos++;
  248. }
  249. public static string[] GetLogicalDrives() => Interop.Sys.GetAllMountPoints();
  250. private static bool Is64BitOperatingSystemWhen32BitProcess => false;
  251. public static string MachineName
  252. {
  253. get
  254. {
  255. string hostName = Interop.Sys.GetHostName();
  256. int dotPos = hostName.IndexOf('.');
  257. return dotPos == -1 ? hostName : hostName.Substring(0, dotPos);
  258. }
  259. }
  260. internal const string NewLineConst = "\n";
  261. private static OperatingSystem GetOSVersion() => GetOperatingSystem(Interop.Sys.GetUnixRelease());
  262. // Tests exercise this method for corner cases via private reflection
  263. private static OperatingSystem GetOperatingSystem(string release)
  264. {
  265. int major = 0, minor = 0, build = 0, revision = 0;
  266. // Parse the uname's utsname.release for the first four numbers found.
  267. // This isn't perfect, but Version already doesn't map exactly to all possible release
  268. // formats, e.g. 2.6.19-1.2895.fc6
  269. if (release != null)
  270. {
  271. int i = 0;
  272. major = FindAndParseNextNumber(release, ref i);
  273. minor = FindAndParseNextNumber(release, ref i);
  274. build = FindAndParseNextNumber(release, ref i);
  275. revision = FindAndParseNextNumber(release, ref i);
  276. }
  277. // For compatibility reasons with Mono, PlatformID.Unix is returned on MacOSX. PlatformID.MacOSX
  278. // is hidden from the editor and shouldn't be used.
  279. return new OperatingSystem(PlatformID.Unix, new Version(major, minor, build, revision));
  280. }
  281. private static int FindAndParseNextNumber(string text, ref int pos)
  282. {
  283. // Move to the beginning of the number
  284. for (; pos < text.Length; pos++)
  285. {
  286. char c = text[pos];
  287. if ('0' <= c && c <= '9')
  288. {
  289. break;
  290. }
  291. }
  292. // Parse the number;
  293. int num = 0;
  294. for (; pos < text.Length; pos++)
  295. {
  296. char c = text[pos];
  297. if ('0' > c || c > '9')
  298. break;
  299. try
  300. {
  301. num = checked((num * 10) + (c - '0'));
  302. }
  303. // Integer overflow can occur for example with:
  304. // Linux nelknet 4.15.0-24201807041620-generic
  305. // To form a valid Version, num must be positive.
  306. catch (OverflowException)
  307. {
  308. return int.MaxValue;
  309. }
  310. }
  311. return num;
  312. }
  313. public static string SystemDirectory => GetFolderPathCore(SpecialFolder.System, SpecialFolderOption.None);
  314. public static int SystemPageSize => CheckedSysConf(Interop.Sys.SysConfName._SC_PAGESIZE);
  315. public static unsafe string UserName
  316. {
  317. get
  318. {
  319. // First try with a buffer that should suffice for 99% of cases.
  320. string? username;
  321. const int BufLen = Interop.Sys.Passwd.InitialBufferSize;
  322. byte* stackBuf = stackalloc byte[BufLen];
  323. if (TryGetUserNameFromPasswd(stackBuf, BufLen, out username))
  324. {
  325. return username ?? string.Empty;
  326. }
  327. // Fallback to heap allocations if necessary, growing the buffer until
  328. // we succeed. TryGetUserNameFromPasswd will throw if there's an unexpected error.
  329. int lastBufLen = BufLen;
  330. while (true)
  331. {
  332. lastBufLen *= 2;
  333. byte[] heapBuf = new byte[lastBufLen];
  334. fixed (byte* buf = &heapBuf[0])
  335. {
  336. if (TryGetUserNameFromPasswd(buf, heapBuf.Length, out username))
  337. {
  338. return username ?? string.Empty;
  339. }
  340. }
  341. }
  342. }
  343. }
  344. private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string? username)
  345. {
  346. // Call getpwuid_r to get the passwd struct
  347. Interop.Sys.Passwd passwd;
  348. int error = Interop.Sys.GetPwUidR(Interop.Sys.GetEUid(), out passwd, buf, bufLen);
  349. // If the call succeeds, give back the user name retrieved
  350. if (error == 0)
  351. {
  352. Debug.Assert(passwd.Name != null);
  353. username = Marshal.PtrToStringAnsi((IntPtr)passwd.Name);
  354. return true;
  355. }
  356. // If the current user's entry could not be found, give back null,
  357. // but still return true (false indicates the buffer was too small).
  358. if (error == -1)
  359. {
  360. username = null;
  361. return true;
  362. }
  363. var errorInfo = new Interop.ErrorInfo(error);
  364. // If the call failed because the buffer was too small, return false to
  365. // indicate the caller should try again with a larger buffer.
  366. if (errorInfo.Error == Interop.Error.ERANGE)
  367. {
  368. username = null;
  369. return false;
  370. }
  371. // Otherwise, fail.
  372. throw new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno);
  373. }
  374. public static string UserDomainName => MachineName;
  375. /// <summary>Invoke <see cref="Interop.Sys.SysConf"/>, throwing if it fails.</summary>
  376. private static int CheckedSysConf(Interop.Sys.SysConfName name)
  377. {
  378. long result = Interop.Sys.SysConf(name);
  379. if (result == -1)
  380. {
  381. Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo();
  382. throw errno.Error == Interop.Error.EINVAL ?
  383. new ArgumentOutOfRangeException(nameof(name), name, errno.GetErrorMessage()) :
  384. Interop.GetIOException(errno);
  385. }
  386. return (int)result;
  387. }
  388. public static long WorkingSet
  389. {
  390. get
  391. {
  392. Type? processType = Type.GetType("System.Diagnostics.Process, System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
  393. if (processType?.GetMethod("GetCurrentProcess")?.Invoke(null, BindingFlags.DoNotWrapExceptions, null, null, null) is IDisposable currentProcess)
  394. {
  395. using (currentProcess)
  396. {
  397. object? result = processType!.GetMethod("get_WorkingSet64")?.Invoke(currentProcess, BindingFlags.DoNotWrapExceptions, null, null, null);
  398. if (result is long) return (long)result;
  399. }
  400. }
  401. // Could not get the current working set.
  402. return 0;
  403. }
  404. }
  405. }
  406. }