Add simple authentication support for cmus-remote
[cmus.git] / load_dir.c
blob5426fc0417476bab49b8419680ac332587fdb4db
1 /*
2 * Copyright Timo Hirvonen
3 */
5 #include "load_dir.h"
6 #include "xmalloc.h"
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 #include <dirent.h>
12 #include <errno.h>
14 int dir_open(struct directory *dir, const char *name)
16 int len = strlen(name);
18 if (len >= sizeof(dir->path) - 2) {
19 errno = ENAMETOOLONG;
20 return -1;
23 dir->d = opendir(name);
24 if (!dir->d)
25 return -1;
27 memcpy(dir->path, name, len);
28 dir->path[len++] = '/';
29 dir->path[len] = 0;
30 dir->len = len;
31 return 0;
34 void dir_close(struct directory *dir)
36 closedir(dir->d);
39 const char *dir_read(struct directory *dir)
41 DIR *d = dir->d;
42 int len = dir->len;
43 char *full = dir->path;
44 struct dirent *de;
46 while ((de = readdir(d))) {
47 const char *name = de->d_name;
48 int nlen = strlen(name);
50 /* just ignore too long paths
51 * + 2 -> space for \0 or / and \0
53 if (len + nlen + 2 >= sizeof(dir->path))
54 continue;
56 memcpy(full + len, name, nlen + 1);
57 if (lstat(full, &dir->st))
58 continue;
60 dir->is_link = 0;
61 if (S_ISLNK(dir->st.st_mode)) {
62 /* argh. must stat the target */
63 if (stat(full, &dir->st))
64 continue;
65 dir->is_link = 1;
68 return full + len;
70 return NULL;
73 void ptr_array_add(struct ptr_array *array, void *ptr)
75 void **ptrs = ptrs = array->ptrs;
76 int alloc = array->alloc;
78 if (alloc == array->count) {
79 alloc = alloc * 3 / 2 + 16;
80 ptrs = xrealloc(ptrs, alloc * sizeof(void *));
81 array->ptrs = ptrs;
82 array->alloc = alloc;
84 ptrs[array->count++] = ptr;