Environment.Unix.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 Internal.Runtime.Augments;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Text;
  12. using System.Threading;
  13. namespace System
  14. {
  15. public static partial class Environment
  16. {
  17. private static readonly bool s_isMac = Interop.Sys.GetUnixName() == "OSX";
  18. private static Func<string, object> s_directoryCreateDirectory;
  19. private static string CurrentDirectoryCore
  20. {
  21. get => Interop.Sys.GetCwd();
  22. set => Interop.CheckIo(Interop.Sys.ChDir(value), value, isDirectory: true);
  23. }
  24. private static string ExpandEnvironmentVariablesCore(string name)
  25. {
  26. Span<char> initialBuffer = stackalloc char[128];
  27. var result = new ValueStringBuilder(initialBuffer);
  28. int lastPos = 0, pos;
  29. while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0)
  30. {
  31. if (name[lastPos] == '%')
  32. {
  33. string key = name.Substring(lastPos + 1, pos - lastPos - 1);
  34. string value = GetEnvironmentVariable(key);
  35. if (value != null)
  36. {
  37. result.Append(value);
  38. lastPos = pos + 1;
  39. continue;
  40. }
  41. }
  42. result.Append(name.AsSpan(lastPos, pos - lastPos));
  43. lastPos = pos;
  44. }
  45. result.Append(name.AsSpan(lastPos));
  46. return result.ToString();
  47. }
  48. private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option)
  49. {
  50. // Get the path for the SpecialFolder
  51. string path = GetFolderPathCoreWithoutValidation(folder);
  52. Debug.Assert(path != null);
  53. // If we didn't get one, or if we got one but we're not supposed to verify it,
  54. // or if we're supposed to verify it and it passes verification, return the path.
  55. if (path.Length == 0 ||
  56. option == SpecialFolderOption.DoNotVerify ||
  57. Interop.Sys.Access(path, Interop.Sys.AccessMode.R_OK) == 0)
  58. {
  59. return path;
  60. }
  61. // Failed verification. If None, then we're supposed to return an empty string.
  62. // If Create, we're supposed to create it and then return the path.
  63. if (option == SpecialFolderOption.None)
  64. {
  65. return string.Empty;
  66. }
  67. else
  68. {
  69. Debug.Assert(option == SpecialFolderOption.Create);
  70. // TODO #11151: Replace with Directory.CreateDirectory once we have access to System.IO.FileSystem here.
  71. Func<string, object> createDirectory = LazyInitializer.EnsureInitialized(ref s_directoryCreateDirectory, () =>
  72. {
  73. Type dirType = Type.GetType("System.IO.Directory, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: true);
  74. MethodInfo mi = dirType.GetTypeInfo().GetDeclaredMethod("CreateDirectory");
  75. return (Func<string, object>)mi.CreateDelegate(typeof(Func<string, object>));
  76. });
  77. createDirectory(path);
  78. return path;
  79. }
  80. }
  81. private static string GetFolderPathCoreWithoutValidation(SpecialFolder folder)
  82. {
  83. // First handle any paths that involve only static paths, avoiding the overheads of getting user-local paths.
  84. // https://www.freedesktop.org/software/systemd/man/file-hierarchy.html
  85. switch (folder)
  86. {
  87. case SpecialFolder.CommonApplicationData: return "/usr/share";
  88. case SpecialFolder.CommonTemplates: return "/usr/share/templates";
  89. }
  90. if (s_isMac)
  91. {
  92. switch (folder)
  93. {
  94. case SpecialFolder.ProgramFiles: return "/Applications";
  95. case SpecialFolder.System: return "/System";
  96. }
  97. }
  98. // All other paths are based on the XDG Base Directory Specification:
  99. // https://specifications.freedesktop.org/basedir-spec/latest/
  100. string home = null;
  101. try
  102. {
  103. home = PersistedFiles.GetHomeDirectory();
  104. }
  105. catch (Exception exc)
  106. {
  107. Debug.Fail($"Unable to get home directory: {exc}");
  108. }
  109. // Fall back to '/' when we can't determine the home directory.
  110. // This location isn't writable by non-root users which provides some safeguard
  111. // that the application doesn't write data which is meant to be private.
  112. if (string.IsNullOrEmpty(home))
  113. {
  114. home = "/";
  115. }
  116. // TODO: Consider caching (or precomputing and caching) all subsequent results.
  117. // This would significantly improve performance for repeated access, at the expense
  118. // of not being responsive to changes in the underlying environment variables,
  119. // configuration files, etc.
  120. switch (folder)
  121. {
  122. case SpecialFolder.UserProfile:
  123. case SpecialFolder.MyDocuments: // same value as Personal
  124. return home;
  125. case SpecialFolder.ApplicationData:
  126. return GetXdgConfig(home);
  127. case SpecialFolder.LocalApplicationData:
  128. // "$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored."
  129. // "If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used."
  130. string data = GetEnvironmentVariable("XDG_DATA_HOME");
  131. if (string.IsNullOrEmpty(data) || data[0] != '/')
  132. {
  133. data = Path.Combine(home, ".local", "share");
  134. }
  135. return data;
  136. case SpecialFolder.Desktop:
  137. case SpecialFolder.DesktopDirectory:
  138. return ReadXdgDirectory(home, "XDG_DESKTOP_DIR", "Desktop");
  139. case SpecialFolder.Templates:
  140. return ReadXdgDirectory(home, "XDG_TEMPLATES_DIR", "Templates");
  141. case SpecialFolder.MyVideos:
  142. return ReadXdgDirectory(home, "XDG_VIDEOS_DIR", "Videos");
  143. case SpecialFolder.MyMusic:
  144. return s_isMac ? Path.Combine(home, "Music") : ReadXdgDirectory(home, "XDG_MUSIC_DIR", "Music");
  145. case SpecialFolder.MyPictures:
  146. return s_isMac ? Path.Combine(home, "Pictures") : ReadXdgDirectory(home, "XDG_PICTURES_DIR", "Pictures");
  147. case SpecialFolder.Fonts:
  148. return s_isMac ? Path.Combine(home, "Library", "Fonts") : Path.Combine(home, ".fonts");
  149. case SpecialFolder.Favorites:
  150. if (s_isMac) return Path.Combine(home, "Library", "Favorites");
  151. break;
  152. case SpecialFolder.InternetCache:
  153. if (s_isMac) return Path.Combine(home, "Library", "Caches");
  154. break;
  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. public static string NewLine => "\n";
  261. private static readonly Lazy<OperatingSystem> s_osVersion = new Lazy<OperatingSystem>(() => GetOperatingSystem(Interop.Sys.GetUnixRelease()));
  262. private static OperatingSystem GetOperatingSystem(string release)
  263. {
  264. int major = 0, minor = 0, build = 0, revision = 0;
  265. // Parse the uname's utsname.release for the first four numbers found.
  266. // This isn't perfect, but Version already doesn't map exactly to all possible release
  267. // formats, e.g. 2.6.19-1.2895.fc6
  268. if (release != null)
  269. {
  270. int i = 0;
  271. major = FindAndParseNextNumber(release, ref i);
  272. minor = FindAndParseNextNumber(release, ref i);
  273. build = FindAndParseNextNumber(release, ref i);
  274. revision = FindAndParseNextNumber(release, ref i);
  275. }
  276. // For compatibility reasons with Mono, PlatformID.Unix is returned on MacOSX. PlatformID.MacOSX
  277. // is hidden from the editor and shouldn't be used.
  278. return new OperatingSystem(PlatformID.Unix, new Version(major, minor, build, revision));
  279. }
  280. private static int FindAndParseNextNumber(string text, ref int pos)
  281. {
  282. // Move to the beginning of the number
  283. for (; pos < text.Length; pos++)
  284. {
  285. char c = text[pos];
  286. if ('0' <= c && c <= '9')
  287. {
  288. break;
  289. }
  290. }
  291. // Parse the number;
  292. int num = 0;
  293. for (; pos < text.Length; pos++)
  294. {
  295. char c = text[pos];
  296. if ('0' > c || c > '9')
  297. break;
  298. try
  299. {
  300. num = checked((num * 10) + (c - '0'));
  301. }
  302. // Integer overflow can occur for example with:
  303. // Linux nelknet 4.15.0-24201807041620-generic
  304. // To form a valid Version, num must be positive.
  305. catch (OverflowException)
  306. {
  307. return int.MaxValue;
  308. }
  309. }
  310. return num;
  311. }
  312. public static string SystemDirectory => GetFolderPathCore(SpecialFolder.System, SpecialFolderOption.None);
  313. public static int SystemPageSize => CheckedSysConf(Interop.Sys.SysConfName._SC_PAGESIZE);
  314. public static unsafe string UserName
  315. {
  316. get
  317. {
  318. // First try with a buffer that should suffice for 99% of cases.
  319. string username;
  320. const int BufLen = Interop.Sys.Passwd.InitialBufferSize;
  321. byte* stackBuf = stackalloc byte[BufLen];
  322. if (TryGetUserNameFromPasswd(stackBuf, BufLen, out username))
  323. {
  324. return username;
  325. }
  326. // Fallback to heap allocations if necessary, growing the buffer until
  327. // we succeed. TryGetUserNameFromPasswd will throw if there's an unexpected error.
  328. int lastBufLen = BufLen;
  329. while (true)
  330. {
  331. lastBufLen *= 2;
  332. byte[] heapBuf = new byte[lastBufLen];
  333. fixed (byte* buf = &heapBuf[0])
  334. {
  335. if (TryGetUserNameFromPasswd(buf, heapBuf.Length, out username))
  336. {
  337. return username;
  338. }
  339. }
  340. }
  341. }
  342. }
  343. private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string path)
  344. {
  345. // Call getpwuid_r to get the passwd struct
  346. Interop.Sys.Passwd passwd;
  347. int error = Interop.Sys.GetPwUidR(Interop.Sys.GetEUid(), out passwd, buf, bufLen);
  348. // If the call succeeds, give back the user name retrieved
  349. if (error == 0)
  350. {
  351. Debug.Assert(passwd.Name != null);
  352. path = Marshal.PtrToStringAnsi((IntPtr)passwd.Name);
  353. return true;
  354. }
  355. // If the current user's entry could not be found, give back null,
  356. // but still return true as false indicates the buffer was too small.
  357. if (error == -1)
  358. {
  359. path = null;
  360. return true;
  361. }
  362. var errorInfo = new Interop.ErrorInfo(error);
  363. // If the call failed because the buffer was too small, return false to
  364. // indicate the caller should try again with a larger buffer.
  365. if (errorInfo.Error == Interop.Error.ERANGE)
  366. {
  367. path = null;
  368. return false;
  369. }
  370. // Otherwise, fail.
  371. throw new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno);
  372. }
  373. public static string UserDomainName => MachineName;
  374. /// <summary>Invoke <see cref="Interop.Sys.SysConf"/>, throwing if it fails.</summary>
  375. private static int CheckedSysConf(Interop.Sys.SysConfName name)
  376. {
  377. long result = Interop.Sys.SysConf(name);
  378. if (result == -1)
  379. {
  380. Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo();
  381. throw errno.Error == Interop.Error.EINVAL ?
  382. new ArgumentOutOfRangeException(nameof(name), name, errno.GetErrorMessage()) :
  383. Interop.GetIOException(errno);
  384. }
  385. return (int)result;
  386. }
  387. }
  388. }