utils: add a function to validate a GUID string

This commit is contained in:
Pino Toscano
2014-02-06 15:57:09 +01:00
parent ed912a54d6
commit beef77403c
3 changed files with 61 additions and 0 deletions

View File

@@ -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_ */

View File

@@ -24,6 +24,7 @@
#include <assert.h>
#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);
}

View File

@@ -28,7 +28,10 @@
#include <sys/wait.h>
#include <libintl.h>
#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;
}