aboutsummaryrefslogtreecommitdiff
path: root/lib/utils_base.c
diff options
context:
space:
mode:
Diffstat (limited to 'lib/utils_base.c')
-rw-r--r--lib/utils_base.c57
1 files changed, 57 insertions, 0 deletions
diff --git a/lib/utils_base.c b/lib/utils_base.c
index d6437fc8..a34cc5cc 100644
--- a/lib/utils_base.c
+++ b/lib/utils_base.c
@@ -251,3 +251,60 @@ int np_warn_if_not_root(void) {
}
return status;
}
+
+/*
+ * Extract the value from key/value pairs, or return NULL. The value returned
+ * can be free()ed.
+ * This function can be used to parse NTP control packet data and performance
+ * data strings.
+ */
+char *np_extract_value(const char *varlist, const char *name) {
+ char *tmp=NULL, *value=NULL;
+ int i;
+
+ while (1) {
+ /* Strip any leading space */
+ for (varlist; isspace(varlist[0]); varlist++);
+
+ if (strncmp(name, varlist, strlen(name)) == 0) {
+ varlist += strlen(name);
+ /* strip trailing spaces */
+ for (varlist; isspace(varlist[0]); varlist++);
+
+ if (varlist[0] == '=') {
+ /* We matched the key, go past the = sign */
+ varlist++;
+ /* strip leading spaces */
+ for (varlist; isspace(varlist[0]); varlist++);
+
+ if (tmp = index(varlist, ',')) {
+ /* Value is delimited by a comma */
+ if (tmp-varlist == 0) continue;
+ value = (char *)malloc(tmp-varlist+1);
+ strncpy(value, varlist, tmp-varlist);
+ value[tmp-varlist] = '\0';
+ } else {
+ /* Value is delimited by a \0 */
+ if (strlen(varlist) == 0) continue;
+ value = (char *)malloc(strlen(varlist) + 1);
+ strncpy(value, varlist, strlen(varlist));
+ value[strlen(varlist)] = '\0';
+ }
+ break;
+ }
+ }
+ if (tmp = index(varlist, ',')) {
+ /* More keys, keep going... */
+ varlist = tmp + 1;
+ } else {
+ /* We're done */
+ break;
+ }
+ }
+
+ /* Clean-up trailing spaces/newlines */
+ if (value) for (i=strlen(value)-1; isspace(value[i]); i--) value[i] = '\0';
+
+ return value;
+}
+