summaryrefslogtreecommitdiffstats
path: root/common/file-list.c
blob: 90c0f429c5102461f472604a32d9b74de36c596a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <common.h>
#include <malloc.h>
#include <fs.h>
#include <file-list.h>
#include <linux/err.h>

#define PARSE_DEVICE	0
#define PARSE_NAME	1
#define PARSE_FLAGS	2

static int file_list_parse_one(struct file_list *files, const char *partstr, const char **endstr)
{
	int i = 0, state = PARSE_DEVICE;
	char filename[PATH_MAX];
	char name[PATH_MAX];
	struct file_list_entry *entry = xzalloc(sizeof(*entry));

	memset(filename, 0, sizeof(filename));
	memset(name, 0, sizeof(name));

	while (*partstr && *partstr != ',') {
		switch (state) {
		case PARSE_DEVICE:
			if (*partstr == '(') {
				state = PARSE_NAME;
				i = 0;
			} else {
				filename[i++] = *partstr;
			}
			break;
		case PARSE_NAME:
			if (*partstr == ')') {
				state = PARSE_FLAGS;
				i = 0;
			} else {
				name[i++] = *partstr;
			}
			break;
		case PARSE_FLAGS:
			switch (*partstr) {
			case 's':
				entry->flags |= FILE_LIST_FLAG_SAFE;
				break;
			case 'r':
				entry->flags |= FILE_LIST_FLAG_READBACK;
				break;
			case 'c':
				entry->flags |= FILE_LIST_FLAG_CREATE;
				break;
			default:
				return -EINVAL;
			}
			break;
		default:
			return -EINVAL;
		}
		partstr++;
	}

	if (state != PARSE_FLAGS)
		return -EINVAL;

	entry->name = xstrdup(name);
	entry->filename = xstrdup(filename);
	if (*partstr == ',')
		partstr++;
	*endstr = partstr;

	list_add_tail(&entry->list, &files->list);

	return 0;
}

struct file_list *file_list_parse(const char *str)
{
	struct file_list *files;
	int ret;
	const char *endptr;

	files = xzalloc(sizeof(*files));

	INIT_LIST_HEAD(&files->list);

	while (*str) {
		if (file_list_parse_one(files, str, &endptr)) {
			printf("parse error\n");
			ret = -EINVAL;
			goto out;
		}
		str = endptr;

		files->num_entries++;
	}

	return files;
out:
	free(files);

	return ERR_PTR(ret);
}

void file_list_free(struct file_list *files)
{
	struct file_list_entry *entry, *tmp;

	list_for_each_entry_safe(entry, tmp, &files->list, list) {
		free(entry->name);
		free(entry->filename);
		free(entry);
	}

	free(files);
}