Blob


1 /*
2 * Copyright (c) 2018 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <limits.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <string.h>
21 #include <stdio.h>
23 #include "got_compat.h"
25 #include "got_opentemp.h"
26 #include "got_error.h"
28 int
29 got_opentempfd(void)
30 {
31 char name[PATH_MAX];
32 int fd;
34 if (strlcpy(name, GOT_TMPDIR_STR "/got.XXXXXXXX", sizeof(name))
35 >= sizeof(name))
36 return -1;
38 fd = mkstemp(name);
39 if (fd != -1)
40 unlink(name);
41 return fd;
42 }
44 FILE *
45 got_opentemp(void)
46 {
47 int fd;
48 FILE *f;
50 fd = got_opentempfd();
51 if (fd < 0)
52 return NULL;
54 f = fdopen(fd, "w+");
55 if (f == NULL) {
56 close(fd);
57 return NULL;
58 }
60 return f;
61 }
63 const struct got_error *
64 got_opentemp_named(char **path, FILE **outfile, const char *basepath)
65 {
66 const struct got_error *err = NULL;
67 int fd;
69 *outfile = NULL;
71 if (asprintf(path, "%s-XXXXXX", basepath) == -1) {
72 *path = NULL;
73 return got_error_from_errno("asprintf");
74 }
76 fd = mkstemp(*path);
77 if (fd == -1) {
78 err = got_error_from_errno2("mkstemp", *path);
79 free(*path);
80 *path = NULL;
81 return err;
82 }
84 *outfile = fdopen(fd, "w+");
85 if (*outfile == NULL) {
86 err = got_error_from_errno2("fdopen", *path);
87 free(*path);
88 *path = NULL;
89 }
91 return err;
92 }
94 const struct got_error *
95 got_opentemp_named_fd(char **path, int *outfd, const char *basepath)
96 {
97 const struct got_error *err = NULL;
98 int fd;
100 *outfd = -1;
102 if (asprintf(path, "%s-XXXXXX", basepath) == -1) {
103 *path = NULL;
104 return got_error_from_errno("asprintf");
107 fd = mkstemp(*path);
108 if (fd == -1) {
109 err = got_error_from_errno("mkstemp");
110 free(*path);
111 *path = NULL;
112 return err;
115 *outfd = fd;
116 return err;
119 const struct got_error *
120 got_opentemp_truncate(FILE *f)
122 if (fpurge(f) == EOF)
123 return got_error_from_errno("fpurge");
124 if (ftruncate(fileno(f), 0L) == -1)
125 return got_error_from_errno("ftruncate");
126 if (fseeko(f, 0L, SEEK_SET) == -1)
127 return got_error_from_errno("fseeko");
128 return NULL;