From: Arran Cudbard-Bell Date: Mon, 14 Jul 2025 00:16:11 +0000 (-0600) Subject: Add utility functions to trim paths X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e7e505e2372dc874600749b88fa5ce642ef16e30;p=thirdparty%2Ffreeradius-server.git Add utility functions to trim paths --- diff --git a/src/lib/util/misc.c b/src/lib/util/misc.c index b20d703963..a690958294 100644 --- a/src/lib/util/misc.c +++ b/src/lib/util/misc.c @@ -26,6 +26,7 @@ RCSID("$Id$") #include #include +#include #include #include #include @@ -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; +} diff --git a/src/lib/util/misc.h b/src/lib/util/misc.h index e7bacbc081..7d659ea3fe 100644 --- a/src/lib/util/misc.h +++ b/src/lib/util/misc.h @@ -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