<fim-prefix>FileWithinDirectory(loadPath, file)
                        ? loadFile(file)
                        : null;
            }
            else {
                final File f = new File(loadPath, file.getPath());
                return f.isFile()
                        ? loadFile(new File(loadPath, file.getPath()))
                        : null;
            }
        }
        catch (Exception ex) {
            throw new VncException(
                        String.format("Failed to load file '%s'", file.getPath()),
                        ex);
        }
    }

    private static File canonical(final File file) {
        try {
            return file.getCanonicalFile();
        }
        catch(IOException ex) {
            throw new VncException(
                    String.format(
                            "The file '%s' can not be converted to a canonical path!",
                            file.getPath()),
                    ex);
        }
    }

    private ByteBuffer loadFile(final File file) {
        try {
            return ByteBuffer.wrap(Files.readAllBytes(file.toPath()));
        }
        catch(IOException ex) {
            return null;
        }
    }

    private boolean isFileWithinDirectory(
            final File dir,
            final File file
    ) throws IOException {
        final File dir_ = dir.getAbsoluteFile();
        if (dir_.isDirectory()) {
            final File fl = new File(dir_, file.getPath());
            if (fl.isFile()) {
                // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
                // if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) {
                // FIXED: 
<fim-middle>                if (fl.getCanonicalFile().toPath().startsWith(dir_.getCanonicalFile().toPath())) {
                    // Prevent accessing files outside the load-path.
                    // E.g.: ../<fix-suffix>../coffee
                    return true;
                }
            }
        }

        return false;
    }

    private Charset getCharset(final String encoding) {
        return encoding == null || encoding.isEmpty()
                ? Charset.defaultCharset()
                : Charset.forName(encoding);
    }


    // a list of existing canonical paths
    private final List<File> paths = new ArrayList<>();
    private final boolean unlimitedAccess;
}
<|endoftext|>