summaryrefslogtreecommitdiff
path: root/src/libstddjb/envdir.c
diff options
context:
space:
mode:
authorLaurent Bercot <ska-skaware@skarnet.org>2014-09-18 18:55:44 +0000
committerLaurent Bercot <ska-skaware@skarnet.org>2014-09-18 18:55:44 +0000
commit3534b428629be185e096be99e3bd5fdfe32d5544 (patch)
tree210ef3198ed66bc7f7b7bf6a85e4579f455e5a36 /src/libstddjb/envdir.c
downloadskalibs-3534b428629be185e096be99e3bd5fdfe32d5544.tar.xz
initial commit with rc for skalibs-2.0.0.0
Diffstat (limited to 'src/libstddjb/envdir.c')
-rw-r--r--src/libstddjb/envdir.c84
1 files changed, 84 insertions, 0 deletions
diff --git a/src/libstddjb/envdir.c b/src/libstddjb/envdir.c
new file mode 100644
index 0000000..7866c7a
--- /dev/null
+++ b/src/libstddjb/envdir.c
@@ -0,0 +1,84 @@
+/* ISC license. */
+
+#include <unistd.h>
+#include <errno.h>
+#include <skalibs/bytestr.h>
+#include <skalibs/env.h>
+#include <skalibs/direntry.h>
+#include <skalibs/stralloc.h>
+#include <skalibs/djbunix.h>
+
+#define MAXVARSIZE 4095
+
+int envdir_internal (char const *path, stralloc *modifs, unsigned int options, char nullis)
+{
+ char buf[MAXVARSIZE + 1] ;
+ unsigned int n = 0 ;
+ unsigned int pathlen = str_len(path) ;
+ unsigned int modifbase = modifs->len ;
+ int wasnull = !modifs->s ;
+ DIR *dir ;
+ if (!nullis) return (errno = EINVAL, -1) ;
+ dir = opendir(path) ;
+ if (!dir) return -1 ;
+ for (;;)
+ {
+ direntry *d ;
+ unsigned int len ;
+ register int r ;
+ errno = 0 ;
+ d = readdir(dir) ;
+ if (!d) break ;
+ if (d->d_name[0] == '.') continue ;
+ len = str_len(d->d_name) ;
+ if (str_chr(d->d_name, '=') < len) continue ;
+ {
+ char tmp[pathlen + len + 2] ;
+ byte_copy(tmp, pathlen, path) ;
+ tmp[pathlen] = '/' ;
+ byte_copy(tmp + pathlen + 1, len + 1, d->d_name) ;
+ r = openreadnclose(tmp, buf, MAXVARSIZE) ;
+ }
+ if (r < 0)
+ {
+ if (errno == ENOENT) errno = EIDRM ;
+ goto err ;
+ }
+ else if (r > 0)
+ {
+ if (options & SKALIBS_ENVDIR_VERBATIM)
+ {
+ if (!(options & SKALIBS_ENVDIR_NOCHOMP) && (buf[r-1] == '\n')) r-- ;
+ }
+ else
+ {
+ r = byte_chr(buf, r, '\n') ;
+ if (!(options & SKALIBS_ENVDIR_NOCHOMP))
+ {
+ while (r--) if ((buf[r] != ' ') && (buf[r] != '\t') && (buf[r] != '\r')) break ;
+ r++ ;
+ }
+ }
+ {
+ register unsigned int i = 0 ;
+ for (; i < (unsigned int)r ; i++) if (!buf[i]) buf[i] = nullis ;
+ }
+ buf[r++] = 0 ;
+ if (!env_addmodif(modifs, d->d_name, buf)) goto err ;
+ }
+ else if (!env_addmodif(modifs, d->d_name, 0)) goto err ;
+ n++ ;
+ }
+ if (errno) goto err ;
+ dir_close(dir) ;
+ return n ;
+
+ err:
+ {
+ register int e = errno ;
+ dir_close(dir) ;
+ if (wasnull) stralloc_free(modifs) ; else modifs->len = modifbase ;
+ errno = e ;
+ return -1 ;
+ }
+}