HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/basic/fileio.c

59,136 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 892cdefdba09f06e121da850e52e91d2d6afd792

Lines 1001–1767 of 1,767

        const char *p;
        int flags;
 
        assert(mode);
 
        if ((p = startswith(mode, "r+")))
                flags = O_RDWR;
        else if ((p = startswith(mode, "r")))
                flags = O_RDONLY;
        else if ((p = startswith(mode, "w+")))
                flags = O_RDWR|O_CREAT|O_TRUNC;
        else if ((p = startswith(mode, "w")))
                flags = O_WRONLY|O_CREAT|O_TRUNC;
        else if ((p = startswith(mode, "a+")))
                flags = O_RDWR|O_CREAT|O_APPEND;
        else if ((p = startswith(mode, "a")))
                flags = O_WRONLY|O_CREAT|O_APPEND;
        else
                return -EINVAL;
 
        for (; *p != 0; p++) {
 
                switch (*p) {
 
                case 'e':
                        flags |= O_CLOEXEC;
                        break;
 
                case 'x':
                        flags |= O_EXCL;
                        break;
 
                case 'm':
                        /* ignore this here, fdopen() might care later though */
                        break;
 
                case 'c': /* not sure what to do about this one */
                default:
                        return -EINVAL;
                }
        }
 
        return flags;
}
 
static int xfopenat_regular(int dir_fd, const char *path, const char *mode, int open_flags, FILE **ret) {
        FILE *f;
 
        /* A combination of fopen() with openat() */
 
        assert(wildcard_fd_is_valid(dir_fd));
        assert(mode);
        assert(ret);
 
        if (dir_fd == AT_FDCWD && path && open_flags == 0)
                f = fopen(path, mode);
        else if (dir_fd == XAT_FDROOT && path && open_flags == 0) {
                _cleanup_free_ char *j = strjoin("/", path);
                if (!j)
                        return -ENOMEM;
 
                f = fopen(j, mode);
        } else {
                _cleanup_close_ int fd = -EBADF;
                int mode_flags;
 
                mode_flags = fopen_mode_to_flags(mode);
                if (mode_flags < 0)
                        return mode_flags;
 
                if (path) {
                        fd = openat(dir_fd, path, mode_flags | open_flags);
                        if (fd < 0)
                                return -errno;
                } else {
                        if (dir_fd == AT_FDCWD)
                                return -EBADF;
 
                        fd = fd_reopen(dir_fd, (mode_flags | open_flags) & ~O_NOFOLLOW);
                        if (fd < 0)
                                return fd;
                }
 
                f = take_fdopen(&fd, mode);
        }
        if (!f)
                return -errno;
 
        *ret = f;
        return 0;
}
 
static int xfopenat_unix_socket(int dir_fd, const char *path, const char *bind_name, FILE **ret) {
        _cleanup_close_ int sk = -EBADF;
        FILE *f;
        int r;
 
        assert(wildcard_fd_is_valid(dir_fd));
        assert(ret);
 
        sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
        if (sk < 0)
                return -errno;
 
        if (bind_name) {
                /* If the caller specified a socket name to bind to, do so before connecting. This is
                 * useful to communicate some minor, short meta-information token from the client to
                 * the server. */
                union sockaddr_union bsa;
 
                r = sockaddr_un_set_path(&bsa.un, bind_name);
                if (r < 0)
                        return r;
 
                if (bind(sk, &bsa.sa, r) < 0)
                        return -errno;
        }
 
        r = connect_unix_path(sk, dir_fd, path);
        if (r < 0)
                return r;
 
        if (shutdown(sk, SHUT_WR) < 0)
                return -errno;
 
        f = take_fdopen(&sk, "r");
        if (!f)
                return -errno;
 
        *ret = f;
        return 0;
}
 
int xfopenat_full(
                int dir_fd,
                const char *path,
                const char *mode,
                int open_flags,
                XfopenFlags flags,
                const char *bind_name,
                FILE **ret) {
 
        FILE *f = NULL;  /* avoid false maybe-uninitialized warning */
        int r;
 
        assert(wildcard_fd_is_valid(dir_fd));
        assert(mode);
        assert(ret);
 
        r = xfopenat_regular(dir_fd, path, mode, open_flags, &f);
        if (r == -ENXIO && FLAGS_SET(flags, XFOPEN_SOCKET)) {
                /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
                r = xfopenat_unix_socket(dir_fd, path, bind_name, &f);
                if (IN_SET(r, -ENOTSOCK, -EINVAL))
                        return -ENXIO; /* propagate original error if this is not a socket after all */
        }
        if (r < 0)
                return r;
 
        if (FLAGS_SET(flags, XFOPEN_UNLOCKED))
                (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
 
        *ret = f;
        return 0;
}
 
int fdopen_independent(int fd, const char *mode, FILE **ret) {
        _cleanup_close_ int copy_fd = -EBADF;
        _cleanup_fclose_ FILE *f = NULL;
        int mode_flags;
 
        assert(fd >= 0);
        assert(mode);
        assert(ret);
 
        /* A combination of fdopen() + fd_reopen(). i.e. reopens the inode the specified fd points to and
         * returns a FILE* for it */
 
        mode_flags = fopen_mode_to_flags(mode);
        if (mode_flags < 0)
                return mode_flags;
 
        /* Flags returned by fopen_mode_to_flags might contain O_CREAT, but it doesn't make sense for fd_reopen
         * since we're working on an existing fd anyway. Let's drop it here to avoid triggering assertion. */
        copy_fd = fd_reopen(fd, mode_flags & ~O_CREAT);
        if (copy_fd < 0)
                return copy_fd;
 
        f = take_fdopen(&copy_fd, mode);
        if (!f)
                return -errno;
 
        *ret = TAKE_PTR(f);
        return 0;
}
 
static int search_and_open_internal(
                const char *path,
                int mode,            /* if ret_fd is NULL this is an [FRWX]_OK mode for access(), otherwise an open mode for open() */
                const char *root,
                char **search,
                int *ret_fd,
                char **ret_path) {
 
        int r;
 
        assert(!ret_fd || !FLAGS_SET(mode, O_CREAT)); /* We don't support O_CREAT for this */
        assert(path);
 
        if (path_is_absolute(path)) {
                _cleanup_close_ int fd = -EBADF;
 
                if (ret_fd)
                        /* We only specify 0777 here to appease static analyzers, it's never used since we
                         * don't support O_CREAT here */
                        r = fd = RET_NERRNO(open(path, mode, 0777));
                else
                        r = RET_NERRNO(access(path, mode));
                if (r < 0)
                        return r;
 
                if (ret_path) {
                        r = path_simplify_alloc(path, ret_path);
                        if (r < 0)
                                return r;
                }
 
                if (ret_fd)
                        *ret_fd = TAKE_FD(fd);
 
                return 0;
        }
 
        if (!path_strv_resolve_uniq(search, root))
                return -ENOMEM;
 
        STRV_FOREACH(i, search) {
                _cleanup_close_ int fd = -EBADF;
                _cleanup_free_ char *p = NULL;
 
                p = path_join(root, *i, path);
                if (!p)
                        return -ENOMEM;
 
                if (ret_fd)
                        /* as above, 0777 is static analyzer appeasement */
                        r = fd = RET_NERRNO(open(p, mode, 0777));
                else
                        r = RET_NERRNO(access(p, F_OK));
                if (r >= 0) {
                        if (ret_path)
                                *ret_path = path_simplify(TAKE_PTR(p));
 
                        if (ret_fd)
                                *ret_fd = TAKE_FD(fd);
 
                        return 0;
                }
                if (r != -ENOENT)
                        return r;
        }
 
        return -ENOENT;
}
 
int search_and_open(
                const char *path,
                int mode,
                const char *root,
                char **search,
                int *ret_fd,
                char **ret_path) {
 
        _cleanup_strv_free_ char **copy = NULL;
 
        assert(path);
 
        copy = strv_copy(search);
        if (!copy)
                return -ENOMEM;
 
        return search_and_open_internal(path, mode, root, copy, ret_fd, ret_path);
}
 
static int search_and_fopen_internal(
                const char *path,
                const char *mode,
                const char *root,
                char **search,
                FILE **ret_file,
                char **ret_path) {
 
        _cleanup_free_ char *found_path = NULL;
        _cleanup_close_ int fd = -EBADF;
        int r;
 
        assert(path);
        assert(mode || !ret_file);
 
        r = search_and_open_internal(
                        path,
                        mode ? fopen_mode_to_flags(mode) : 0,
                        root,
                        search,
                        ret_file ? &fd : NULL,
                        ret_path ? &found_path : NULL);
        if (r < 0)
                return r;
 
        if (ret_file) {
                FILE *f = take_fdopen(&fd, mode);
                if (!f)
                        return -errno;
 
                *ret_file = f;
        }
 
        if (ret_path)
                *ret_path = TAKE_PTR(found_path);
 
        return 0;
}
 
int search_and_fopen(
                const char *path,
                const char *mode,
                const char *root,
                const char **search,
                FILE **ret_file,
                char **ret_path) {
 
        _cleanup_strv_free_ char **copy = NULL;
 
        assert(path);
        assert(mode || !ret_file);
 
        copy = strv_copy((char**) search);
        if (!copy)
                return -ENOMEM;
 
        return search_and_fopen_internal(path, mode, root, copy, ret_file, ret_path);
}
 
int search_and_fopen_nulstr(
                const char *path,
                const char *mode,
                const char *root,
                const char *search,
                FILE **ret_file,
                char **ret_path) {
 
        _cleanup_strv_free_ char **l = NULL;
 
        assert(path);
        assert(mode || !ret_file);
 
        l = strv_split_nulstr(search);
        if (!l)
                return -ENOMEM;
 
        return search_and_fopen_internal(path, mode, root, l, ret_file, ret_path);
}
 
int fflush_and_check(FILE *f) {
        assert(f);
 
        errno = 0;
        fflush(f);
 
        if (ferror(f))
                return errno_or_else(EIO);
 
        return 0;
}
 
int fflush_sync_and_check(FILE *f) {
        int r, fd;
 
        assert(f);
 
        r = fflush_and_check(f);
        if (r < 0)
                return r;
 
        /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
         * assume that in that case we need no explicit syncing */
        fd = fileno(f);
        if (fd < 0)
                return 0;
 
        r = fsync_full(fd);
        if (r < 0)
                return r;
 
        return 0;
}
 
int write_timestamp_file_atomic(const char *fn, usec_t n) {
        char ln[DECIMAL_STR_MAX(n)+2];
 
        /* Creates a "timestamp" file, that contains nothing but a
         * usec_t timestamp, formatted in ASCII. */
 
        if (!timestamp_is_set(n))
                return -ERANGE;
 
        xsprintf(ln, USEC_FMT "\n", n);
 
        return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
}
 
int read_timestamp_file(const char *fn, usec_t *ret) {
        _cleanup_free_ char *ln = NULL;
        uint64_t t;
        int r;
 
        assert(ret);
 
        r = read_one_line_file(fn, &ln);
        if (r < 0)
                return r;
 
        r = safe_atou64(ln, &t);
        if (r < 0)
                return r;
 
        if (!timestamp_is_set(t))
                return -ERANGE;
 
        *ret = (usec_t) t;
        return 0;
}
 
int fputs_with_separator(FILE *f, const char *s, const char *separator, bool *space) {
        assert(s);
        assert(space);
 
        /* Outputs the specified string with fputs(), but optionally prefixes it with a separator.
         * The *space parameter when specified shall initially point to a boolean variable initialized
         * to false. It is set to true after the first invocation. This call is supposed to be use in loops,
         * where a separator shall be inserted between each element, but not before the first one. */
 
        if (!f)
                f = stdout;
 
        if (!separator)
                separator = " ";
 
        if (*space)
                if (fputs(separator, f) < 0)
                        return -EIO;
 
        *space = true;
 
        if (fputs(s, f) < 0)
                return -EIO;
 
        return 0;
}
 
int fputs_with_newline(FILE *f, const char *s) {
 
        /* This is like fputs() but outputs a trailing newline char, but only if the string isn't empty
         * and doesn't end in a newline already. Returns 0 in case we didn't append a newline, > 0 otherwise. */
 
        if (isempty(s))
                return 0;
 
        if (!f)
                f = stdout;
 
        if (fputs(s, f) < 0)
                return -EIO;
 
        if (endswith(s, "\n"))
                return 0;
 
        if (fputc('\n', f) < 0)
                return -EIO;
 
        return 1;
}
 
/* A bitmask of the EOL markers we know */
typedef enum EndOfLineMarker {
        EOL_NONE     = 0,
        EOL_ZERO     = 1 << 0,  /* \0 (aka NUL) */
        EOL_TEN      = 1 << 1,  /* \n (aka NL, aka LF)  */
        EOL_THIRTEEN = 1 << 2,  /* \r (aka CR)  */
} EndOfLineMarker;
 
static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
 
        if (!FLAGS_SET(flags, READ_LINE_ONLY_NUL)) {
                if (c == '\n')
                        return EOL_TEN;
                if (c == '\r')
                        return EOL_THIRTEEN;
        }
 
        if (c == '\0')
                return EOL_ZERO;
 
        return EOL_NONE;
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
 
int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
        _cleanup_free_ char *buffer = NULL;
        size_t n = 0, count = 0;
        int r;
 
        assert(f);
 
        /* Something like a bounded version of getline().
         *
         * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
         * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
         * endings:
         *
         *     • \n        (UNIX)
         *     • \r        (old MacOS)
         *     • \0        (C strings)
         *     • \n\0
         *     • \r\0
         *     • \r\n      (Windows)
         *     • \n\r
         *     • \r\n\0
         *     • \n\r\0
         *
         * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
         * the number of characters in the returned string). When EOF is hit, 0 is returned.
         *
         * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
         * delimiters. If the limit is hit we fail and return -ENOBUFS.
         *
         * If a line shall be skipped ret may be initialized as NULL. */
 
        if (ret) {
                if (!GREEDY_REALLOC(buffer, 1))
                        return -ENOMEM;
        }
 
        {
                _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
                EndOfLineMarker previous_eol = EOL_NONE;
                flockfile(f);
 
                for (;;) {
                        EndOfLineMarker eol;
                        char c;
 
                        if (n >= limit)
                                return -ENOBUFS;
 
                        if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
                                return -ENOBUFS;
 
                        r = safe_fgetc(f, &c);
                        if (r < 0)
                                return r;
                        if (r == 0) /* EOF is definitely EOL */
                                break;
 
                        eol = categorize_eol(c, flags);
 
                        if (FLAGS_SET(previous_eol, EOL_ZERO) ||
                            (eol == EOL_NONE && previous_eol != EOL_NONE) ||
                            (eol != EOL_NONE && (previous_eol & eol) != 0)) {
                                /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
                                 * EOL marker has been seen right before?  In either of these three cases we are
                                 * done. But first, let's put this character back in the queue. (Note that we have to
                                 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
                                 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
                                 * pass a negative value here. That said, to complicate things further ungetc() is
                                 * actually happy with most negative characters and implicitly casts them back to
                                 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
                                 * godawful API!) */
                                assert_se(ungetc((unsigned char) c, f) != EOF);
                                break;
                        }
 
                        count++;
 
                        if (eol != EOL_NONE) {
                                /* If we are on a tty, we can't shouldn't wait for more input, because that
                                 * generally means waiting for the user, interactively. In the case of a TTY
                                 * we expect only \n as the single EOL marker, so we are in the lucky
                                 * position that there is no need to wait. We check this condition last, to
                                 * avoid isatty() check if not necessary. */
 
                                if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
                                        int fd;
 
                                        fd = fileno(f);
                                        if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
                                                     * and don't call isatty() on an invalid fd */
                                                flags |= READ_LINE_NOT_A_TTY;
                                        else
                                                flags |= isatty_safe(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
                                }
                                if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
                                        break;
                        }
 
                        if (eol != EOL_NONE) {
                                previous_eol |= eol;
                                continue;
                        }
 
                        if (ret) {
                                if (!GREEDY_REALLOC(buffer, n + 2))
                                        return -ENOMEM;
 
                                buffer[n] = c;
                        }
 
                        n++;
                }
        }
 
        if (ret) {
                buffer[n] = 0;
 
                *ret = TAKE_PTR(buffer);
        }
 
        return (int) count;
}
 
int read_stripped_line(FILE *f, size_t limit, char **ret) {
        _cleanup_free_ char *s = NULL;
        int r, k;
 
        assert(f);
 
        r = read_line(f, limit, ret ? &s : NULL);
        if (r < 0)
                return r;
 
        if (ret) {
                const char *p = strstrip(s);
                if (p == s)
                        *ret = TAKE_PTR(s);
                else {
                        k = strdup_to(ret, p);
                        if (k < 0)
                                return k;
                }
        }
 
        return r > 0;          /* Return 1 if something was read. */
}
 
int safe_fgetc(FILE *f, char *ret) {
        int k;
 
        assert(f);
 
        /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
         * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
         * has. */
 
        errno = 0;
        k = fgetc(f);
        if (k == EOF) {
                if (ferror(f))
                        return errno_or_else(EIO);
 
                if (ret)
                        *ret = 0;
 
                return 0;
        }
 
        if (ret)
                *ret = k;
 
        return 1;
}
 
int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
        struct stat _st;
 
        if (!filename)
                return 0;
 
        if (!st) {
                if (stat(filename, &_st) < 0)
                        return -errno;
                st = &_st;
        }
 
        if ((st->st_mode & S_IRWXO) == 0)
                return 0;
 
        if (unit)
                log_syntax(unit, LOG_WARNING, filename, line, 0,
                           "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
                           filename, st->st_mode & 07777);
        else
                log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
                            filename, st->st_mode & 07777);
        return 0;
}
 
int write_data_file_atomic_at(
                int dir_fd,
                const char *path,
                const struct iovec *iovec,
                WriteDataFileFlags flags) {
 
        int r;
 
        assert(wildcard_fd_is_valid(dir_fd));
 
        /* This is a cousin of write_string_file_atomic(), but operates with arbitrary struct iovec binary
         * data (rather than strings), works without FILE* streams, and does direct syscalls instead. */
 
        _cleanup_free_ char *dn = NULL, *fn = NULL;
        r = path_split_prefix_filename(path, &dn, &fn);
        if (IN_SET(r, -EADDRNOTAVAIL, O_DIRECTORY))
                return -EISDIR; /* path refers to "." or "/" (which are dirs, which we cannot write), or is suffixed with "/" */
        if (r < 0)
                return r;
 
        _cleanup_close_ int mfd = -EBADF;
        if (dn) {
                /* If there's a directory component, readjust our position */
                r = chaseat(XAT_FDROOT,
                            dir_fd,
                            dn,
                            FLAGS_SET(flags, WRITE_DATA_FILE_MKDIR_0755) ? CHASE_MKDIR_0755 : 0,
                            /* ret_path= */ NULL,
                            &mfd);
                if (r < 0)
                        return r;
 
                dir_fd = mfd;
        }
 
        _cleanup_free_ char *t = NULL;
        _cleanup_close_ int fd = open_tmpfile_linkable_at(dir_fd, fn, O_WRONLY|O_CLOEXEC, &t);
        if (fd < 0)
                return fd;
 
        CLEANUP_TMPFILE_AT(dir_fd, t);
 
        if (iovec_is_set(iovec)) {
                r = loop_write(fd, iovec->iov_base, iovec->iov_len);
                if (r < 0)
                        return r;
        }
 
        r = fchmod_umask(fd, FLAGS_SET(flags, WRITE_DATA_FILE_MODE_0400) ? 0400 : 0644);
        if (r < 0)
                return r;
 
        r = link_tmpfile_at(fd, dir_fd, t, fn, LINK_TMPFILE_REPLACE);
        if (r < 0)
                return r;
 
        t = mfree(t); /* disarm CLEANUP_TMPFILE_AT */
        return 0;
}