]> git.proxmox.com Git - mirror_lxc.git/blobdiff - src/lxc/utils.c
secure coding: #2 strcpy => strlcpy
[mirror_lxc.git] / src / lxc / utils.c
index a82a2f49465e45e329e870aaa7b37461d205832c..1319025a1ba21758f376ce7678b1cbe0efa6d0db 100644 (file)
@@ -31,6 +31,7 @@
 #include <grp.h>
 #include <inttypes.h>
 #include <libgen.h>
+#include <pthread.h>
 #include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include "parse.h"
 #include "utils.h"
 
+#ifndef HAVE_STRLCPY
+#include "include/strlcpy.h"
+#endif
+
 #ifndef O_PATH
 #define O_PATH      010000000
 #endif
@@ -84,9 +89,6 @@ static int _recursive_rmdir(const char *dirname, dev_t pdev,
                struct stat mystat;
                int rc;
 
-               if (!direntp)
-                       break;
-
                if (!strcmp(direntp->d_name, ".") ||
                    !strcmp(direntp->d_name, ".."))
                        continue;
@@ -245,8 +247,13 @@ char *get_rundir()
 {
        char *rundir;
        const char *homedir;
+       struct stat sb;
+
+       if (stat(RUNTIME_PATH, &sb) < 0) {
+               return NULL;
+       }
 
-       if (geteuid() == 0) {
+       if (geteuid() == sb.st_uid || getegid() == sb.st_gid) {
                rundir = strdup(RUNTIME_PATH);
                return rundir;
        }
@@ -473,7 +480,7 @@ struct lxc_popen_FILE *lxc_popen(const char *command)
                        ret = fcntl(pipe_fds[1], F_SETFD, 0);
                if (ret < 0) {
                        close(pipe_fds[1]);
-                       exit(EXIT_FAILURE);
+                       _exit(EXIT_FAILURE);
                }
 
                /* duplicate stderr */
@@ -483,19 +490,19 @@ struct lxc_popen_FILE *lxc_popen(const char *command)
                        ret = fcntl(pipe_fds[1], F_SETFD, 0);
                close(pipe_fds[1]);
                if (ret < 0)
-                       exit(EXIT_FAILURE);
+                       _exit(EXIT_FAILURE);
 
                /* unblock all signals */
                ret = sigfillset(&mask);
                if (ret < 0)
-                       exit(EXIT_FAILURE);
+                       _exit(EXIT_FAILURE);
 
-               ret = sigprocmask(SIG_UNBLOCK, &mask, NULL);
+               ret = pthread_sigmask(SIG_UNBLOCK, &mask, NULL);
                if (ret < 0)
-                       exit(EXIT_FAILURE);
+                       _exit(EXIT_FAILURE);
 
                execl("/bin/sh", "sh", "-c", command, (char *)NULL);
-               exit(127);
+               _exit(127);
        }
 
        close(pipe_fds[1]);
@@ -504,10 +511,14 @@ struct lxc_popen_FILE *lxc_popen(const char *command)
        fp = malloc(sizeof(*fp));
        if (!fp)
                goto on_error;
+       memset(fp, 0, sizeof(*fp));
 
        fp->child_pid = child_pid;
        fp->pipe = pipe_fds[0];
 
+       /* From now on, closing fp->f will also close fp->pipe. So only ever
+        * call fclose(fp->f).
+        */
        fp->f = fdopen(pipe_fds[0], "r");
        if (!fp->f)
                goto on_error;
@@ -515,15 +526,22 @@ struct lxc_popen_FILE *lxc_popen(const char *command)
        return fp;
 
 on_error:
-       if (fp)
-               free(fp);
-
-       if (pipe_fds[0] >= 0)
+       /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
+        * called yet. Otherwise the fd belongs to the file opened by fdopen()
+        * since it isn't dup()ed.
+        */
+       if (fp && !fp->f && pipe_fds[0] >= 0)
                close(pipe_fds[0]);
 
        if (pipe_fds[1] >= 0)
                close(pipe_fds[1]);
 
+       if (fp && fp->f)
+               fclose(fp->f);
+
+       if (fp)
+               free(fp);
+
        return NULL;
 }
 
@@ -539,7 +557,6 @@ int lxc_pclose(struct lxc_popen_FILE *fp)
                wait_pid = waitpid(fp->child_pid, &wstatus, 0);
        } while (wait_pid < 0 && errno == EINTR);
 
-       close(fp->pipe);
        fclose(fp->f);
        free(fp);
 
@@ -628,7 +645,8 @@ char *lxc_string_join(const char *sep, const char **parts, bool use_as_prefix)
                return NULL;
 
        if (use_as_prefix)
-               strcpy(result, sep);
+               (void)strlcpy(result, sep, result_len + 1);
+
        for (p = (char **)parts; *p; p++) {
                if (p > (char **)parts)
                        strcat(result, sep);
@@ -745,12 +763,15 @@ bool lxc_string_in_list(const char *needle, const char *haystack, char _sep)
 {
        char *token, *str, *saveptr = NULL;
        char sep[2] = { _sep, '\0' };
+       size_t len;
 
        if (!haystack || !needle)
                return 0;
 
-       str = alloca(strlen(haystack)+1);
-       strcpy(str, haystack);
+       len = strlen(haystack);
+       str = alloca(len + 1);
+       (void)strlcpy(str, haystack, len + 1);
+
        for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
                if (strcmp(needle, token) == 0)
                        return 1;
@@ -767,12 +788,15 @@ char **lxc_string_split(const char *string, char _sep)
        size_t result_capacity = 0;
        size_t result_count = 0;
        int r, saved_errno;
+       size_t len;
 
        if (!string)
                return calloc(1, sizeof(char *));
 
-       str = alloca(strlen(string) + 1);
-       strcpy(str, string);
+       len = strlen(string);
+       str = alloca(len + 1);
+       (void)strlcpy(str, string, len + 1);
+
        for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
                r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 16);
                if (r < 0)
@@ -876,12 +900,15 @@ char **lxc_string_split_and_trim(const char *string, char _sep)
        size_t result_count = 0;
        int r, saved_errno;
        size_t i = 0;
+       size_t len;
 
        if (!string)
                return calloc(1, sizeof(char *));
 
-       str = alloca(strlen(string)+1);
-       strcpy(str, string);
+       len = strlen(string);
+       str = alloca(len + 1);
+       (void)strlcpy(str, string, len + 1);
+
        for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
                while (token[0] == ' ' || token[0] == '\t')
                        token++;
@@ -956,12 +983,13 @@ size_t lxc_array_len(void **array)
        return result;
 }
 
-int lxc_write_to_file(const char *filename, const void* buf, size_t count, bool add_newline)
+int lxc_write_to_file(const char *filename, const void *buf, size_t count,
+                     bool add_newline, mode_t mode)
 {
        int fd, saved_errno;
        ssize_t ret;
 
-       fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0666);
+       fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, mode);
        if (fd < 0)
                return -1;
        ret = lxc_write_nointr(fd, buf, count);
@@ -1701,7 +1729,7 @@ int lxc_mount_proc_if_needed(const char *rootfs)
                return -1;
        }
 
-       mypid = getpid();
+       mypid = lxc_raw_getpid();
        INFO("I am %d, /proc/self points to \"%s\"", mypid, link);
 
        if (lxc_safe_int(link, &link_to_pid) < 0)
@@ -1795,46 +1823,18 @@ int lxc_count_file_lines(const char *fn)
        return n;
 }
 
-void *lxc_strmmap(void *addr, size_t length, int prot, int flags, int fd,
-                 off_t offset)
-{
-       void *tmp = NULL, *overlap = NULL;
-
-       /* We establish an anonymous mapping that is one byte larger than the
-        * underlying file. The pages handed to us are zero filled. */
-       tmp = mmap(addr, length + 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
-       if (tmp == MAP_FAILED)
-               return tmp;
-
-       /* Now we establish a fixed-address mapping starting at the address we
-        * received from our anonymous mapping and replace all bytes excluding
-        * the additional \0-byte with the file. This allows us to use normal
-        * string-handling functions. */
-       overlap = mmap(tmp, length, prot, MAP_FIXED | flags, fd, offset);
-       if (overlap == MAP_FAILED)
-               munmap(tmp, length + 1);
-
-       return overlap;
-}
-
-int lxc_strmunmap(void *addr, size_t length)
-{
-       return munmap(addr, length + 1);
-}
-
 /* Check whether a signal is blocked by a process. */
 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
-#define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
-bool task_blocking_signal(pid_t pid, int signal)
+#define __PROC_STATUS_LEN (6 + (LXC_NUMSTRLEN64) + 7 + 1)
+bool task_blocks_signal(pid_t pid, int signal)
 {
-       bool bret = false;
-       char *line = NULL;
-       long unsigned int sigblk = 0;
-       size_t n = 0;
        int ret;
-       FILE *f;
-
        char status[__PROC_STATUS_LEN];
+       FILE *f;
+       uint64_t sigblk = 0, one = 1;
+       size_t n = 0;
+       bool bret = false;
+       char *line = NULL;
 
        ret = snprintf(status, __PROC_STATUS_LEN, "/proc/%d/status", pid);
        if (ret < 0 || ret >= __PROC_STATUS_LEN)
@@ -1845,14 +1845,20 @@ bool task_blocking_signal(pid_t pid, int signal)
                return bret;
 
        while (getline(&line, &n, f) != -1) {
-               if (strncmp(line, "SigBlk:\t", 8))
+               char *numstr;
+
+               if (strncmp(line, "SigBlk:", 7))
                        continue;
 
-               if (sscanf(line + 8, "%lx", &sigblk) != 1)
+               numstr = lxc_trim_whitespace_in_place(line + 7);
+               ret = lxc_safe_uint64(numstr, &sigblk, 16);
+               if (ret < 0)
                        goto out;
+
+               break;
        }
 
-       if (sigblk & (1LU << (signal - 1)))
+       if (sigblk & (one << (signal - 1)))
                bret = true;
 
 out:
@@ -1969,6 +1975,29 @@ int lxc_safe_ulong(const char *numstr, unsigned long *converted)
        return 0;
 }
 
+int lxc_safe_uint64(const char *numstr, uint64_t *converted, int base)
+{
+       char *err = NULL;
+       uint64_t u;
+
+       while (isspace(*numstr))
+               numstr++;
+
+       if (*numstr == '-')
+               return -EINVAL;
+
+       errno = 0;
+       u = strtoull(numstr, &err, base);
+       if (errno == ERANGE && u == ULLONG_MAX)
+               return -ERANGE;
+
+       if (err == numstr || *err != '\0')
+               return -EINVAL;
+
+       *converted = u;
+       return 0;
+}
+
 int lxc_safe_int(const char *numstr, int *converted)
 {
        char *err = NULL;
@@ -2073,9 +2102,6 @@ static int lxc_get_unused_loop_dev_legacy(char *loop_name)
                return -1;
 
        while ((dp = readdir(dir))) {
-               if (!dp)
-                       break;
-
                if (strncmp(dp->d_name, "loop", 4) != 0)
                        continue;
 
@@ -2221,7 +2247,7 @@ int run_command(char *buf, size_t buf_size, int (*child_fn)(void *), void *args)
        int ret, fret, pipefd[2];
        ssize_t bytes;
 
-       /* Make sure our callers do not receive unitialized memory. */
+       /* Make sure our callers do not receive uninitialized memory. */
        if (buf_size > 0 && buf)
                buf[0] = '\0';
 
@@ -2230,7 +2256,7 @@ int run_command(char *buf, size_t buf_size, int (*child_fn)(void *), void *args)
                return -1;
        }
 
-       child = fork();
+       child = lxc_raw_clone(0);
        if (child < 0) {
                close(pipefd[0]);
                close(pipefd[1]);
@@ -2254,13 +2280,13 @@ int run_command(char *buf, size_t buf_size, int (*child_fn)(void *), void *args)
 
                if (ret < 0) {
                        SYSERROR("failed to duplicate std{err,out} file descriptor");
-                       exit(EXIT_FAILURE);
+                       _exit(EXIT_FAILURE);
                }
 
                /* Does not return. */
                child_fn(args);
                ERROR("failed to exec command");
-               exit(EXIT_FAILURE);
+               _exit(EXIT_FAILURE);
        }
 
        /* close the write-end of the pipe */
@@ -2302,6 +2328,33 @@ char *must_make_path(const char *first, ...)
        return dest;
 }
 
+char *must_append_path(char *first, ...)
+{
+       char *cur;
+       size_t full_len;
+       va_list args;
+       char *dest = first;
+
+       full_len = strlen(first);
+       va_start(args, first);
+       while ((cur = va_arg(args, char *)) != NULL) {
+               full_len += strlen(cur);
+
+               if (cur[0] != '/')
+                       full_len++;
+
+               dest = must_realloc(dest, full_len + 1);
+
+               if (cur[0] != '/')
+                       strcat(dest, "/");
+
+               strcat(dest, cur);
+       }
+       va_end(args);
+
+       return dest;
+}
+
 char *must_copy_string(const char *entry)
 {
        char *ret;
@@ -2372,8 +2425,11 @@ bool lxc_nic_exists(char *nic)
 int lxc_make_tmpfile(char *template, bool rm)
 {
        int fd, ret;
+       mode_t msk;
 
+       msk = umask(0022);
        fd = mkstemp(template);
+       umask(msk);
        if (fd < 0)
                return -1;
 
@@ -2389,17 +2445,6 @@ int lxc_make_tmpfile(char *template, bool rm)
        return fd;
 }
 
-uint64_t lxc_getpagesize(void)
-{
-       int64_t pgsz;
-
-       pgsz = sysconf(_SC_PAGESIZE);
-       if (pgsz <= 0)
-               pgsz = 1 << 12;
-
-       return pgsz;
-}
-
 int parse_byte_size_string(const char *s, int64_t *converted)
 {
        int ret, suffix_len;
@@ -2407,12 +2452,12 @@ int parse_byte_size_string(const char *s, int64_t *converted)
        int64_t mltpl, overflow;
        char *end;
        char dup[LXC_NUMSTRLEN64 + 2];
-       char suffix[3];
+       char suffix[3] = {0};
 
        if (!s || !strcmp(s, ""))
                return -EINVAL;
 
-       end = stpncpy(dup, s, sizeof(dup));
+       end = stpncpy(dup, s, sizeof(dup) - 1);
        if (*end != '\0')
                return -EINVAL;
 
@@ -2423,15 +2468,11 @@ int parse_byte_size_string(const char *s, int64_t *converted)
        else
                return -EINVAL;
 
-       if ((end - 2) == dup && !isdigit(*(end - 2)))
+       if (suffix_len > 0 && (end - 2) == dup && !isdigit(*(end - 2)))
                return -EINVAL;
 
-       if (isalpha(*(end - 2))) {
-               if (suffix_len == 1)
-                       suffix_len++;
-               else
-                       return -EINVAL;
-       }
+       if (suffix_len > 0 && isalpha(*(end - 2)))
+               suffix_len++;
 
        if (suffix_len > 0) {
                memcpy(suffix, end - suffix_len, suffix_len);
@@ -2449,11 +2490,11 @@ int parse_byte_size_string(const char *s, int64_t *converted)
                return 0;
        }
 
-       if (!strcmp(suffix, "kB"))
+       if (strcasecmp(suffix, "KB") == 0)
                mltpl = 1024;
-       else if (!strcmp(suffix, "MB"))
+       else if (strcasecmp(suffix, "MB") == 0)
                mltpl = 1024 * 1024;
-       else if (!strcmp(suffix, "GB"))
+       else if (strcasecmp(suffix, "GB") == 0)
                mltpl = 1024 * 1024 * 1024;
        else
                return -EINVAL;
@@ -2483,3 +2524,40 @@ uint64_t lxc_find_next_power2(uint64_t n)
        n = n << 1;
        return n;
 }
+
+int lxc_set_death_signal(int signal)
+{
+       int ret;
+       pid_t ppid;
+
+       ret = prctl(PR_SET_PDEATHSIG, signal, 0, 0, 0);
+
+       /* Check whether we have been orphaned. */
+       ppid = (pid_t)syscall(SYS_getppid);
+       if (ppid == 1) {
+               pid_t self;
+
+               self = lxc_raw_getpid();
+               ret = kill(self, SIGKILL);
+               if (ret < 0)
+                       return -1;
+       }
+
+       if (ret < 0) {
+               SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal);
+               return -1;
+       }
+
+       return 0;
+}
+
+void remove_trailing_newlines(char *l)
+{
+       char *p = l;
+
+       while (*p)
+               p++;
+
+       while (--p >= l && *p == '\n')
+               *p = '\0';
+}