summaryrefslogtreecommitdiff
path: root/src/tempfile.c
blob: 6890efb5c3287dae236654862af31ca85734f7c3 (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/* -*- c-file-style: "java"; indent-tabs-mode: nil; tab-width: 4; fill-column: 78 -*-
 *
 * distcc -- A simple distributed compiler system
 *
 * Copyright (C) 2002, 2003, 2004 by Martin Pool <mbp@samba.org>
 * Copyright 2007 Google Inc.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 */


                /* "More computing sins are committed in the name of
                 * efficiency (without necessarily achieving it) than
                 * for any other single reason - including blind
                 * stupidity."  -- W.A. Wulf
                 */



#include <config.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

#include "distcc.h"
#include "trace.h"
#include "util.h"
#include "snprintf.h"
#include "exitcode.h"

#ifdef __CYGWIN32__
    #define NOGDI
    #include <windows.h>
#endif


/**
 * @file
 *
 * Routines for naming, generating and removing temporary files.
 *
 * Temporary files are stored under $TMPDIR or /tmp.
 *
 * From 2.10 on, our lock and state files are not stored in there.
 *
 * It would be nice if we could use a standard function, but I don't
 * think any of them are adequate: we need to control the extension
 * and know the filename.  tmpfile() does not give back the filename.
 * tmpnam() is insecure.  mkstemp() does not allow us to set the
 * extension.
 *
 * It sucks that there is no standard function.  The implementation
 * below is inspired by the __gen_tempname() code in glibc; hopefully
 * it will be secure on all platforms.
 *
 * We need to touch the filename before running commands on it,
 * because we cannot be sure that the compiler will create it
 * securely.
 *
 * Even with all this, we are not necessarily secure in the presence
 * of a tmpreaper if the attacker can play timing tricks.  However,
 * since we are not setuid and since there is no completely safe way
 * to write tmpreapers, this is left alone for now.
 *
 * If you're really paranoid, you should just use per-user TMPDIRs.
 *
 * @sa http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoid-race.html#TEMPORARY-FILES
 **/

/**
 * Create the directory @p path, and register it for deletion when this
 * compilation finished.  If it already exists as a directory
 * we succeed, but we don't register the directory for deletion.
 **/
int dcc_mk_tmpdir(const char *path)
{
    struct stat buf;
    int ret;

    if (stat(path, &buf) == -1) {
        if (mkdir(path, 0777) == -1) {
            return EXIT_IO_ERROR;
        }
        if ((ret = dcc_add_cleanup(path))) {
            /* bailing out */
            rmdir(path);
            return ret;
        }
    } else {
        /* we could stat the file successfully; if it's a directory,
         * all is well, but we should not it delete later, since we did
         * not make it.
         */
         if (S_ISDIR(buf.st_mode)) {
             return 0;
         } else {
             rs_log_error("mkdir '%s' failed: %s", path, strerror(errno));
             return EXIT_IO_ERROR;
         }
    }
    return 0;
}

/**
 * Create the directory @p path.  If it already exists as a directory
 * we succeed.
 **/
int dcc_mkdir(const char *path)
{
    if ((mkdir(path, 0777) == -1) && (errno != EEXIST)) {
        rs_log_error("mkdir '%s' failed: %s", path, strerror(errno));
        return EXIT_IO_ERROR;
    }

    return 0;
}


#ifndef HAVE_MKDTEMP
static char* mkdtemp(char *pattern)
{
    /* We could try this a few times if we wanted */
    char* path = mktemp(pattern);
    if (path == NULL)
        return NULL;
    if (mkdir(path, 0700) == 0)
        return path;
    return NULL;
}
#endif

/* This function creates a temporary directory, to be used for
 * all (input) files during one compilation.
 * The name of the directory is stored in @p tempdir, which is
 * malloc'ed here. The caller is responsible for freeing it.
 * The format of the directory name is <TMPTOP>/distccd_<randomnumber>
 * Returns the new temp dir in tempdir.
 */
int dcc_get_new_tmpdir(char **tempdir)
{
    int ret;
    const char *tmp_top;
    char *s;
    if ((ret = dcc_get_tmp_top(&tmp_top))) {
        return ret;
    }
    if (asprintf(&s, "%s/distccd_XXXXXX", tmp_top) == -1)
        return EXIT_OUT_OF_MEMORY;
    if ((*tempdir = mkdtemp(s)) == 0) {
        return EXIT_IO_ERROR;
    }
    if ((ret = dcc_add_cleanup(s))) {
        /* bailing out */
        rmdir(s);
        return ret;
    }
    return 0;
}

/* This function returns a directory-name, it does not end in a slash. */
int dcc_get_tmp_top(const char **p_ret)
{
#ifdef __CYGWIN32__
    int ret;

    char *s = malloc(MAXPATHLEN+1);
    int f,ln;
    GetTempPath(MAXPATHLEN+1,s);
    /* Convert slashes */
    for (f = 0, ln = strlen(s); f != ln; f++)
        if (s[f]=='\\') s[f]='/';
    /* Delete trailing slashes -- but leave one slash if s is all slashes */
    for (f = strlen(s)-1; f > 0 && s[f] == '/'; f--)
        s[f]='\0';

    if ((ret = dcc_add_cleanup(s))) {
        free(s);
        return ret;
    }
    *p_ret = s;
    return 0;
#else
    const char *d;

    d = getenv("TMPDIR");

    if (!d || d[0] == '\0') {
        *p_ret = "/tmp";
        return 0;
    } else {
        *p_ret = d;
        return 0;
    }
#endif
}

/**
 * Create the full @path. If it already exists as a directory
 * we succeed.
 */
int dcc_mk_tmp_ancestor_dirs(const char *path)
{
    char *copy = 0;
    char *p;
    int ret;

    copy = strdup(path);
    if (copy == NULL) {
        return EXIT_OUT_OF_MEMORY;
    }

    dcc_truncate_to_dirname(copy);
    if (copy[0] == '\0') {
        free(copy);
        return 0;
    }

    /* First, let's try and see if all parent directories
     * exist already */
    if ((ret = dcc_mk_tmpdir(copy)) == 0) {
        free(copy);
        return 0;
    }

    /* This is the "pessimistic" algorithm for making directories,
     * which assumes that most directories that it's asked to create
     * do not exist. It's expensive for very deep directories;
     * it tries to make all the directories from the root to that
     * dir. However, it only gets called if we tried to make a dir
     * in a directory and failed; which means we only get called
     * once per directory.
     */
    /* Body of this loop does not execute when *p=='\0';
     * therefore the very last component of the directory does not
     * get created here.
     */
    for (p = copy; *p != '\0'; ++p) {
        if (*p == '/' && p != copy) {
            *p = '\0';
            if ((ret = dcc_mk_tmpdir(copy))) {
                free(copy);
                return ret;
            }
            *p = '/';
        }
    }
    ret = dcc_mk_tmpdir(copy);
    free(copy);
    return ret;
}

/**
 * Return a static string holding DISTCC_DIR, or ~/.distcc.
 * The directory is created if it does not exist.
 **/
int dcc_get_top_dir(char **path_ret)
{
    char *env;
    static char *cached;
    int ret;

    if (cached) {
        *path_ret = cached;
        return 0;
    }

    if ((env = getenv("DISTCC_DIR"))) {
        if ((cached = strdup(env)) == NULL) {
            return EXIT_OUT_OF_MEMORY;
        } else {
            *path_ret = cached;
            return 0;
        }
    }

    if ((env = getenv("HOME")) == NULL) {
        rs_log_warning("HOME is not set; can't find distcc directory");
        return EXIT_BAD_ARGUMENTS;
    }

    if (asprintf(path_ret, "%s/.distcc", env) == -1) {
        rs_log_error("asprintf failed");
        return EXIT_OUT_OF_MEMORY;
    }

    ret = dcc_mkdir(*path_ret);
    if (ret == 0)
        cached = *path_ret;
    return ret;
}


/**
 * Return a subdirectory of the DISTCC_DIR of the given name, making
 * sure that the directory exists.
 **/
int dcc_get_subdir(const char *name,
                          char **dir_ret)
{
    int ret;
    char *topdir;

    if ((ret = dcc_get_top_dir(&topdir)))
        return ret;

    if (asprintf(dir_ret, "%s/%s", topdir, name) == -1) {
        rs_log_error("asprintf failed");
        return EXIT_OUT_OF_MEMORY;
    }

    return dcc_mkdir(*dir_ret);
}

int dcc_get_lock_dir(char **dir_ret)
{
    static char *cached;
    int ret;

    if (cached) {
        *dir_ret = cached;
        return 0;
    } else {
        ret = dcc_get_subdir("lock", dir_ret);
        if (ret == 0)
            cached = *dir_ret;
        return ret;
    }
}

int dcc_get_state_dir(char **dir_ret)
{
    static char *cached;
    int ret;

    if (cached) {
        *dir_ret = cached;
        return 0;
    } else {
        ret = dcc_get_subdir("state", dir_ret);
        if (ret == 0)
            cached = *dir_ret;
        return ret;
    }
}



/**
 * Create a file inside the temporary directory and register it for
 * later cleanup, and return its name.
 *
 * The file will be reopened later, possibly in a child.  But we know
 * that it exists with appropriately tight permissions.
 **/
int dcc_make_tmpnam(const char *prefix,
                    const char *suffix,
                    char **name_ret)
{
    char *s = NULL;
    const char *tempdir;
    int ret;
    unsigned long random_bits;
    int fd;

    if ((ret = dcc_get_tmp_top(&tempdir)))
        return ret;

    if (access(tempdir, W_OK|X_OK) == -1) {
        rs_log_error("can't use TMPDIR \"%s\": %s", tempdir, strerror(errno));
        return EXIT_IO_ERROR;
    }

    random_bits = (unsigned long) getpid() << 16;

# if HAVE_GETTIMEOFDAY
    {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        random_bits ^= tv.tv_usec << 16;
        random_bits ^= tv.tv_sec;
    }
# else
    random_bits ^= time(NULL);
# endif

#if 0
    random_bits = 0;            /* FOR TESTING */
#endif

    do {
        free(s);

        if (asprintf(&s, "%s/%s_%08lx%s",
                     tempdir,
                     prefix,
                     random_bits & 0xffffffffUL,
                     suffix) == -1)
            return EXIT_OUT_OF_MEMORY;

        /* Note that if the name already exists as a symlink, this
         * open call will fail.
         *
         * The permissions are tight because nobody but this process
         * and our children should do anything with it. */
        fd = open(s, O_WRONLY | O_CREAT | O_EXCL, 0600);
        if (fd == -1) {
            /* try again */
            rs_trace("failed to create %s: %s", s, strerror(errno));
            random_bits += 7777; /* fairly prime */
            continue;
        }

        if (close(fd) == -1) {  /* huh? */
            rs_log_warning("failed to close %s: %s", s, strerror(errno));
            return EXIT_IO_ERROR;
        }

        break;
    } while (1);

    if ((ret = dcc_add_cleanup(s))) {
        /* bailing out */
        unlink(s);
        free(s);
        return ret;
    }

    *name_ret = s;
    return 0;
}