Debian Codegraph @

compat/mkstemp.c

raw
1 /*
2 * mkstemp.c --
3 *
4 * Source code for the "mkstemp" library routine.
5 *
6 * Copyright (c) 2009 Donal K. Fellows
7 *
8 * See the file "license.terms" for information on usage and redistribution of
9 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
10 */
11
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16
17 /*
18 *----------------------------------------------------------------------
19 *
20 * mkstemp --
21 *
22 * Create an open temporary file from a template.
23 *
24 * Results:
25 * A file descriptor, or -1 (with errno set) in the case of an error.
26 *
27 * Side effects:
28 * The template is updated to contain the real filename.
29 *
30 *----------------------------------------------------------------------
31 */
32
33 int
34 mkstemp(
35 char *template) /* Template for filename. */
36 {
37 static const char alphanumerics[] =
38 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
39 char *a, *b;
40 int fd, count, alphanumericsLen = strlen(alphanumerics); /* == 62 */
41
42 a = template + strlen(template);
43 while (a > template && *(a-1) == 'X') {
44 a--;
45 }
46
47 if (a == template) {
48 errno = ENOENT;
49 return -1;
50 }
51
52 /*
53 * We'll only try up to 10 times; after that, we're suffering from enemy
54 * action and should let the caller know.
55 */
56
57 count = 10;
58 do {
59 /*
60 * Replace the X's in the original template with random alphanumeric
61 * digits.
62 */
63
64 for (b=a ; *b ; b++) {
65 float r = rand() / ((float) RAND_MAX);
66
67 *b = alphanumerics[(int)(r * alphanumericsLen)];
68 }
69
70 /*
71 * Template is now realized; try to open (with correct options).
72 */
73
74 fd = open(template, O_RDWR|O_CREAT|O_EXCL, 0600);
75 } while (fd == -1 && errno == EEXIST && --count > 0);
76
77 return fd;
78 }