]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
lib/path: add error handling to path_vcreate()
authorRuediger Meier <ruediger.meier@ga-group.nl>
Tue, 27 Jun 2017 18:33:08 +0000 (20:33 +0200)
committerRuediger Meier <ruediger.meier@ga-group.nl>
Thu, 29 Jun 2017 12:03:49 +0000 (14:03 +0200)
Do not operate on truncated/random paths. Note, path_strdup()
can now really return NULL, to be handled in next commit.

Signed-off-by: Ruediger Meier <ruediger.meier@ga-group.nl>
lib/path.c

index eaa6d881c60638d8dc399c60dc53baa1f74ab992..3c587e43332c24b48f7c868e2f87f09c3f1e45ee 100644 (file)
@@ -38,11 +38,15 @@ static char pathbuf[PATH_MAX];
 static const char *
 path_vcreate(const char *path, va_list ap)
 {
-       if (prefixlen)
-               vsnprintf(pathbuf + prefixlen,
-                         sizeof(pathbuf) - prefixlen, path, ap);
-       else
-               vsnprintf(pathbuf, sizeof(pathbuf), path, ap);
+       int rc = vsnprintf(
+               pathbuf + prefixlen, sizeof(pathbuf) - prefixlen, path, ap);
+
+       if (rc < 0)
+               return NULL;
+       if ((size_t)rc >= sizeof(pathbuf)) {
+               errno = ENAMETOOLONG;
+               return NULL;
+       }
        return pathbuf;
 }
 
@@ -64,11 +68,18 @@ path_vfopen(const char *mode, int exit_on_error, const char *path, va_list ap)
 {
        FILE *f;
        const char *p = path_vcreate(path, ap);
+       if (!p)
+               goto err;
 
        f = fopen(p, mode);
-       if (!f && exit_on_error)
-               err(EXIT_FAILURE, _("cannot open %s"), p);
+       if (!f)
+               goto err;
+
        return f;
+err:
+       if (exit_on_error)
+               err(EXIT_FAILURE, _("cannot open %s"), p ? p : "path");
+       return NULL;
 }
 
 static int
@@ -76,11 +87,16 @@ path_vopen(int flags, const char *path, va_list ap)
 {
        int fd;
        const char *p = path_vcreate(path, ap);
+       if (!p)
+               goto err;
 
        fd = open(p, flags);
        if (fd == -1)
-               err(EXIT_FAILURE, _("cannot open %s"), p);
+               goto err;
+
        return fd;
+err:
+       err(EXIT_FAILURE, _("cannot open %s"), p ? p : "path");
 }
 
 FILE *
@@ -181,7 +197,7 @@ path_exist(const char *path, ...)
        p = path_vcreate(path, ap);
        va_end(ap);
 
-       return access(p, F_OK) == 0;
+       return p && access(p, F_OK) == 0;
 }
 
 #ifdef HAVE_CPU_SET_T