tempfile.c 8.32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*
 * State diagram and cleanup
 * -------------------------
 *
 * If the program exits while a temporary file is active, we want to
 * make sure that we remove it. This is done by remembering the active
 * temporary files in a linked list, `tempfile_list`. An `atexit(3)`
 * handler and a signal handler are registered, to clean up any active
 * temporary files.
 *
 * Because the signal handler can run at any time, `tempfile_list` and
 * the `tempfile` objects that comprise it must be kept in
 * self-consistent states at all times.
 *
 * The possible states of a `tempfile` object are as follows:
 *
 * - Uninitialized. In this state the object's `on_list` field must be
 *   zero but the rest of its contents need not be initialized. As
 *   soon as the object is used in any way, it is irrevocably
 *   registered in `tempfile_list`, and `on_list` is set.
 *
 * - Active, file open (after `create_tempfile()` or
 *   `reopen_tempfile()`). In this state:
 *
 *   - the temporary file exists
 *   - `active` is set
 *   - `filename` holds the filename of the temporary file
 *   - `fd` holds a file descriptor open for writing to it
 *   - `fp` holds a pointer to an open `FILE` object if and only if
 *     `fdopen_tempfile()` has been called on the object
 *   - `owner` holds the PID of the process that created the file
 *
33
 * - Active, file closed (after `close_tempfile_gently()`). Same
34 35 36
 *   as the previous state, except that the temporary file is closed,
 *   `fd` is -1, and `fp` is `NULL`.
 *
37 38
 * - Inactive (after `delete_tempfile()`, `rename_tempfile()`, or a
 *   failed attempt to create a temporary file). In this state:
39 40 41 42 43 44
 *
 *   - `active` is unset
 *   - `filename` is empty (usually, though there are transitory
 *     states in which this condition doesn't hold). Client code should
 *     *not* rely on the filename being empty in this state.
 *   - `fd` is -1 and `fp` is `NULL`
45
 *   - the object is removed from `tempfile_list` (but could be used again)
46 47 48 49 50 51 52 53 54 55 56
 *
 * A temporary file is owned by the process that created it. The
 * `tempfile` has an `owner` field that records the owner's PID. This
 * field is used to prevent a forked process from deleting a temporary
 * file created by its parent.
 */

#include "cache.h"
#include "tempfile.h"
#include "sigchain.h"

57
static VOLATILE_LIST_HEAD(tempfile_list);
58

59
static void remove_tempfiles(int in_signal_handler)
60 61
{
	pid_t me = getpid();
62 63 64 65
	volatile struct volatile_list_head *pos;

	list_for_each(pos, &tempfile_list) {
		struct tempfile *p = list_entry(pos, struct tempfile, list);
66

67 68 69 70 71 72 73 74 75 76 77 78
		if (!is_tempfile_active(p) || p->owner != me)
			continue;

		if (p->fd >= 0)
			close(p->fd);

		if (in_signal_handler)
			unlink(p->filename.buf);
		else
			unlink_or_warn(p->filename.buf);

		p->active = 0;
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
	}
}

static void remove_tempfiles_on_exit(void)
{
	remove_tempfiles(0);
}

static void remove_tempfiles_on_signal(int signo)
{
	remove_tempfiles(1);
	sigchain_pop(signo);
	raise(signo);
}

94
static struct tempfile *new_tempfile(void)
95
{
96
	struct tempfile *tempfile = xmalloc(sizeof(*tempfile));
97 98 99 100 101 102
	tempfile->fd = -1;
	tempfile->fp = NULL;
	tempfile->active = 0;
	tempfile->owner = 0;
	INIT_LIST_HEAD(&tempfile->list);
	strbuf_init(&tempfile->filename, 0);
103
	return tempfile;
104 105
}

106 107
static void activate_tempfile(struct tempfile *tempfile)
{
108 109 110 111 112 113 114 115 116 117 118 119
	static int initialized;

	if (is_tempfile_active(tempfile))
		BUG("activate_tempfile called for active object");

	if (!initialized) {
		sigchain_push_common(remove_tempfiles_on_signal);
		atexit(remove_tempfiles_on_exit);
		initialized = 1;
	}

	volatile_list_add(&tempfile->list, &tempfile_list);
120 121 122 123
	tempfile->owner = getpid();
	tempfile->active = 1;
}

124 125 126
static void deactivate_tempfile(struct tempfile *tempfile)
{
	tempfile->active = 0;
127
	strbuf_release(&tempfile->filename);
128
	volatile_list_del(&tempfile->list);
129
	free(tempfile);
130 131
}

132
/* Make sure errno contains a meaningful value on error */
133
struct tempfile *create_tempfile(const char *path)
134
{
135
	struct tempfile *tempfile = new_tempfile();
136 137

	strbuf_add_absolute_path(&tempfile->filename, path);
138 139 140 141 142 143
	tempfile->fd = open(tempfile->filename.buf,
			    O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0666);
	if (O_CLOEXEC && tempfile->fd < 0 && errno == EINVAL)
		/* Try again w/o O_CLOEXEC: the kernel might not support it */
		tempfile->fd = open(tempfile->filename.buf,
				    O_RDWR | O_CREAT | O_EXCL, 0666);
144
	if (tempfile->fd < 0) {
145
		deactivate_tempfile(tempfile);
146
		return NULL;
147
	}
148
	activate_tempfile(tempfile);
149 150 151
	if (adjust_shared_perm(tempfile->filename.buf)) {
		int save_errno = errno;
		error("cannot fix permission bits on %s", tempfile->filename.buf);
152
		delete_tempfile(&tempfile);
153
		errno = save_errno;
154
		return NULL;
155
	}
156 157

	return tempfile;
158 159
}

160
struct tempfile *register_tempfile(const char *path)
161
{
162
	struct tempfile *tempfile = new_tempfile();
163
	strbuf_add_absolute_path(&tempfile->filename, path);
164
	activate_tempfile(tempfile);
165
	return tempfile;
166 167
}

168
struct tempfile *mks_tempfile_sm(const char *filename_template, int suffixlen, int mode)
169
{
170
	struct tempfile *tempfile = new_tempfile();
171

172
	strbuf_add_absolute_path(&tempfile->filename, filename_template);
173 174
	tempfile->fd = git_mkstemps_mode(tempfile->filename.buf, suffixlen, mode);
	if (tempfile->fd < 0) {
175
		deactivate_tempfile(tempfile);
176
		return NULL;
177
	}
178
	activate_tempfile(tempfile);
179
	return tempfile;
180 181
}

182
struct tempfile *mks_tempfile_tsm(const char *filename_template, int suffixlen, int mode)
183
{
184
	struct tempfile *tempfile = new_tempfile();
185 186 187 188 189 190
	const char *tmpdir;

	tmpdir = getenv("TMPDIR");
	if (!tmpdir)
		tmpdir = "/tmp";

191
	strbuf_addf(&tempfile->filename, "%s/%s", tmpdir, filename_template);
192 193
	tempfile->fd = git_mkstemps_mode(tempfile->filename.buf, suffixlen, mode);
	if (tempfile->fd < 0) {
194
		deactivate_tempfile(tempfile);
195
		return NULL;
196
	}
197
	activate_tempfile(tempfile);
198
	return tempfile;
199 200
}

201
struct tempfile *xmks_tempfile_m(const char *filename_template, int mode)
202
{
203
	struct tempfile *tempfile;
204 205
	struct strbuf full_template = STRBUF_INIT;

206
	strbuf_add_absolute_path(&full_template, filename_template);
207 208
	tempfile = mks_tempfile_m(full_template.buf, mode);
	if (!tempfile)
209 210 211 212
		die_errno("Unable to create temporary file '%s'",
			  full_template.buf);

	strbuf_release(&full_template);
213
	return tempfile;
214 215
}

216 217
FILE *fdopen_tempfile(struct tempfile *tempfile, const char *mode)
{
218
	if (!is_tempfile_active(tempfile))
219
		BUG("fdopen_tempfile() called for inactive object");
220
	if (tempfile->fp)
221
		BUG("fdopen_tempfile() called for open object");
222 223 224 225 226 227 228

	tempfile->fp = fdopen(tempfile->fd, mode);
	return tempfile->fp;
}

const char *get_tempfile_path(struct tempfile *tempfile)
{
229
	if (!is_tempfile_active(tempfile))
230
		BUG("get_tempfile_path() called for inactive object");
231 232 233 234 235
	return tempfile->filename.buf;
}

int get_tempfile_fd(struct tempfile *tempfile)
{
236
	if (!is_tempfile_active(tempfile))
237
		BUG("get_tempfile_fd() called for inactive object");
238 239 240 241 242
	return tempfile->fd;
}

FILE *get_tempfile_fp(struct tempfile *tempfile)
{
243
	if (!is_tempfile_active(tempfile))
244
		BUG("get_tempfile_fp() called for inactive object");
245 246 247
	return tempfile->fp;
}

248
int close_tempfile_gently(struct tempfile *tempfile)
249
{
250 251
	int fd;
	FILE *fp;
252 253
	int err;

254
	if (!is_tempfile_active(tempfile) || tempfile->fd < 0)
255 256
		return 0;

257 258
	fd = tempfile->fd;
	fp = tempfile->fp;
259 260 261
	tempfile->fd = -1;
	if (fp) {
		tempfile->fp = NULL;
262 263 264 265 266 267 268
		if (ferror(fp)) {
			err = -1;
			if (!fclose(fp))
				errno = EIO;
		} else {
			err = fclose(fp);
		}
269 270 271 272
	} else {
		err = close(fd);
	}

273
	return err ? -1 : 0;
274 275 276 277
}

int reopen_tempfile(struct tempfile *tempfile)
{
278
	if (!is_tempfile_active(tempfile))
279
		BUG("reopen_tempfile called for an inactive object");
280
	if (0 <= tempfile->fd)
281
		BUG("reopen_tempfile called for an open object");
282
	tempfile->fd = open(tempfile->filename.buf, O_WRONLY|O_TRUNC);
283 284 285
	return tempfile->fd;
}

286
int rename_tempfile(struct tempfile **tempfile_p, const char *path)
287
{
288 289
	struct tempfile *tempfile = *tempfile_p;

290
	if (!is_tempfile_active(tempfile))
291
		BUG("rename_tempfile called for inactive object");
292

293
	if (close_tempfile_gently(tempfile)) {
294
		delete_tempfile(tempfile_p);
295
		return -1;
296
	}
297 298 299

	if (rename(tempfile->filename.buf, path)) {
		int save_errno = errno;
300
		delete_tempfile(tempfile_p);
301 302 303 304
		errno = save_errno;
		return -1;
	}

305
	deactivate_tempfile(tempfile);
306
	*tempfile_p = NULL;
307 308 309
	return 0;
}

310
void delete_tempfile(struct tempfile **tempfile_p)
311
{
312 313
	struct tempfile *tempfile = *tempfile_p;

314
	if (!is_tempfile_active(tempfile))
315 316
		return;

317 318
	close_tempfile_gently(tempfile);
	unlink_or_warn(tempfile->filename.buf);
319
	deactivate_tempfile(tempfile);
320
	*tempfile_p = NULL;
321
}