Environment.Unix.cs 19 KB

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