aboutsummaryrefslogtreecommitdiffstats
path: root/libcontacts_list_contacts.c
blob: 6879999f7ceb9432d6cb614548862be61de39532 (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
/* See LICENSE file for copyright and license details. */
#include "common.h"


int
libcontacts_list_contacts(char ***idsp, const struct passwd *user, int with_me)
{
	char *dirnam;
	DIR *dir;
	struct dirent *f;
	size_t i = 0;
	void *new;
	int saved_errno = errno;

	*idsp = NULL;

	dirnam = libcontacts_get_path("", user);
	if (!dirnam)
		return -1;

	dir = opendir(dirnam);
	if (!dir) {
		if (errno == ENOENT) {
			errno = saved_errno;
			new = malloc(sizeof(**idsp));
			if (new) {
				*idsp = new;
				**idsp = NULL;
				free(dirnam);
				return 0;
			}
		}
		free(dirnam);
		return -1;
	}

	goto start;
	while ((f = readdir(dir))) {
		if (f->d_name[0] == '.') {
			if (!with_me || strcmp(f->d_name, ".me"))
				continue;
		} else if (!f->d_name[0] || strchr(f->d_name, '\0')[-1] == '~') {
			continue;
		}
		if (!((*idsp)[i++] = strdup(f->d_name)))
			goto fail;
	start:
		new = realloc(*idsp, (i + 1) * sizeof(**idsp));
		if (!new)
			goto fail;
		*idsp = new;
	}
	(*idsp)[i] = NULL;

	if (errno)
		goto fail;
	closedir(dir);
	free(dirnam);
	errno = saved_errno;
	return 0;

fail:
	saved_errno = errno;
	closedir(dir);
	free(dirnam);
	if (*idsp) {
		for (i = 0; (*idsp)[i]; i++)
			free((*idsp)[i]);
		free(*idsp);
	}
	errno = saved_errno;
	return -1;
}