check snprintf error aswell, handle as truncation error

Signed-off-by: Hiltjo Posthuma <hiltjo@codemadness.org>
This commit is contained in:
Hiltjo Posthuma 2014-06-01 15:01:09 +02:00 committed by sin
parent 953ebf3573
commit eac0f658cf
3 changed files with 13 additions and 10 deletions

6
du.c
View File

@ -120,6 +120,7 @@ du(const char *path)
struct dirent *dent; struct dirent *dent;
struct stat st; struct stat st;
long n = 0, m; long n = 0, m;
int r;
if (lstat(path, &st) < 0) if (lstat(path, &st) < 0)
eprintf("stat: %s:", path); eprintf("stat: %s:", path);
@ -149,8 +150,9 @@ du(const char *path)
n += m; n += m;
if (aflag && !sflag) { if (aflag && !sflag) {
if (S_ISLNK(st.st_mode)) { if (S_ISLNK(st.st_mode)) {
if (snprintf(file, sizeof(file), "%s/%s", r = snprintf(file, sizeof(file), "%s/%s",
cwd, dent->d_name) >= sizeof(file)) cwd, dent->d_name);
if(r >= sizeof(file) || r < 0)
eprintf("path too long\n"); eprintf("path too long\n");
} else { } else {
xrealpath(dent->d_name, file); xrealpath(dent->d_name, file);

View File

@ -21,7 +21,7 @@ main(int argc, char *argv[])
char *template = "tmp.XXXXXXXXXX"; char *template = "tmp.XXXXXXXXXX";
char *tmpdir = "/tmp", *p; char *tmpdir = "/tmp", *p;
char tmppath[PATH_MAX]; char tmppath[PATH_MAX];
int fd; int fd, r;
ARGBEGIN { ARGBEGIN {
case 'd': case 'd':
@ -42,8 +42,9 @@ main(int argc, char *argv[])
if ((p = getenv("TMPDIR"))) if ((p = getenv("TMPDIR")))
tmpdir = p; tmpdir = p;
if (snprintf(tmppath, sizeof(tmppath), r = snprintf(tmppath, sizeof(tmppath),
"%s/%s", tmpdir, template) >= sizeof(tmppath)) "%s/%s", tmpdir, template);
if (r >= sizeof(tmppath) || r < 0)
eprintf("path too long\n"); eprintf("path too long\n");
if (dflag) { if (dflag) {
if (!mkdtemp(tmppath)) { if (!mkdtemp(tmppath)) {

View File

@ -24,6 +24,7 @@ cp(const char *s1, const char *s2)
struct dirent *d; struct dirent *d;
struct stat st; struct stat st;
DIR *dp; DIR *dp;
int r;
if (stat(s1, &st) == 0 && S_ISDIR(st.st_mode)) { if (stat(s1, &st) == 0 && S_ISDIR(st.st_mode)) {
if (!cp_rflag) if (!cp_rflag)
@ -40,14 +41,13 @@ cp(const char *s1, const char *s2)
while((d = readdir(dp))) { while((d = readdir(dp))) {
if(strcmp(d->d_name, ".") if(strcmp(d->d_name, ".")
&& strcmp(d->d_name, "..")) { && strcmp(d->d_name, "..")) {
if(snprintf(ns1, size1, "%s/%s", s1, r = snprintf(ns1, size1, "%s/%s", s1, d->d_name);
d->d_name) >= size1) { if(r >= size1 || r < 0) {
eprintf("%s/%s: filename too long\n", eprintf("%s/%s: filename too long\n",
s1, d->d_name); s1, d->d_name);
} }
r = snprintf(ns2, size2, "%s/%s", s2, d->d_name);
if(snprintf(ns2, size2, "%s/%s", s2, if(r >= size2 || r < 0) {
d->d_name) >= size2) {
eprintf("%s/%s: filename too long\n", eprintf("%s/%s: filename too long\n",
s2, d->d_name); s2, d->d_name);
} }