1 /* $OpenBSD: sshbuf-io.c,v 1.2 2020/01/25 23:28:06 djm Exp $ */
3 * Copyright (c) 2011 Damien Miller
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include <sys/types.h>
32 /* Load a file from a fd into a buffer */
34 sshbuf_load_fd(int fd, struct sshbuf **blobp)
44 if (fstat(fd, &st) == -1)
45 return SSH_ERR_SYSTEM_ERROR;
46 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
47 st.st_size > SSHBUF_SIZE_MAX)
48 return SSH_ERR_INVALID_FORMAT;
49 if ((blob = sshbuf_new()) == NULL)
50 return SSH_ERR_ALLOC_FAIL;
52 if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
55 r = SSH_ERR_SYSTEM_ERROR;
58 if ((r = sshbuf_put(blob, buf, len)) != 0)
60 if (sshbuf_len(blob) > SSHBUF_SIZE_MAX) {
61 r = SSH_ERR_INVALID_FORMAT;
65 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
66 st.st_size != (off_t)sshbuf_len(blob)) {
67 r = SSH_ERR_FILE_CHANGED;
72 blob = NULL; /* transferred */
75 explicit_bzero(buf, sizeof(buf));
81 sshbuf_load_file(const char *path, struct sshbuf **bufp)
86 if ((fd = open(path, O_RDONLY)) == -1)
87 return SSH_ERR_SYSTEM_ERROR;
88 if ((r = sshbuf_load_fd(fd, bufp)) != 0)
101 sshbuf_write_file(const char *path, struct sshbuf *buf)
105 if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1)
106 return SSH_ERR_SYSTEM_ERROR;
107 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(buf),
108 sshbuf_len(buf)) != sshbuf_len(buf) || close(fd) != 0) {
113 return SSH_ERR_SYSTEM_ERROR;