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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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 static org.eclipse.jgit.lib.ConfigConstants.CONFIG_CORE_SECTION;
  45. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_SUPPORTSATOMICFILECREATION;
  46. import java.io.BufferedReader;
  47. import java.io.File;
  48. import java.io.IOException;
  49. import java.io.InputStreamReader;
  50. import java.io.PrintStream;
  51. import java.nio.charset.Charset;
  52. import java.nio.file.FileAlreadyExistsException;
  53. import java.nio.file.Files;
  54. import java.nio.file.InvalidPathException;
  55. import java.nio.file.Path;
  56. import java.nio.file.Paths;
  57. import java.nio.file.attribute.PosixFilePermission;
  58. import java.text.MessageFormat;
  59. import java.util.ArrayList;
  60. import java.util.Arrays;
  61. import java.util.List;
  62. import java.util.Optional;
  63. import java.util.Set;
  64. import java.util.UUID;
  65. import org.eclipse.jgit.annotations.Nullable;
  66. import org.eclipse.jgit.api.errors.JGitInternalException;
  67. import org.eclipse.jgit.errors.CommandFailedException;
  68. import org.eclipse.jgit.errors.ConfigInvalidException;
  69. import org.eclipse.jgit.internal.JGitText;
  70. import org.eclipse.jgit.lib.Constants;
  71. import org.eclipse.jgit.lib.Repository;
  72. import org.eclipse.jgit.lib.StoredConfig;
  73. import org.slf4j.Logger;
  74. import org.slf4j.LoggerFactory;
  75. /**
  76. * Base FS for POSIX based systems
  77. *
  78. * @since 3.0
  79. */
  80. public class FS_POSIX extends FS {
  81. private final static Logger LOG = LoggerFactory.getLogger(FS_POSIX.class);
  82. private static final int DEFAULT_UMASK = 0022;
  83. private volatile int umask = -1;
  84. private volatile boolean supportsUnixNLink = true;
  85. private volatile AtomicFileCreation supportsAtomicFileCreation = AtomicFileCreation.UNDEFINED;
  86. private enum AtomicFileCreation {
  87. SUPPORTED, NOT_SUPPORTED, UNDEFINED
  88. }
  89. /**
  90. * Default constructor.
  91. */
  92. protected FS_POSIX() {
  93. }
  94. /**
  95. * Constructor
  96. *
  97. * @param src
  98. * FS to copy some settings from
  99. */
  100. protected FS_POSIX(FS src) {
  101. super(src);
  102. if (src instanceof FS_POSIX) {
  103. umask = ((FS_POSIX) src).umask;
  104. }
  105. }
  106. /** {@inheritDoc} */
  107. @Override
  108. public FS newInstance() {
  109. return new FS_POSIX(this);
  110. }
  111. /**
  112. * Set the umask, overriding any value observed from the shell.
  113. *
  114. * @param umask
  115. * mask to apply when creating files.
  116. * @since 4.0
  117. */
  118. public void setUmask(int umask) {
  119. this.umask = umask;
  120. }
  121. private int umask() {
  122. int u = umask;
  123. if (u == -1) {
  124. u = readUmask();
  125. umask = u;
  126. }
  127. return u;
  128. }
  129. /** @return mask returned from running {@code umask} command in shell. */
  130. private static int readUmask() {
  131. try {
  132. Process p = Runtime.getRuntime().exec(
  133. new String[] { "sh", "-c", "umask" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  134. null, null);
  135. try (BufferedReader lineRead = new BufferedReader(
  136. new InputStreamReader(p.getInputStream(), Charset
  137. .defaultCharset().name()))) {
  138. if (p.waitFor() == 0) {
  139. String s = lineRead.readLine();
  140. if (s != null && s.matches("0?\\d{3}")) { //$NON-NLS-1$
  141. return Integer.parseInt(s, 8);
  142. }
  143. }
  144. return DEFAULT_UMASK;
  145. }
  146. } catch (Exception e) {
  147. return DEFAULT_UMASK;
  148. }
  149. }
  150. /** {@inheritDoc} */
  151. @Override
  152. protected File discoverGitExe() {
  153. String path = SystemReader.getInstance().getenv("PATH"); //$NON-NLS-1$
  154. File gitExe = searchPath(path, "git"); //$NON-NLS-1$
  155. if (gitExe == null) {
  156. if (SystemReader.getInstance().isMacOS()) {
  157. if (searchPath(path, "bash") != null) { //$NON-NLS-1$
  158. // On MacOSX, PATH is shorter when Eclipse is launched from the
  159. // Finder than from a terminal. Therefore try to launch bash as a
  160. // login shell and search using that.
  161. String w;
  162. try {
  163. w = readPipe(userHome(),
  164. new String[]{"bash", "--login", "-c", "which git"}, // //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  165. Charset.defaultCharset().name());
  166. } catch (CommandFailedException e) {
  167. LOG.warn(e.getMessage());
  168. return null;
  169. }
  170. if (!StringUtils.isEmptyOrNull(w)) {
  171. gitExe = new File(w);
  172. }
  173. }
  174. }
  175. }
  176. return gitExe;
  177. }
  178. /** {@inheritDoc} */
  179. @Override
  180. public boolean isCaseSensitive() {
  181. return !SystemReader.getInstance().isMacOS();
  182. }
  183. /** {@inheritDoc} */
  184. @Override
  185. public boolean supportsExecute() {
  186. return true;
  187. }
  188. /** {@inheritDoc} */
  189. @Override
  190. public boolean canExecute(File f) {
  191. return FileUtils.canExecute(f);
  192. }
  193. /** {@inheritDoc} */
  194. @Override
  195. public boolean setExecute(File f, boolean canExecute) {
  196. if (!isFile(f))
  197. return false;
  198. if (!canExecute)
  199. return f.setExecutable(false, false);
  200. try {
  201. Path path = FileUtils.toPath(f);
  202. Set<PosixFilePermission> pset = Files.getPosixFilePermissions(path);
  203. // owner (user) is always allowed to execute.
  204. pset.add(PosixFilePermission.OWNER_EXECUTE);
  205. int mask = umask();
  206. apply(pset, mask, PosixFilePermission.GROUP_EXECUTE, 1 << 3);
  207. apply(pset, mask, PosixFilePermission.OTHERS_EXECUTE, 1);
  208. Files.setPosixFilePermissions(path, pset);
  209. return true;
  210. } catch (IOException e) {
  211. // The interface doesn't allow to throw IOException
  212. final boolean debug = Boolean.parseBoolean(SystemReader
  213. .getInstance().getProperty("jgit.fs.debug")); //$NON-NLS-1$
  214. if (debug)
  215. System.err.println(e);
  216. return false;
  217. }
  218. }
  219. private static void apply(Set<PosixFilePermission> set,
  220. int umask, PosixFilePermission perm, int test) {
  221. if ((umask & test) == 0) {
  222. // If bit is clear in umask, permission is allowed.
  223. set.add(perm);
  224. } else {
  225. // If bit is set in umask, permission is denied.
  226. set.remove(perm);
  227. }
  228. }
  229. /** {@inheritDoc} */
  230. @Override
  231. public ProcessBuilder runInShell(String cmd, String[] args) {
  232. List<String> argv = new ArrayList<>(4 + args.length);
  233. argv.add("sh"); //$NON-NLS-1$
  234. argv.add("-c"); //$NON-NLS-1$
  235. argv.add(cmd + " \"$@\""); //$NON-NLS-1$
  236. argv.add(cmd);
  237. argv.addAll(Arrays.asList(args));
  238. ProcessBuilder proc = new ProcessBuilder();
  239. proc.command(argv);
  240. return proc;
  241. }
  242. /** {@inheritDoc} */
  243. @Override
  244. public ProcessResult runHookIfPresent(Repository repository, String hookName,
  245. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  246. String stdinArgs) throws JGitInternalException {
  247. return internalRunHookIfPresent(repository, hookName, args, outRedirect,
  248. errRedirect, stdinArgs);
  249. }
  250. /** {@inheritDoc} */
  251. @Override
  252. public boolean retryFailedLockFileCommit() {
  253. return false;
  254. }
  255. /** {@inheritDoc} */
  256. @Override
  257. public boolean supportsSymlinks() {
  258. return true;
  259. }
  260. /** {@inheritDoc} */
  261. @Override
  262. public void setHidden(File path, boolean hidden) throws IOException {
  263. // no action on POSIX
  264. }
  265. /** {@inheritDoc} */
  266. @Override
  267. public Attributes getAttributes(File path) {
  268. return FileUtils.getFileAttributesPosix(this, path);
  269. }
  270. /** {@inheritDoc} */
  271. @Override
  272. public File normalize(File file) {
  273. return FileUtils.normalize(file);
  274. }
  275. /** {@inheritDoc} */
  276. @Override
  277. public String normalize(String name) {
  278. return FileUtils.normalize(name);
  279. }
  280. /** {@inheritDoc} */
  281. @Override
  282. public File findHook(Repository repository, String hookName) {
  283. final File gitdir = repository.getDirectory();
  284. if (gitdir == null) {
  285. return null;
  286. }
  287. final Path hookPath = gitdir.toPath().resolve(Constants.HOOKS)
  288. .resolve(hookName);
  289. if (Files.isExecutable(hookPath))
  290. return hookPath.toFile();
  291. return null;
  292. }
  293. /** {@inheritDoc} */
  294. @Override
  295. public boolean supportsAtomicCreateNewFile() {
  296. if (supportsAtomicFileCreation == AtomicFileCreation.UNDEFINED) {
  297. try {
  298. StoredConfig config = SystemReader.getInstance().getUserConfig();
  299. String value = config.getString(CONFIG_CORE_SECTION, null,
  300. CONFIG_KEY_SUPPORTSATOMICFILECREATION);
  301. if (value != null) {
  302. supportsAtomicFileCreation = StringUtils.toBoolean(value)
  303. ? AtomicFileCreation.SUPPORTED
  304. : AtomicFileCreation.NOT_SUPPORTED;
  305. } else {
  306. supportsAtomicFileCreation = AtomicFileCreation.SUPPORTED;
  307. }
  308. } catch (IOException | ConfigInvalidException e) {
  309. LOG.warn(JGitText.get().assumeAtomicCreateNewFile, e);
  310. supportsAtomicFileCreation = AtomicFileCreation.SUPPORTED;
  311. }
  312. }
  313. return supportsAtomicFileCreation == AtomicFileCreation.SUPPORTED;
  314. }
  315. @Override
  316. @SuppressWarnings("boxing")
  317. /**
  318. * {@inheritDoc}
  319. * <p>
  320. * An implementation of the File#createNewFile() semantics which works also
  321. * on NFS. If the config option
  322. * {@code core.supportsAtomicCreateNewFile = true} (which is the default)
  323. * then simply File#createNewFile() is called.
  324. *
  325. * But if {@code core.supportsAtomicCreateNewFile = false} then after
  326. * successful creation of the lock file a hard link to that lock file is
  327. * created and the attribute nlink of the lock file is checked to be 2. If
  328. * multiple clients manage to create the same lock file nlink would be
  329. * greater than 2 showing the error.
  330. *
  331. * @see "https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html"
  332. *
  333. * @deprecated use {@link FS_POSIX#createNewFileAtomic(File)} instead
  334. * @since 4.5
  335. */
  336. @Deprecated
  337. public boolean createNewFile(File lock) throws IOException {
  338. if (!lock.createNewFile()) {
  339. return false;
  340. }
  341. if (supportsAtomicCreateNewFile() || !supportsUnixNLink) {
  342. return true;
  343. }
  344. Path lockPath = lock.toPath();
  345. Path link = null;
  346. try {
  347. link = Files.createLink(
  348. Paths.get(lock.getAbsolutePath() + ".lnk"), //$NON-NLS-1$
  349. lockPath);
  350. Integer nlink = (Integer) (Files.getAttribute(lockPath,
  351. "unix:nlink")); //$NON-NLS-1$
  352. if (nlink > 2) {
  353. LOG.warn("nlink of link to lock file {} was not 2 but {}", //$NON-NLS-1$
  354. lock.getPath(), nlink);
  355. return false;
  356. } else if (nlink < 2) {
  357. supportsUnixNLink = false;
  358. }
  359. return true;
  360. } catch (UnsupportedOperationException | IllegalArgumentException e) {
  361. supportsUnixNLink = false;
  362. return true;
  363. } finally {
  364. if (link != null) {
  365. Files.delete(link);
  366. }
  367. }
  368. }
  369. /**
  370. * {@inheritDoc}
  371. * <p>
  372. * An implementation of the File#createNewFile() semantics which can create
  373. * a unique file atomically also on NFS. If the config option
  374. * {@code core.supportsAtomicCreateNewFile = true} (which is the default)
  375. * then simply Files#createFile() is called.
  376. *
  377. * But if {@code core.supportsAtomicCreateNewFile = false} then after
  378. * successful creation of the lock file a hard link to that lock file is
  379. * created and the attribute nlink of the lock file is checked to be 2. If
  380. * multiple clients manage to create the same lock file nlink would be
  381. * greater than 2 showing the error. The hard link needs to be retained
  382. * until the corresponding file is no longer needed in order to prevent that
  383. * another process can create the same file concurrently using another NFS
  384. * client which might not yet see the file due to caching.
  385. *
  386. * @see "https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html"
  387. * @param file
  388. * the unique file to be created atomically
  389. * @return LockToken this lock token must be held until the file is no
  390. * longer needed
  391. * @throws IOException
  392. * @since 5.0
  393. */
  394. @Override
  395. public LockToken createNewFileAtomic(File file) throws IOException {
  396. Path path;
  397. try {
  398. path = file.toPath();
  399. Files.createFile(path);
  400. } catch (FileAlreadyExistsException | InvalidPathException e) {
  401. return token(false, null);
  402. }
  403. if (supportsAtomicCreateNewFile() || !supportsUnixNLink) {
  404. return token(true, null);
  405. }
  406. Path link = null;
  407. try {
  408. link = Files.createLink(Paths.get(uniqueLinkPath(file)), path);
  409. Integer nlink = (Integer) (Files.getAttribute(path,
  410. "unix:nlink")); //$NON-NLS-1$
  411. if (nlink.intValue() > 2) {
  412. LOG.warn(MessageFormat.format(
  413. JGitText.get().failedAtomicFileCreation, path, nlink));
  414. return token(false, link);
  415. } else if (nlink.intValue() < 2) {
  416. supportsUnixNLink = false;
  417. }
  418. return token(true, link);
  419. } catch (UnsupportedOperationException | IllegalArgumentException e) {
  420. supportsUnixNLink = false;
  421. return token(true, link);
  422. }
  423. }
  424. private static LockToken token(boolean created, @Nullable Path p) {
  425. return ((p != null) && Files.exists(p))
  426. ? new LockToken(created, Optional.of(p))
  427. : new LockToken(created, Optional.empty());
  428. }
  429. private static String uniqueLinkPath(File file) {
  430. UUID id = UUID.randomUUID();
  431. return file.getAbsolutePath() + "." //$NON-NLS-1$
  432. + Long.toHexString(id.getMostSignificantBits())
  433. + Long.toHexString(id.getLeastSignificantBits());
  434. }
  435. }