Environment.Unix.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. internal static readonly bool IsMac = Interop.Sys.GetUnixName() == "OSX";
  18. private static Func<string, object> s_directoryCreateDirectory;
  19. private static string CurrentDirectoryCore
  20. {
  21. get { return Interop.Sys.GetCwd(); }
  22. set { Interop.CheckIo(Interop.Sys.ChDir(value), value, isDirectory: true); }
  23. }
  24. public static int ExitCode { get { return EnvironmentAugments.ExitCode; } set { EnvironmentAugments.ExitCode = value; } }
  25. private static string ExpandEnvironmentVariablesCore(string name)
  26. {
  27. Span<char> initialBuffer = stackalloc char[128];
  28. var result = new ValueStringBuilder(initialBuffer);
  29. int lastPos = 0, pos;
  30. while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0)
  31. {
  32. if (name[lastPos] == '%')
  33. {
  34. string key = name.Substring(lastPos + 1, pos - lastPos - 1);
  35. string value = GetEnvironmentVariable(key);
  36. if (value != null)
  37. {
  38. result.Append(value);
  39. lastPos = pos + 1;
  40. continue;
  41. }
  42. }
  43. result.Append(name.AsSpan(lastPos, pos - lastPos));
  44. lastPos = pos;
  45. }
  46. result.Append(name.AsSpan(lastPos));
  47. return result.ToString();
  48. }
  49. private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option)
  50. {
  51. // Get the path for the SpecialFolder
  52. string path = GetFolderPathCoreWithoutValidation(folder);
  53. Debug.Assert(path != null);
  54. // If we didn't get one, or if we got one but we're not supposed to verify it,
  55. // or if we're supposed to verify it and it passes verification, return the path.
  56. if (path.Length == 0 ||
  57. option == SpecialFolderOption.DoNotVerify ||
  58. Interop.Sys.Access(path, Interop.Sys.AccessMode.R_OK) == 0)
  59. {
  60. return path;
  61. }
  62. // Failed verification. If None, then we're supposed to return an empty string.
  63. // If Create, we're supposed to create it and then return the path.
  64. if (option == SpecialFolderOption.None)
  65. {
  66. return string.Empty;
  67. }
  68. else
  69. {
  70. Debug.Assert(option == SpecialFolderOption.Create);
  71. // TODO #11151: Replace with Directory.CreateDirectory once we have access to System.IO.FileSystem here.
  72. Func<string, object> createDirectory = LazyInitializer.EnsureInitialized(ref s_directoryCreateDirectory, () =>
  73. {
  74. Type dirType = Type.GetType("System.IO.Directory, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: true);
  75. MethodInfo mi = dirType.GetTypeInfo().GetDeclaredMethod("CreateDirectory");
  76. return (Func<string, object>)mi.CreateDelegate(typeof(Func<string, object>));
  77. });
  78. createDirectory(path);
  79. return path;
  80. }
  81. }
  82. private static string GetFolderPathCoreWithoutValidation(SpecialFolder folder)
  83. {
  84. // First handle any paths that involve only static paths, avoiding the overheads of getting user-local paths.
  85. // https://www.freedesktop.org/software/systemd/man/file-hierarchy.html
  86. switch (folder)
  87. {
  88. case SpecialFolder.CommonApplicationData: return "/usr/share";
  89. case SpecialFolder.CommonTemplates: return "/usr/share/templates";
  90. }
  91. if (IsMac)
  92. {
  93. switch (folder)
  94. {
  95. case SpecialFolder.ProgramFiles: return "/Applications";
  96. case SpecialFolder.System: return "/System";
  97. }
  98. }
  99. // All other paths are based on the XDG Base Directory Specification:
  100. // https://specifications.freedesktop.org/basedir-spec/latest/
  101. string home = null;
  102. try
  103. {
  104. home = PersistedFiles.GetHomeDirectory();
  105. }
  106. catch (Exception exc)
  107. {
  108. Debug.Fail($"Unable to get home directory: {exc}");
  109. }
  110. // Fall back to '/' when we can't determine the home directory.
  111. // This location isn't writable by non-root users which provides some safeguard
  112. // that the application doesn't write data which is meant to be private.
  113. if (string.IsNullOrEmpty(home))
  114. {
  115. home = "/";
  116. }
  117. // TODO: Consider caching (or precomputing and caching) all subsequent results.
  118. // This would significantly improve performance for repeated access, at the expense
  119. // of not being responsive to changes in the underlying environment variables,
  120. // configuration files, etc.
  121. switch (folder)
  122. {
  123. case SpecialFolder.UserProfile:
  124. case SpecialFolder.MyDocuments: // same value as Personal
  125. return home;
  126. case SpecialFolder.ApplicationData:
  127. return GetXdgConfig(home);
  128. case SpecialFolder.LocalApplicationData:
  129. // "$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored."
  130. // "If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used."
  131. string data = GetEnvironmentVariable("XDG_DATA_HOME");
  132. if (string.IsNullOrEmpty(data) || data[0] != '/')
  133. {
  134. data = Path.Combine(home, ".local", "share");
  135. }
  136. return data;
  137. case SpecialFolder.Desktop:
  138. case SpecialFolder.DesktopDirectory:
  139. return ReadXdgDirectory(home, "XDG_DESKTOP_DIR", "Desktop");
  140. case SpecialFolder.Templates:
  141. return ReadXdgDirectory(home, "XDG_TEMPLATES_DIR", "Templates");
  142. case SpecialFolder.MyVideos:
  143. return ReadXdgDirectory(home, "XDG_VIDEOS_DIR", "Videos");
  144. case SpecialFolder.MyMusic:
  145. return IsMac ? Path.Combine(home, "Music") : ReadXdgDirectory(home, "XDG_MUSIC_DIR", "Music");
  146. case SpecialFolder.MyPictures:
  147. return IsMac ? Path.Combine(home, "Pictures") : ReadXdgDirectory(home, "XDG_PICTURES_DIR", "Pictures");
  148. case SpecialFolder.Fonts:
  149. return IsMac ? Path.Combine(home, "Library", "Fonts") : Path.Combine(home, ".fonts");
  150. case SpecialFolder.Favorites:
  151. if (IsMac) return Path.Combine(home, "Library", "Favorites");
  152. break;
  153. case SpecialFolder.InternetCache:
  154. if (IsMac) return Path.Combine(home, "Library", "Caches");
  155. break;
  156. }
  157. // No known path for the SpecialFolder
  158. return string.Empty;
  159. }
  160. private static string GetXdgConfig(string home)
  161. {
  162. // "$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored."
  163. // "If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used."
  164. string config = GetEnvironmentVariable("XDG_CONFIG_HOME");
  165. if (string.IsNullOrEmpty(config) || config[0] != '/')
  166. {
  167. config = Path.Combine(home, ".config");
  168. }
  169. return config;
  170. }
  171. private static string ReadXdgDirectory(string homeDir, string key, string fallback)
  172. {
  173. Debug.Assert(!string.IsNullOrEmpty(homeDir), $"Expected non-empty homeDir");
  174. Debug.Assert(!string.IsNullOrEmpty(key), $"Expected non-empty key");
  175. Debug.Assert(!string.IsNullOrEmpty(fallback), $"Expected non-empty fallback");
  176. string envPath = GetEnvironmentVariable(key);
  177. if (!string.IsNullOrEmpty(envPath) && envPath[0] == '/')
  178. {
  179. return envPath;
  180. }
  181. // Use the user-dirs.dirs file to look up the right config.
  182. // Note that the docs also highlight a list of directories in which to look for this file:
  183. // "$XDG_CONFIG_DIRS defines the preference-ordered set of base directories to search for configuration files in addition
  184. // to the $XDG_CONFIG_HOME base directory. The directories in $XDG_CONFIG_DIRS should be separated with a colon ':'. If
  185. // $XDG_CONFIG_DIRS is either not set or empty, a value equal to / etc / xdg should be used."
  186. // For simplicity, we don't currently do that. We can add it if/when necessary.
  187. string userDirsPath = Path.Combine(GetXdgConfig(homeDir), "user-dirs.dirs");
  188. if (Interop.Sys.Access(userDirsPath, Interop.Sys.AccessMode.R_OK) == 0)
  189. {
  190. try
  191. {
  192. using (var reader = new StreamReader(userDirsPath))
  193. {
  194. string line;
  195. while ((line = reader.ReadLine()) != null)
  196. {
  197. // Example lines:
  198. // XDG_DESKTOP_DIR="$HOME/Desktop"
  199. // XDG_PICTURES_DIR = "/absolute/path"
  200. // Skip past whitespace at beginning of line
  201. int pos = 0;
  202. SkipWhitespace(line, ref pos);
  203. if (pos >= line.Length) continue;
  204. // Skip past requested key name
  205. if (string.CompareOrdinal(line, pos, key, 0, key.Length) != 0) continue;
  206. pos += key.Length;
  207. // Skip past whitespace and past '='
  208. SkipWhitespace(line, ref pos);
  209. if (pos >= line.Length - 4 || line[pos] != '=') continue; // 4 for ="" and at least one char between quotes
  210. pos++; // skip past '='
  211. // Skip past whitespace and past first quote
  212. SkipWhitespace(line, ref pos);
  213. if (pos >= line.Length - 3 || line[pos] != '"') continue; // 3 for "" and at least one char between quotes
  214. pos++; // skip past opening '"'
  215. // Skip past relative prefix if one exists
  216. bool relativeToHome = false;
  217. const string RelativeToHomePrefix = "$HOME/";
  218. if (string.CompareOrdinal(line, pos, RelativeToHomePrefix, 0, RelativeToHomePrefix.Length) == 0)
  219. {
  220. relativeToHome = true;
  221. pos += RelativeToHomePrefix.Length;
  222. }
  223. else if (line[pos] != '/') // if not relative to home, must be absolute path
  224. {
  225. continue;
  226. }
  227. // Find end of path
  228. int endPos = line.IndexOf('"', pos);
  229. if (endPos <= pos) continue;
  230. // Got we need. Now extract it.
  231. string path = line.Substring(pos, endPos - pos);
  232. return relativeToHome ?
  233. Path.Combine(homeDir, path) :
  234. path;
  235. }
  236. }
  237. }
  238. catch (Exception exc)
  239. {
  240. // assembly not found, file not found, errors reading file, etc. Just eat everything.
  241. Debug.Fail($"Failed reading {userDirsPath}: {exc}");
  242. }
  243. }
  244. return Path.Combine(homeDir, fallback);
  245. }
  246. private static void SkipWhitespace(string line, ref int pos)
  247. {
  248. while (pos < line.Length && char.IsWhiteSpace(line[pos])) pos++;
  249. }
  250. public static string[] GetLogicalDrives() => Interop.Sys.GetAllMountPoints();
  251. private static bool Is64BitOperatingSystemWhen32BitProcess => false;
  252. public static string MachineName
  253. {
  254. get
  255. {
  256. string hostName = Interop.Sys.GetHostName();
  257. int dotPos = hostName.IndexOf('.');
  258. return dotPos == -1 ? hostName : hostName.Substring(0, dotPos);
  259. }
  260. }
  261. public static string NewLine => "\n";
  262. private static readonly Lazy<OperatingSystem> s_osVersion = new Lazy<OperatingSystem>(() => GetOperatingSystem(Interop.Sys.GetUnixRelease()));
  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;
  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;
  339. }
  340. }
  341. }
  342. }
  343. }
  344. private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string path)
  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. path = 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 as false indicates the buffer was too small.
  358. if (error == -1)
  359. {
  360. path = 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. path = 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. }
  389. }