]> git.ipfire.org Git - thirdparty/freeradius-server.git/commitdiff
Add utility functions to trim paths
authorArran Cudbard-Bell <a.cudbardb@freeradius.org>
Mon, 14 Jul 2025 00:16:11 +0000 (18:16 -0600)
committerArran Cudbard-Bell <a.cudbardb@freeradius.org>
Mon, 14 Jul 2025 01:37:39 +0000 (19:37 -0600)
src/lib/util/misc.c
src/lib/util/misc.h

index b20d703963b162c9196c6958a732aa2950b29658..a690958294f1f7159bee7fe8c61427865d4d2c61 100644 (file)
@@ -26,6 +26,7 @@ RCSID("$Id$")
 #include <freeradius-devel/util/sbuff.h>
 #include <freeradius-devel/util/syserror.h>
 
+#include <string.h>
 #include <fcntl.h>
 #include <grp.h>
 #include <pwd.h>
@@ -478,3 +479,50 @@ int fr_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
 
        return result;          /* 0 is OK, !0 is !OK, just like memcmp */
 }
+
+/** Get the filename from a path
+ *
+ * @param path to get filename from.
+ * @return
+ *     - pointer to the filename in the path.
+ *     - pointer to the path if no '/' is found.
+ */
+char const *fr_filename(char const *path)
+{
+       char const *p = strrchr(path, '/');
+
+       if (p) return p + 1;
+
+       return path;
+}
+
+/** Get the filename from a path
+ *
+ * @param path to get filename from.
+ * @return
+ *     - pointer to the filename in the path.
+ *     - pointer to the path if no '/' is found.
+ */
+char const *fr_filename_common_trim(char const *path, char const *common)
+{
+       char const *p_p, *p_c, *p_pn, *p_cn;
+
+       if (!path) return NULL;
+       if (!common) return NULL;
+
+       p_p = path;
+       p_c = common;
+
+       while ((p_pn = strchr(p_p, '/')) != NULL) {
+               p_cn = strchr(p_c, '/');
+               if (!p_cn) p_cn = p_c + strlen(p_c);
+
+               if ((p_pn - p_p) != (p_cn - p_c)) break;        /* path component not the same len */
+               if (strncmp(p_p, p_c, p_pn - p_p) != 0) break;  /* path component not the same */
+
+               p_p = p_pn + 1;
+               p_c = p_cn + 1;
+       }
+
+       return p_p;
+}
index e7bacbc081e45f4e103299e3c620422378cd1108..7d659ea3fe2fd6ff0a1c9472d558e444970a34c9 100644 (file)
@@ -153,6 +153,9 @@ int8_t              fr_pointer_cmp(void const *a, void const *b);
 void           fr_quick_sort(void const *to_sort[], int min_idx, int max_idx, fr_cmp_t cmp);
 int            fr_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length) CC_HINT(nonnull);
 
+char const     *fr_filename(char const *path);
+char const     *fr_filename_common_trim(char const *path, char const *common);
+
 #ifdef __cplusplus
 }
 #endif