summaryrefslogtreecommitdiffstats
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 d6437fc..a34cc5c 100644
--- a/lib/utils_base.c
+++ b/lib/utils_base.c
@@ -251,3 +251,60 @@ int np_warn_if_not_root(void) {
251 } 251 }
252 return status; 252 return status;
253} 253}
254
255/*
256 * Extract the value from key/value pairs, or return NULL. The value returned
257 * can be free()ed.
258 * This function can be used to parse NTP control packet data and performance
259 * data strings.
260 */
261char *np_extract_value(const char *varlist, const char *name) {
262 char *tmp=NULL, *value=NULL;
263 int i;
264
265 while (1) {
266 /* Strip any leading space */
267 for (varlist; isspace(varlist[0]); varlist++);
268
269 if (strncmp(name, varlist, strlen(name)) == 0) {
270 varlist += strlen(name);
271 /* strip trailing spaces */
272 for (varlist; isspace(varlist[0]); varlist++);
273
274 if (varlist[0] == '=') {
275 /* We matched the key, go past the = sign */
276 varlist++;
277 /* strip leading spaces */
278 for (varlist; isspace(varlist[0]); varlist++);
279
280 if (tmp = index(varlist, ',')) {
281 /* Value is delimited by a comma */
282 if (tmp-varlist == 0) continue;
283 value = (char *)malloc(tmp-varlist+1);
284 strncpy(value, varlist, tmp-varlist);
285 value[tmp-varlist] = '\0';
286 } else {
287 /* Value is delimited by a \0 */
288 if (strlen(varlist) == 0) continue;
289 value = (char *)malloc(strlen(varlist) + 1);
290 strncpy(value, varlist, strlen(varlist));
291 value[strlen(varlist)] = '\0';
292 }
293 break;
294 }
295 }
296 if (tmp = index(varlist, ',')) {
297 /* More keys, keep going... */
298 varlist = tmp + 1;
299 } else {
300 /* We're done */
301 break;
302 }
303 }
304
305 /* Clean-up trailing spaces/newlines */
306 if (value) for (i=strlen(value)-1; isspace(value[i]); i--) value[i] = '\0';
307
308 return value;
309}
310