You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FS_POSIX.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * Copyright (C) 2010, Robin Rosenberg
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.util;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.io.InputStreamReader;
  48. import java.io.PrintStream;
  49. import java.nio.charset.Charset;
  50. import java.nio.file.Files;
  51. import java.nio.file.Path;
  52. import java.nio.file.Paths;
  53. import java.nio.file.attribute.PosixFilePermission;
  54. import java.util.ArrayList;
  55. import java.util.Arrays;
  56. import java.util.List;
  57. import java.util.Set;
  58. import org.eclipse.jgit.api.errors.JGitInternalException;
  59. import org.eclipse.jgit.errors.CommandFailedException;
  60. import org.eclipse.jgit.errors.ConfigInvalidException;
  61. import org.eclipse.jgit.lib.ConfigConstants;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.storage.file.FileBasedConfig;
  65. import org.slf4j.Logger;
  66. import org.slf4j.LoggerFactory;
  67. /**
  68. * Base FS for POSIX based systems
  69. *
  70. * @since 3.0
  71. */
  72. public class FS_POSIX extends FS {
  73. private final static Logger LOG = LoggerFactory.getLogger(FS_POSIX.class);
  74. private static final int DEFAULT_UMASK = 0022;
  75. private volatile int umask = -1;
  76. private volatile boolean supportsUnixNLink = true;
  77. private volatile Boolean supportsAtomicCreateNewFile;
  78. /** Default constructor. */
  79. protected FS_POSIX() {
  80. }
  81. /**
  82. * Constructor
  83. *
  84. * @param src
  85. * FS to copy some settings from
  86. */
  87. protected FS_POSIX(FS src) {
  88. super(src);
  89. if (src instanceof FS_POSIX) {
  90. umask = ((FS_POSIX) src).umask;
  91. }
  92. }
  93. private void determineAtomicFileCreationSupport() {
  94. // @TODO: enhance SystemReader to support this without copying code
  95. Boolean ret = getAtomicFileCreationSupportOption(
  96. SystemReader.getInstance().openUserConfig(null, this));
  97. if (ret == null && StringUtils.isEmptyOrNull(SystemReader.getInstance()
  98. .getenv(Constants.GIT_CONFIG_NOSYSTEM_KEY))) {
  99. ret = getAtomicFileCreationSupportOption(
  100. SystemReader.getInstance().openSystemConfig(null, this));
  101. }
  102. supportsAtomicCreateNewFile = (ret == null) || ret;
  103. }
  104. private Boolean getAtomicFileCreationSupportOption(FileBasedConfig config) {
  105. try {
  106. config.load();
  107. String value = config.getString(ConfigConstants.CONFIG_CORE_SECTION,
  108. null,
  109. ConfigConstants.CONFIG_KEY_SUPPORTSATOMICFILECREATION);
  110. if (value == null) {
  111. return null;
  112. }
  113. return Boolean.valueOf(StringUtils.toBoolean(value));
  114. } catch (IOException | ConfigInvalidException e) {
  115. return Boolean.TRUE;
  116. }
  117. }
  118. @Override
  119. public FS newInstance() {
  120. return new FS_POSIX(this);
  121. }
  122. /**
  123. * Set the umask, overriding any value observed from the shell.
  124. *
  125. * @param umask
  126. * mask to apply when creating files.
  127. * @since 4.0
  128. */
  129. public void setUmask(int umask) {
  130. this.umask = umask;
  131. }
  132. private int umask() {
  133. int u = umask;
  134. if (u == -1) {
  135. u = readUmask();
  136. umask = u;
  137. }
  138. return u;
  139. }
  140. /** @return mask returned from running {@code umask} command in shell. */
  141. private static int readUmask() {
  142. try {
  143. Process p = Runtime.getRuntime().exec(
  144. new String[] { "sh", "-c", "umask" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  145. null, null);
  146. try (BufferedReader lineRead = new BufferedReader(
  147. new InputStreamReader(p.getInputStream(), Charset
  148. .defaultCharset().name()))) {
  149. if (p.waitFor() == 0) {
  150. String s = lineRead.readLine();
  151. if (s != null && s.matches("0?\\d{3}")) { //$NON-NLS-1$
  152. return Integer.parseInt(s, 8);
  153. }
  154. }
  155. return DEFAULT_UMASK;
  156. }
  157. } catch (Exception e) {
  158. return DEFAULT_UMASK;
  159. }
  160. }
  161. @Override
  162. protected File discoverGitExe() {
  163. String path = SystemReader.getInstance().getenv("PATH"); //$NON-NLS-1$
  164. File gitExe = searchPath(path, "git"); //$NON-NLS-1$
  165. if (gitExe == null) {
  166. if (SystemReader.getInstance().isMacOS()) {
  167. if (searchPath(path, "bash") != null) { //$NON-NLS-1$
  168. // On MacOSX, PATH is shorter when Eclipse is launched from the
  169. // Finder than from a terminal. Therefore try to launch bash as a
  170. // login shell and search using that.
  171. String w;
  172. try {
  173. w = readPipe(userHome(),
  174. new String[]{"bash", "--login", "-c", "which git"}, // //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  175. Charset.defaultCharset().name());
  176. } catch (CommandFailedException e) {
  177. LOG.warn(e.getMessage());
  178. return null;
  179. }
  180. if (!StringUtils.isEmptyOrNull(w)) {
  181. gitExe = new File(w);
  182. }
  183. }
  184. }
  185. }
  186. return gitExe;
  187. }
  188. @Override
  189. public boolean isCaseSensitive() {
  190. return !SystemReader.getInstance().isMacOS();
  191. }
  192. @Override
  193. public boolean supportsExecute() {
  194. return true;
  195. }
  196. @Override
  197. public boolean canExecute(File f) {
  198. return FileUtils.canExecute(f);
  199. }
  200. @Override
  201. public boolean setExecute(File f, boolean canExecute) {
  202. if (!isFile(f))
  203. return false;
  204. if (!canExecute)
  205. return f.setExecutable(false);
  206. try {
  207. Path path = f.toPath();
  208. Set<PosixFilePermission> pset = Files.getPosixFilePermissions(path);
  209. // owner (user) is always allowed to execute.
  210. pset.add(PosixFilePermission.OWNER_EXECUTE);
  211. int mask = umask();
  212. apply(pset, mask, PosixFilePermission.GROUP_EXECUTE, 1 << 3);
  213. apply(pset, mask, PosixFilePermission.OTHERS_EXECUTE, 1);
  214. Files.setPosixFilePermissions(path, pset);
  215. return true;
  216. } catch (IOException e) {
  217. // The interface doesn't allow to throw IOException
  218. final boolean debug = Boolean.parseBoolean(SystemReader
  219. .getInstance().getProperty("jgit.fs.debug")); //$NON-NLS-1$
  220. if (debug)
  221. System.err.println(e);
  222. return false;
  223. }
  224. }
  225. private static void apply(Set<PosixFilePermission> set,
  226. int umask, PosixFilePermission perm, int test) {
  227. if ((umask & test) == 0) {
  228. // If bit is clear in umask, permission is allowed.
  229. set.add(perm);
  230. } else {
  231. // If bit is set in umask, permission is denied.
  232. set.remove(perm);
  233. }
  234. }
  235. @Override
  236. public ProcessBuilder runInShell(String cmd, String[] args) {
  237. List<String> argv = new ArrayList<String>(4 + args.length);
  238. argv.add("sh"); //$NON-NLS-1$
  239. argv.add("-c"); //$NON-NLS-1$
  240. argv.add(cmd + " \"$@\""); //$NON-NLS-1$
  241. argv.add(cmd);
  242. argv.addAll(Arrays.asList(args));
  243. ProcessBuilder proc = new ProcessBuilder();
  244. proc.command(argv);
  245. return proc;
  246. }
  247. /**
  248. * @since 4.0
  249. */
  250. @Override
  251. public ProcessResult runHookIfPresent(Repository repository, String hookName,
  252. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  253. String stdinArgs) throws JGitInternalException {
  254. return internalRunHookIfPresent(repository, hookName, args, outRedirect,
  255. errRedirect, stdinArgs);
  256. }
  257. @Override
  258. public boolean retryFailedLockFileCommit() {
  259. return false;
  260. }
  261. @Override
  262. public boolean supportsSymlinks() {
  263. return true;
  264. }
  265. @Override
  266. public void setHidden(File path, boolean hidden) throws IOException {
  267. // no action on POSIX
  268. }
  269. /**
  270. * @since 3.3
  271. */
  272. @Override
  273. public Attributes getAttributes(File path) {
  274. return FileUtils.getFileAttributesPosix(this, path);
  275. }
  276. /**
  277. * @since 3.3
  278. */
  279. @Override
  280. public File normalize(File file) {
  281. return FileUtils.normalize(file);
  282. }
  283. /**
  284. * @since 3.3
  285. */
  286. @Override
  287. public String normalize(String name) {
  288. return FileUtils.normalize(name);
  289. }
  290. /**
  291. * @since 3.7
  292. */
  293. @Override
  294. public File findHook(Repository repository, String hookName) {
  295. final File gitdir = repository.getDirectory();
  296. if (gitdir == null) {
  297. return null;
  298. }
  299. final Path hookPath = gitdir.toPath().resolve(Constants.HOOKS)
  300. .resolve(hookName);
  301. if (Files.isExecutable(hookPath))
  302. return hookPath.toFile();
  303. return null;
  304. }
  305. @Override
  306. public boolean supportsAtomicCreateNewFile() {
  307. if (supportsAtomicCreateNewFile == null) {
  308. determineAtomicFileCreationSupport();
  309. }
  310. return supportsAtomicCreateNewFile.booleanValue();
  311. }
  312. @SuppressWarnings("boxing")
  313. /**
  314. * An implementation of the File#createNewFile() semantics which works also
  315. * on NFS. If the config option
  316. * {@code core.supportsAtomicCreateNewFile = true} (which is the default)
  317. * then simply File#createNewFile() is called.
  318. *
  319. * But if {@code core.supportsAtomicCreateNewFile = false} then after
  320. * successful creation of the lock file a hardlink to that lock file is
  321. * created and the attribute nlink of the lock file is checked to be 2. If
  322. * multiple clients manage to create the same lock file nlink would be
  323. * greater than 2 showing the error.
  324. *
  325. * @see https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html
  326. * @since 4.5
  327. */
  328. public boolean createNewFile(File lock) throws IOException {
  329. if (!lock.createNewFile()) {
  330. return false;
  331. }
  332. if (supportsAtomicCreateNewFile() || !supportsUnixNLink) {
  333. return true;
  334. }
  335. Path lockPath = lock.toPath();
  336. Path link = Files.createLink(Paths.get(lock.getAbsolutePath() + ".lnk"), //$NON-NLS-1$
  337. lockPath);
  338. try {
  339. Integer nlink = (Integer) (Files.getAttribute(lockPath,
  340. "unix:nlink")); //$NON-NLS-1$
  341. if (nlink != 2) {
  342. LOG.warn("nlink of link to lock file {0} was not 2 but {1}", //$NON-NLS-1$
  343. lock.getPath(), nlink);
  344. return false;
  345. }
  346. return true;
  347. } catch (UnsupportedOperationException | IllegalArgumentException e) {
  348. supportsUnixNLink = false;
  349. return true;
  350. } finally {
  351. Files.delete(link);
  352. }
  353. }
  354. }