Path: blob/master/src/java.base/share/classes/java/nio/file/TempFileHelper.java
41159 views
/*1* Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio.file;2627import java.util.Set;28import java.util.EnumSet;29import java.security.SecureRandom;30import java.io.IOException;31import java.nio.file.attribute.FileAttribute;32import java.nio.file.attribute.PosixFilePermission;33import java.nio.file.attribute.PosixFilePermissions;34import static java.nio.file.attribute.PosixFilePermission.*;35import jdk.internal.util.StaticProperty;3637/**38* Helper class to support creation of temporary files and directories with39* initial attributes.40*/4142class TempFileHelper {43private TempFileHelper() { }4445// temporary directory location46private static final Path tmpdir = Path.of(StaticProperty.javaIoTmpDir());4748private static final boolean isPosix =49FileSystems.getDefault().supportedFileAttributeViews().contains("posix");5051// file name generation, same as java.io.File for now52private static final SecureRandom random = new SecureRandom();53private static Path generatePath(String prefix, String suffix, Path dir) {54long n = random.nextLong();55String s = prefix + Long.toUnsignedString(n) + suffix;56Path name = dir.getFileSystem().getPath(s);57// the generated name should be a simple file name58if (name.getParent() != null)59throw new IllegalArgumentException("Invalid prefix or suffix");60return dir.resolve(name);61}6263// default file and directory permissions (lazily initialized)64private static class PosixPermissions {65static final FileAttribute<Set<PosixFilePermission>> filePermissions =66PosixFilePermissions.asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE));67static final FileAttribute<Set<PosixFilePermission>> dirPermissions =68PosixFilePermissions.asFileAttribute(EnumSet69.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE));70}7172/**73* Creates a file or directory in the given directory (or in the74* temporary directory if dir is {@code null}).75*/76private static Path create(Path dir,77String prefix,78String suffix,79boolean createDirectory,80FileAttribute<?>[] attrs)81throws IOException82{83if (prefix == null)84prefix = "";85if (suffix == null)86suffix = (createDirectory) ? "" : ".tmp";87if (dir == null)88dir = tmpdir;8990// in POSIX environments use default file and directory permissions91// if initial permissions not given by caller.92if (isPosix && (dir.getFileSystem() == FileSystems.getDefault())) {93if (attrs.length == 0) {94// no attributes so use default permissions95attrs = new FileAttribute<?>[1];96attrs[0] = (createDirectory) ? PosixPermissions.dirPermissions :97PosixPermissions.filePermissions;98} else {99// check if posix permissions given; if not use default100boolean hasPermissions = false;101for (int i=0; i<attrs.length; i++) {102if (attrs[i].name().equals("posix:permissions")) {103hasPermissions = true;104break;105}106}107if (!hasPermissions) {108FileAttribute<?>[] copy = new FileAttribute<?>[attrs.length+1];109System.arraycopy(attrs, 0, copy, 0, attrs.length);110attrs = copy;111attrs[attrs.length-1] = (createDirectory) ?112PosixPermissions.dirPermissions :113PosixPermissions.filePermissions;114}115}116}117118// loop generating random names until file or directory can be created119@SuppressWarnings("removal")120SecurityManager sm = System.getSecurityManager();121for (;;) {122Path f;123try {124f = generatePath(prefix, suffix, dir);125} catch (InvalidPathException e) {126// don't reveal temporary directory location127if (sm != null)128throw new IllegalArgumentException("Invalid prefix or suffix");129throw e;130}131try {132if (createDirectory) {133return Files.createDirectory(f, attrs);134} else {135return Files.createFile(f, attrs);136}137} catch (SecurityException e) {138// don't reveal temporary directory location139if (dir == tmpdir && sm != null)140throw new SecurityException("Unable to create temporary file or directory");141throw e;142} catch (FileAlreadyExistsException e) {143// ignore144}145}146}147148/**149* Creates a temporary file in the given directory, or in the150* temporary directory if dir is {@code null}.151*/152static Path createTempFile(Path dir,153String prefix,154String suffix,155FileAttribute<?>[] attrs)156throws IOException157{158return create(dir, prefix, suffix, false, attrs);159}160161/**162* Creates a temporary directory in the given directory, or in the163* temporary directory if dir is {@code null}.164*/165static Path createTempDirectory(Path dir,166String prefix,167FileAttribute<?>[] attrs)168throws IOException169{170return create(dir, prefix, null, true, attrs);171}172}173174175