8066915: (fs) Files.newByteChannel opens directories for cases where subsequent reads may fail
authoralanb
Wed, 10 Dec 2014 15:01:26 +0000
changeset 27952 38cbc8b0395b
parent 27951 6e1836efc0cf
child 27953 03e0e3891572
8066915: (fs) Files.newByteChannel opens directories for cases where subsequent reads may fail Reviewed-by: chegar
jdk/src/java.base/unix/classes/sun/nio/fs/UnixChannelFactory.java
jdk/test/java/nio/file/Files/SBC.java
--- a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixChannelFactory.java	Tue Dec 09 14:02:53 2014 -0800
+++ b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixChannelFactory.java	Wed Dec 10 15:01:26 2014 +0000
@@ -270,6 +270,22 @@
             throw x;
         }
 
+        // fail if the file is a directory
+        if (flags.read) {
+            UnixException exc = null;
+            try {
+                if (UnixFileAttributes.get(fd).isDirectory()) {
+                    exc = new UnixException(EISDIR);
+                }
+            } catch (UnixException x) {
+                exc = x;
+            }
+            if (exc != null) {
+                close(fd);
+                throw exc;
+            }
+        }
+
         // unlink file immediately if delete on close. The spec is clear that
         // an implementation cannot guarantee to unlink the correct file when
         // replaced by an attacker after it is opened.
--- a/jdk/test/java/nio/file/Files/SBC.java	Tue Dec 09 14:02:53 2014 -0800
+++ b/jdk/test/java/nio/file/Files/SBC.java	Wed Dec 10 15:01:26 2014 +0000
@@ -22,7 +22,7 @@
  */
 
 /* @test
- * @bug 4313887
+ * @bug 4313887 8066915
  * @summary Unit test for java.nio.file.Files.newByteChannel
  * @library ..
  */
@@ -59,6 +59,7 @@
                 dosSharingOptionTests(dir);
 
             // misc. tests
+            directoryOpenTests(dir);
             badCombinations(dir);
             unsupportedOptions(dir);
             nullTests(dir);
@@ -278,6 +279,21 @@
         }
     }
 
+    // test opening a directory for read or write
+    static void directoryOpenTests(Path dir) throws Exception {
+        try (SeekableByteChannel sbc = Files.newByteChannel(dir, READ)) {
+            throw new RuntimeException("Opened directory for read");
+        } catch (IOException expected) { }
+
+        try (SeekableByteChannel sbc = Files.newByteChannel(dir, WRITE)) {
+            throw new RuntimeException("Opened directory for write");
+        } catch (IOException expected) { }
+
+        try (SeekableByteChannel sbc = Files.newByteChannel(dir, APPEND)) {
+            throw new RuntimeException("Opened directory for append ");
+        } catch (IOException expected) { }
+    }
+
     // Windows specific options for the use by applications that really want
     // to use legacy DOS sharing options
     static void dosSharingOptionTests(Path dir) throws Exception {