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. 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 OperatingSystem GetOSVersion() => GetOperatingSystem(Interop.Sys.GetUnixRelease());
  264. // Tests exercise this method for corner cases via private reflection
  265. private static OperatingSystem GetOperatingSystem(string release)
  266. {
  267. int major = 0, minor = 0, build = 0, revision = 0;
  268. // Parse the uname's utsname.release for the first four numbers found.
  269. // This isn't perfect, but Version already doesn't map exactly to all possible release
  270. // formats, e.g. 2.6.19-1.2895.fc6
  271. if (release != null)
  272. {
  273. int i = 0;
  274. major = FindAndParseNextNumber(release, ref i);
  275. minor = FindAndParseNextNumber(release, ref i);
  276. build = FindAndParseNextNumber(release, ref i);
  277. revision = FindAndParseNextNumber(release, ref i);
  278. }
  279. // For compatibility reasons with Mono, PlatformID.Unix is returned on MacOSX. PlatformID.MacOSX
  280. // is hidden from the editor and shouldn't be used.
  281. return new OperatingSystem(PlatformID.Unix, new Version(major, minor, build, revision));
  282. }
  283. private static int FindAndParseNextNumber(string text, ref int pos)
  284. {
  285. // Move to the beginning of the number
  286. for (; pos < text.Length; pos++)
  287. {
  288. char c = text[pos];
  289. if ('0' <= c && c <= '9')
  290. {
  291. break;
  292. }
  293. }
  294. // Parse the number;
  295. int num = 0;
  296. for (; pos < text.Length; pos++)
  297. {
  298. char c = text[pos];
  299. if ('0' > c || c > '9')
  300. break;
  301. try
  302. {
  303. num = checked((num * 10) + (c - '0'));
  304. }
  305. // Integer overflow can occur for example with:
  306. // Linux nelknet 4.15.0-24201807041620-generic
  307. // To form a valid Version, num must be positive.
  308. catch (OverflowException)
  309. {
  310. return int.MaxValue;
  311. }
  312. }
  313. return num;
  314. }
  315. public static string SystemDirectory => GetFolderPathCore(SpecialFolder.System, SpecialFolderOption.None);
  316. public static int SystemPageSize => CheckedSysConf(Interop.Sys.SysConfName._SC_PAGESIZE);
  317. public static unsafe string UserName
  318. {
  319. get
  320. {
  321. // First try with a buffer that should suffice for 99% of cases.
  322. string username;
  323. const int BufLen = Interop.Sys.Passwd.InitialBufferSize;
  324. byte* stackBuf = stackalloc byte[BufLen];
  325. if (TryGetUserNameFromPasswd(stackBuf, BufLen, out username))
  326. {
  327. return username;
  328. }
  329. // Fallback to heap allocations if necessary, growing the buffer until
  330. // we succeed. TryGetUserNameFromPasswd will throw if there's an unexpected error.
  331. int lastBufLen = BufLen;
  332. while (true)
  333. {
  334. lastBufLen *= 2;
  335. byte[] heapBuf = new byte[lastBufLen];
  336. fixed (byte* buf = &heapBuf[0])
  337. {
  338. if (TryGetUserNameFromPasswd(buf, heapBuf.Length, out username))
  339. {
  340. return username;
  341. }
  342. }
  343. }
  344. }
  345. }
  346. private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string path)
  347. {
  348. // Call getpwuid_r to get the passwd struct
  349. Interop.Sys.Passwd passwd;
  350. int error = Interop.Sys.GetPwUidR(Interop.Sys.GetEUid(), out passwd, buf, bufLen);
  351. // If the call succeeds, give back the user name retrieved
  352. if (error == 0)
  353. {
  354. Debug.Assert(passwd.Name != null);
  355. path = Marshal.PtrToStringAnsi((IntPtr)passwd.Name);
  356. return true;
  357. }
  358. // If the current user's entry could not be found, give back null,
  359. // but still return true as false indicates the buffer was too small.
  360. if (error == -1)
  361. {
  362. path = null;
  363. return true;
  364. }
  365. var errorInfo = new Interop.ErrorInfo(error);
  366. // If the call failed because the buffer was too small, return false to
  367. // indicate the caller should try again with a larger buffer.
  368. if (errorInfo.Error == Interop.Error.ERANGE)
  369. {
  370. path = null;
  371. return false;
  372. }
  373. // Otherwise, fail.
  374. throw new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno);
  375. }
  376. public static string UserDomainName => MachineName;
  377. /// <summary>Invoke <see cref="Interop.Sys.SysConf"/>, throwing if it fails.</summary>
  378. private static int CheckedSysConf(Interop.Sys.SysConfName name)
  379. {
  380. long result = Interop.Sys.SysConf(name);
  381. if (result == -1)
  382. {
  383. Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo();
  384. throw errno.Error == Interop.Error.EINVAL ?
  385. new ArgumentOutOfRangeException(nameof(name), name, errno.GetErrorMessage()) :
  386. Interop.GetIOException(errno);
  387. }
  388. return (int)result;
  389. }
  390. }
  391. }