blob: b3ab8ab19076129c75c3e0b16e2a20d1abd4f15d [file] [log] [blame]
Richard Haines6d0b91b2015-06-04 20:03:41 +01001/*
2 * This file contains helper functions for labeling support.
3 *
4 * Author : Richard Haines <richard_c_haines@btinternet.com>
5 */
6
7#include <stdlib.h>
8#include <stdarg.h>
9#include <ctype.h>
10#include <string.h>
11#include "label_internal.h"
12
13/*
14 * The read_spec_entries and read_spec_entry functions may be used to
15 * replace sscanf to read entries from spec files. The file and
16 * property services now use these.
17 */
18
19/* Read an entry from a spec file (e.g. file_contexts) */
20static inline int read_spec_entry(char **entry, char **ptr, int *len)
21{
22 *entry = NULL;
23 char *tmp_buf = NULL;
24
25 while (isspace(**ptr) && **ptr != '\0')
26 (*ptr)++;
27
28 tmp_buf = *ptr;
29 *len = 0;
30
31 while (!isspace(**ptr) && **ptr != '\0') {
32 (*ptr)++;
33 (*len)++;
34 }
35
36 if (*len) {
37 *entry = strndup(tmp_buf, *len);
38 if (!*entry)
39 return -1;
40 }
41
42 return 0;
43}
44
45/*
46 * line_buf - Buffer containing the spec entries .
47 * num_args - The number of spec parameter entries to process.
48 * ... - A 'char **spec_entry' for each parameter.
49 * returns - The number of items processed.
50 *
51 * This function calls read_spec_entry() to do the actual string processing.
52 */
53int hidden read_spec_entries(char *line_buf, int num_args, ...)
54{
55 char **spec_entry, *buf_p;
56 int len, rc, items, entry_len = 0;
57 va_list ap;
58
59 len = strlen(line_buf);
60 if (line_buf[len - 1] == '\n')
61 line_buf[len - 1] = '\0';
62 else
63 /* Handle case if line not \n terminated by bumping
64 * the len for the check below (as the line is NUL
65 * terminated by getline(3)) */
66 len++;
67
68 buf_p = line_buf;
69 while (isspace(*buf_p))
70 buf_p++;
71
72 /* Skip comment lines and empty lines. */
73 if (*buf_p == '#' || *buf_p == '\0')
74 return 0;
75
76 /* Process the spec file entries */
77 va_start(ap, num_args);
78
79 items = 0;
80 while (items < num_args) {
81 spec_entry = va_arg(ap, char **);
82
83 if (len - 1 == buf_p - line_buf) {
84 va_end(ap);
85 return items;
86 }
87
88 rc = read_spec_entry(spec_entry, &buf_p, &entry_len);
89 if (rc < 0) {
90 va_end(ap);
91 return rc;
92 }
93 if (entry_len)
94 items++;
95 }
96 va_end(ap);
97 return items;
98}