btrfs-progs: add stat check in open_ctree_fs_info
authorAustin S. Hemmelgarn <ahferroin7@gmail.com>
Fri, 18 Mar 2016 14:03:42 +0000 (10:03 -0400)
committerDavid Sterba <dsterba@suse.com>
Fri, 18 Mar 2016 15:38:14 +0000 (16:38 +0100)
Currently, open_ctree_fs_info will open whatever path you pass it and try
to interpret it as a BTRFS filesystem.  While this is not nessecarily
dangerous (except possibly if done on a character device), it does
result in some rather cryptic and non-sensical error messages when
trying to run certain commands in ways they weren't intended to be run.
Add a check using stat(2) to verify that the path we've been passed is
in fact a regular file or a block device, or a symlink pointing to a
regular file or block device.

This causes the following commands to provide a helpful error message
when run on a FIFO, directory, character device, or socket:
    * btrfs check
    * btrfs restore
    * btrfs-image
    * btrfs-find-root
    * btrfs inspect-internal dump-tree

stat(2) is used instead of lstat(2), as stat(2) follows symlinks just
like open(2) does, which means we check the same inode that open(2)
opens, and thus don't need special handling for symlinks.

Signed-off-by: Austin S. Hemmelgarn <ahferroin7@gmail.com>
Signed-off-by: David Sterba <dsterba@suse.com>
disk-io.c

index 88015b7..6b47977 100644 (file)
--- a/disk-io.c
+++ b/disk-io.c
@@ -1325,6 +1325,13 @@ struct btrfs_fs_info *open_ctree_fs_info(const char *filename,
        int fp;
        struct btrfs_fs_info *info;
        int oflags = O_CREAT | O_RDWR;
+       struct stat st;
+
+       stat(filename, &st);
+       if (!(((st.st_mode & S_IFMT) == S_IFREG) || ((st.st_mode & S_IFMT) == S_IFBLK))) {
+               fprintf (stderr, "%s is not a regular file or block device\n", filename);
+               return NULL;
+       }
 
        if (!(flags & OPEN_CTREE_WRITES))
                oflags = O_RDONLY;