diff --git a/src/guestfs-internal.h b/src/guestfs-internal.h index 3752f7982..545146f70 100644 --- a/src/guestfs-internal.h +++ b/src/guestfs-internal.h @@ -833,4 +833,7 @@ extern void guestfs___cleanup_cmd_close (struct command **); /* launch-direct.c */ extern char *guestfs___drive_source_qemu_param (guestfs_h *g, const struct drive_source *src); +/* utils.c */ +extern int guestfs___validate_guid (const char *); + #endif /* GUESTFS_INTERNAL_H_ */ diff --git a/src/test-utils.c b/src/test-utils.c index 8ee287306..089d6b803 100644 --- a/src/test-utils.c +++ b/src/test-utils.c @@ -24,6 +24,7 @@ #include #include "guestfs.h" +#include "guestfs-internal.h" #include "guestfs-internal-frontend.h" /* Test guestfs___split_string. */ @@ -145,12 +146,25 @@ test_join (void) free (ret); } +/* Test guestfs___validate_guid. */ +static void +test_validate_guid (void) +{ + assert (guestfs___validate_guid ("") == 0); + assert (guestfs___validate_guid ("1") == 0); + assert (guestfs___validate_guid ("21EC20203AEA1069A2DD08002B30309D") == 0); + + assert (guestfs___validate_guid ("{21EC2020-3AEA-1069-A2DD-08002B30309D}") == 1); + assert (guestfs___validate_guid ("21EC2020-3AEA-1069-A2DD-08002B30309D") == 1); +} + int main (int argc, char *argv[]) { test_split (); test_concat (); test_join (); + test_validate_guid (); exit (EXIT_SUCCESS); } diff --git a/src/utils.c b/src/utils.c index 5eebdf6e8..45adc3db6 100644 --- a/src/utils.c +++ b/src/utils.c @@ -28,7 +28,10 @@ #include #include +#include "c-ctype.h" + #include "guestfs.h" +#include "guestfs-internal.h" #include "guestfs-internal-frontend.h" /* Note that functions in libutils are used by the tools and language @@ -268,3 +271,44 @@ guestfs___drive_name (size_t index, char *ret) *ret = '\0'; return ret; } + +/* Check whether a string supposed to contain a GUID actually contains it. + * It can recognize strings either as '{21EC2020-3AEA-1069-A2DD-08002B30309D}' + * or '21EC2020-3AEA-1069-A2DD-08002B30309D'. + */ +int +guestfs___validate_guid (const char *str) +{ + int len = strlen (str); + switch (len) { + case 36: + break; + case 38: + if (str[0] == '{' && str[len -1] == '}') { + ++str; + len -= 2; + break; + } + return 0; + default: + return 0; + } + + for (int i = 0; i < len; ++i) { + switch (i) { + case 8: + case 13: + case 18: + case 23: + if (str[i] != '-') + return 0; + break; + default: + if (!c_isalnum (str[i])) + return 0; + break; + } + } + + return 1; +}