]> git.hungrycats.org Git - btrfs-progs/commitdiff
btrfs-progs: add path helper for readlink
authorDavid Sterba <dsterba@suse.com>
Tue, 9 Jun 2026 19:24:09 +0000 (21:24 +0200)
committerDavid Sterba <dsterba@suse.com>
Tue, 14 Jul 2026 21:14:26 +0000 (23:14 +0200)
Readlink does not add the terminating null byte and can silently
truncate the buffer if not provided enough space. Add a helper to
abstract the edge cases. The destination argument must be path, i.e.
at least PATH_MAX bytes.

Signed-off-by: David Sterba <dsterba@suse.com>
common/path-utils.c
common/path-utils.h

index 4c517db661dc5f501a405b1896e7e0065c3f37d3..3ce312348de1764821cc13477709289608d2eecf 100644 (file)
@@ -482,3 +482,29 @@ char *path_dirname(char *path)
 {
        return dirname(path);
 }
+
+/*
+ * Read contents of symlink @src and store it to @dest (assuming PATH_MAX buffer).
+ * Makes sure it's a null terminated string.
+ *
+ * Return number of bytes written to @dest, or negative error.
+ */
+int path_readlink(char *dest, const char *src)
+{
+       int ret;
+
+       /* Readlink does not add the final null byte and can fill the whole buffer. */
+       ret = readlink(src, dest, PATH_MAX);
+       if (ret < 0)
+               return -errno;
+       /*
+        * Extend the meaning of EINVAL which is either negative buffer size or
+        * the named file is not a symbolic link. Zero-sized symlink cannot exist.
+        */
+       if (ret == 0)
+               return -EINVAL;
+       if (ret >= PATH_MAX)
+               return -ENAMETOOLONG;
+       dest[ret] = 0;
+       return ret;
+}
index 9783c77238a09c36594c7ef32ab3ec139ce86724..7719d0fd5bcdd156163cf26f2b39fcaaa4477674 100644 (file)
@@ -36,5 +36,6 @@ int path_is_reg_or_block_device(const char *filename);
 int path_is_in_dir(const char *parent, const char *path);
 char *path_basename(char *path);
 char *path_dirname(char *path);
+int path_readlink(char *dest, const char *src);
 
 #endif