Package ghidra.formats.gfilesystem

# Class FSUtilities

java.lang.Object
ghidra.formats.gfilesystem.FSUtilities

public class FSUtilities extends Object

- ## Field Summary

  Fields
  Modifier and Type
  Field
  Description
  `static final Comparator<GFile>`
  `GFILE_NAME_TYPE_COMPARATOR`
  Sorts GFiles by type (directories segregated from files) and then by name, case-insensitive.
  `static final String`
  `SEPARATOR`
  `static final String`
  `SEPARATOR_CHARS`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `FSUtilities()`

- ## Method Summary

  Modifier and Type
  Method
  Description
  `static String`
  `appendPath(String... paths)`
  Concats path strings together, taking care to ensure that there is a correct path separator character between each part.
  `static long`
  `copyByteProviderToFile(ByteProvider provider, File destFile, TaskMonitor monitor)`
  Copy the contents of a `ByteProvider` to a file.
  `static void`
  `displayException(Object originator, Component parent, String title, String message, Throwable throwable)`
  Displays a filesystem related `exception` in the most user-friendly manner possible, even if we have to do some hacky things with helping the user with crypto problems.
  `static String`
  `escapeDecode(String s)`
  Returns a decoded version of the input stream where "%nn" escape sequences are replaced with their actual characters, using UTF-8 decoding rules.
  `static String`
  `escapeEncode(String s)`
  Returns a copy of the input string with FSRL problematic[1] characters escaped as "%nn" sequences, where nn are hexdigits specifying the numeric ascii value of that character.
  `static String`
  `formatFSTimestamp(Date d)`
  Common / unified date formatting for all file system information strings.
  `static String`
  `formatSize(Long length)`
  Common / unified size formatting for all file system information strings.
  `static String`
  `getExtension(String path, int extLevel)`
  Returns the "extension" of the filename part of the path string.
  `static String`
  `getFileMD5(File f, TaskMonitor monitor)`
  Calculate the MD5 of a file.
  `static String`
  `getFilesystemDescriptionFromClass(Class<?> clazz)`
  Returns the description value of the `FileSystemInfo` annotation attached to the specified class.
  `static int`
  `getFilesystemPriorityFromClass(Class<?> clazz)`
  Returns the priority value of the `FileSystemInfo` annotation attached to the specified class.
  `static String`
  `getFilesystemTypeFromClass(Class<?> clazz)`
  Returns the type value of the `FileSystemInfo` annotation attached to the specified class.
  `static FileType`
  `getFileType(File f)`
  `static List<String>`
  `getLines(ByteProvider byteProvider)`
  Returns the text lines in the specified ByteProvider.
  `static String`
  `getMD5(ByteProvider provider, TaskMonitor monitor)`
  Calculate the MD5 of a file.
  `static String`
  `getMD5(InputStream is, String name, long expectedLength, TaskMonitor monitor)`
  Calculate the hash of an `InputStream`.
  `static String`
  `getSafeFilename(String untrustedFilename)`
  Best-effort of sanitizing an untrusted string that will be used to create a file on the user's local filesystem.
  `static String`
  `infoMapToString(Map<String,String> info)`
  Converts a string-to-string mapping into a "key: value\n" multi-line string.
  `static boolean`
  `isSameFS(List<FSRL> fsrls)`
  Returns true if all the `FSRL`s in the specified list are from the filesystem.
  `static boolean`
  `isSymlink(File f)`
  `static List<GFile>`
  `listFileSystem(GFileSystem fs, GFile dir, List<GFile> result, TaskMonitor taskMonitor)`
  Deprecated, for removal: This API element is subject to removal in a future version.
  Use `GFileSystem.files(GFile)` instead
  `static String`
  `mirroredProjectPath(String path)`
  Converts the given path to a valid mirrored project path.
  `static String`
  `normalizeNativePath(String path)`
  Returns a copy of the string path that has been fixed to have correct slashes and a correct leading root slash '/'.
  `static String`
  `readSymlink(File f)`
  Returns the destination of a symlink, or null if not a symlink or other error
  `static String[]`
  `splitPath(String path)`
  Splits the given path into its individual directory and filename components.
  `static long`
  `streamCopy(InputStream is, OutputStream os, TaskMonitor monitor)`
  Copy a stream while updating a TaskMonitor.
  `static void`
  `uncheckedClose(AutoCloseable c, String msg)`
  Helper method to invoke close() on a AutoCloseable without having to catch an IOException.

  ### Methods inherited from class java.lang.Object

  `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Field Details

  - ### SEPARATOR_CHARS

    public static final String SEPARATOR_CHARS
    See Also:
      - Constant Field Values

  - ### SEPARATOR

    public static final String SEPARATOR
    See Also:
      - Constant Field Values

  - ### GFILE_NAME_TYPE_COMPARATOR

    public static final Comparator<GFile> GFILE_NAME_TYPE_COMPARATOR
    Sorts GFiles by type (directories segregated from files) and then by name, case-insensitive.

- ## Constructor Details

  - ### FSUtilities

    public FSUtilities()

- ## Method Details

  - ### infoMapToString

    public static String infoMapToString(Map<String,String> info)
    Converts a string-to-string mapping into a "key: value\n" multi-line string.
    Parameters:
      `info` - map of string key to string value.
    Returns:
      Multi-line string "key: value" string.

  - ### getSafeFilename

    public static String getSafeFilename(String untrustedFilename)
    Best-effort of sanitizing an untrusted string that will be used to create a file on the user's local filesystem.
    Parameters:
      `untrustedFilename` - filename string with possibly bad / hostile characters or sequences.
    Returns:
      sanitized filename

  - ### escapeEncode

    public static String escapeEncode(String s)
    Returns a copy of the input string with FSRL problematic[1] characters escaped as "%nn" sequences, where nn are hexdigits specifying the numeric ascii value of that character.

    Characters that need more than a byte to encode will result in multiple "%nn" values that encode the necessary UTF8 codepoints.

    [1] - non-ascii / unprintable / FSRL portion separation characters.

    Parameters:
      `s` - string, or null.
    Returns:
      string with problematic characters escaped as "%nn" sequences, or null if parameter was null.

  - ### escapeDecode

    public static String escapeDecode(String s) throws MalformedURLException
    Returns a decoded version of the input stream where "%nn" escape sequences are replaced with their actual characters, using UTF-8 decoding rules.
    Parameters:
      `s` - string with escape sequences in the form "%nn", or null.
    Returns:
      string with all escape sequences replaced with native characters, or null if original parameter was null.
    Throws:
      `MalformedURLException` - if bad escape sequence format.

  - ### listFileSystem

    @Deprecated(forRemoval=true, since="11.4") public static List<GFile> listFileSystem(GFileSystem fs, GFile dir, List<GFile> result, TaskMonitor taskMonitor) throws IOException, CancelledException
    Deprecated, for removal: This API element is subject to removal in a future version.
    Use `GFileSystem.files(GFile)` instead
    Returns a list of all files in a GFileSystem.
    Parameters:
      `fs` - `GFileSystem` to recursively query for all files.
      `dir` - the `GFile` directory to recurse into
      `result` - `List` of GFiles where the results are accumulated into, or null to allocate a new List, returned as the result.
      `taskMonitor` - `TaskMonitor` that will be checked for cancel.
    Returns:
      `List` of accumulated `result`s
    Throws:
      `IOException` - if io error during listing of directories
      `CancelledException` - if user cancels

  - ### getFilesystemTypeFromClass

    public static String getFilesystemTypeFromClass(Class<?> clazz)
    Returns the type value of the `FileSystemInfo` annotation attached to the specified class.
    Parameters:
      `clazz` - Class to query.
    Returns:
      File system type string.

  - ### getFilesystemDescriptionFromClass

    public static String getFilesystemDescriptionFromClass(Class<?> clazz)
    Returns the description value of the `FileSystemInfo` annotation attached to the specified class.
    Parameters:
      `clazz` - Class to query.
    Returns:
      File system description string.

  - ### getFilesystemPriorityFromClass

    public static int getFilesystemPriorityFromClass(Class<?> clazz)
    Returns the priority value of the `FileSystemInfo` annotation attached to the specified class.
    Parameters:
      `clazz` - Class to query.
    Returns:
      File system priority integer.

  - ### isSameFS

    public static boolean isSameFS(List<FSRL> fsrls)
    Returns true if all the `FSRL`s in the specified list are from the filesystem.
    Parameters:
      `fsrls` - `List` of `FSRL`s.
    Returns:
      boolean true if all are from same filesystem.

  - ### displayException

    public static void displayException(Object originator, Component parent, String title, String message, Throwable throwable)
    Displays a filesystem related `exception` in the most user-friendly manner possible, even if we have to do some hacky things with helping the user with crypto problems.
    Parameters:
      `originator` - a Logger instance, "this", or YourClass.class
      `parent` - a parent component used to center the dialog (or null if you don't have one)
      `title` - the title of the pop-up dialog (main subject of message)
      `message` - the details of the message
      `throwable` - the Throwable that describes the cause of the error

  - ### copyByteProviderToFile

    public static long copyByteProviderToFile(ByteProvider provider, File destFile, TaskMonitor monitor) throws IOException, CancelledException
    Copy the contents of a `ByteProvider` to a file.
    Parameters:
      `provider` - `ByteProvider` source of bytes
      `destFile` - `File` destination file
      `monitor` - `TaskMonitor` to update
    Returns:
      number of bytes copied
    Throws:
      `IOException` - if error
      `CancelledException` - if cancelled

  - ### streamCopy

    public static long streamCopy(InputStream is, OutputStream os, TaskMonitor monitor) throws IOException, CancelledException
    Copy a stream while updating a TaskMonitor.
    Parameters:
      `is` - `InputStream` source of bytes
      `os` - `OutputStream` destination of bytes
      `monitor` - `TaskMonitor` to update
    Returns:
      number of bytes copied
    Throws:
      `IOException` - if error
      `CancelledException` - if cancelled

  - ### getLines

    public static List<String> getLines(ByteProvider byteProvider) throws IOException
    Returns the text lines in the specified ByteProvider.

    See `FileUtilities.getLines(InputStream)`

    Parameters:
      `byteProvider` - `ByteProvider` to read
    Returns:
      list of text lines
    Throws:
      `IOException` - if error

  - ### getFileMD5

    public static String getFileMD5(File f, TaskMonitor monitor) throws IOException, CancelledException
    Calculate the MD5 of a file.
    Parameters:
      `f` - `File` to read.
      `monitor` - `TaskMonitor` to watch for cancel
    Returns:
      md5 as a hex encoded string, never null.
    Throws:
      `IOException` - if error
      `CancelledException` - if cancelled

  - ### getMD5

    public static String getMD5(ByteProvider provider, TaskMonitor monitor) throws IOException, CancelledException
    Calculate the MD5 of a file.
    Parameters:
      `provider` - `ByteProvider`
      `monitor` - `TaskMonitor` to watch for cancel
    Returns:
      md5 as a hex encoded string, never null.
    Throws:
      `IOException` - if error
      `CancelledException` - if cancelled

  - ### getMD5

    public static String getMD5(InputStream is, String name, long expectedLength, TaskMonitor monitor) throws IOException, CancelledException
    Calculate the hash of an `InputStream`.
    Parameters:
      `is` - `InputStream`
      `name` - of the inputstream
      `expectedLength` - the length of the inputstream
      `monitor` - `TaskMonitor` to update
    Returns:
      md5 as a hex encoded string, never null
    Throws:
      `IOException` - if error
      `CancelledException` - if cancelled

  - ### appendPath

    public static String appendPath(String... paths)
    Concats path strings together, taking care to ensure that there is a correct path separator character between each part.

    Handles forward or back slashes as path separator characters in the input, but only adds forward slashes when separating the path strings that need a separator.

    Parameters:
      `paths` - vararg list of path strings, empty or null elements are ok and are skipped.
    Returns:
      null if all params null, "" empty string if all are empty, or "path_element[1]/path_element[2]/.../path_element[N]" otherwise.

  - ### getExtension

    public static String getExtension(String path, int extLevel)
    Returns the "extension" of the filename part of the path string.

    Ie. everything after the nth last '.' char in the filename, including that '.' character.

    Using: "path/filename.ext1.ext2"

    Gives:

    - extLevel 1: ".ext2"
    - extLevel 2: ".ext1.ext2"
    - extLevel 3: `null`
    Parameters:
      `path` - path/filename.ext string
      `extLevel` - number of ext levels; must be greater than 0
    Returns:
      ".ext1" for "path/filename.notext.ext1" level 1, ".ext1.ext2" for "path/filename.ext1.ext2" level 2, etc. or null if there was no dot character
    Throws:
      `IllegalArgumentException` - if the given level is less than 1

  - ### normalizeNativePath

    public static String normalizeNativePath(String path)
    Returns a copy of the string path that has been fixed to have correct slashes and a correct leading root slash '/'.
    Parameters:
      `path` - String forward or backslash path
    Returns:
      String path with all forward slashes and a leading root slash.

  - ### formatFSTimestamp

    public static String formatFSTimestamp(Date d)
    Common / unified date formatting for all file system information strings.
    Parameters:
      `d` - `Date` to format, or null
    Returns:
      formatted date string, or "NA" if date was null

  - ### formatSize

    public static String formatSize(Long length)
    Common / unified size formatting for all file system information strings.
    Parameters:
      `length` - `Long` length, null ok
    Returns:
      pretty'ish length format string, or "NA" if length was null

  - ### uncheckedClose

    public static void uncheckedClose(AutoCloseable c, String msg)
    Helper method to invoke close() on a AutoCloseable without having to catch an IOException.
    Parameters:
      `c` - `AutoCloseable` to close
      `msg` - optional msg to log if exception is thrown, null is okay

  - ### isSymlink

    public static boolean isSymlink(File f)

  - ### readSymlink

    public static String readSymlink(File f)
    Returns the destination of a symlink, or null if not a symlink or other error
    Parameters:
      `f` - `File` that is a symlink
    Returns:
      destination path string of the symlink, or null if not symlink

  - ### getFileType

    public static FileType getFileType(File f)

  - ### splitPath

    public static String[] splitPath(String path)
    Splits the given path into its individual directory and filename components. For example, `"/dir/dir/dir/file"` becomes `["", "dir", "dir", "dir", "file"]`.
    Parameters:
      `path` - The path to split
    Returns:
      The split path

  - ### mirroredProjectPath

    public static String mirroredProjectPath(String path)
    Converts the given path to a valid mirrored project path. Care must be taken to minimize project path collisions, allowing them only when completely necessary.
    Parameters:
      `path` - The path to convert
    Returns:
      The mirrored project path