Provide a fallback for PATH_MAX.
[gnulib.git] / lib / clean-temp.c
1 /* Temporary directories and temporary files with automatic cleanup.
2    Copyright (C) 2001, 2003, 2006 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2006.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19
20 #include <config.h>
21
22 /* Specification.  */
23 #include "clean-temp.h"
24
25 #include <errno.h>
26 #include <limits.h>
27 #include <stdbool.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #include "error.h"
33 #include "fatal-signal.h"
34 #include "pathmax.h"
35 #include "tmpdir.h"
36 #include "mkdtemp.h"
37 #include "xalloc.h"
38 #include "xallocsa.h"
39 #include "gl_linkedhash_list.h"
40 #include "gettext.h"
41
42 #define _(str) gettext (str)
43
44 /* GNU Hurd doesn't have PATH_MAX.  */
45 #ifndef PATH_MAX
46 # ifdef MAXPATHLEN
47 #  define PATH_MAX MAXPATHLEN
48 # else
49 #  define PATH_MAX 1024
50 # endif
51 #endif
52
53 #ifndef uintptr_t
54 # define uintptr_t unsigned long
55 #endif
56
57
58 /* The use of 'volatile' in the types below (and ISO C 99 section 5.1.2.3.(5))
59    ensure that while constructing or modifying the data structures, the field
60    values are written to memory in the order of the C statements.  So the
61    signal handler can rely on these field values to be up to date.  */
62
63
64 /* Registry for a single temporary directory.
65    'struct temp_dir' from the public header file overlaps with this.  */
66 struct tempdir
67 {
68   /* The absolute pathname of the directory.  */
69   char * volatile dirname;
70   /* Whether errors during explicit cleanup are reported to standard error.  */
71   bool cleanup_verbose;
72   /* Absolute pathnames of subdirectories.  */
73   gl_list_t /* <char *> */ volatile subdirs;
74   /* Absolute pathnames of files.  */
75   gl_list_t /* <char *> */ volatile files;
76 };
77
78 /* List of all temporary directories.  */
79 static struct
80 {
81   struct tempdir * volatile * volatile tempdir_list;
82   size_t volatile tempdir_count;
83   size_t tempdir_allocated;
84 } cleanup_list /* = { NULL, 0, 0 } */;
85
86 /* List of all open file descriptors to temporary files.  */
87 static gl_list_t /* <int> */ volatile descriptors;
88
89
90 /* For the subdirs and for the files, we use a gl_list_t of type LINKEDHASH.
91    Why?  We need a data structure that
92
93      1) Can contain an arbitrary number of 'char *' values.  The strings
94         are compared via strcmp, not pointer comparison.
95      2) Has insertion and deletion operations that are fast: ideally O(1),
96         or possibly O(log n).  This is important for GNU sort, which may
97         create a large number of temporary files.
98      3) Allows iteration through all elements from within a signal handler.
99      4) May or may not allow duplicates.  It doesn't matter here, since
100         any file or subdir can only be removed once.
101
102    Criterion 1) would allow any gl_list_t or gl_oset_t implementation.
103
104    Criterion 2) leaves only GL_LINKEDHASH_LIST, GL_TREEHASH_LIST, or
105    GL_TREE_OSET.
106
107    Criterion 3) puts at disadvantage GL_TREEHASH_LIST and GL_TREE_OSET.
108    Namely, iteration through the elements of a binary tree requires access
109    to many ->left, ->right, ->parent pointers. However, the rebalancing
110    code for insertion and deletion in an AVL or red-black tree is so
111    complicated that we cannot assume that >left, ->right, ->parent pointers
112    are in a consistent state throughout these operations.  Therefore, to
113    avoid a crash in the signal handler, all destructive operations to the
114    lists would have to be protected by a
115        block_fatal_signals ();
116        ...
117        unblock_fatal_signals ();
118    pair.  Which causes extra system calls.
119
120    Criterion 3) would also discourage GL_ARRAY_LIST and GL_CARRAY_LIST,
121    if they were not already excluded.  Namely, these implementations use
122    xrealloc(), leaving a time window in which in the list->elements pointer
123    points to already deallocated memory.  To avoid a crash in the signal
124    handler at such a moment, all destructive operations would have to
125    protected by block/unblock_fatal_signals (), in this case too.
126
127    A list of type GL_LINKEDHASH_LIST without duplicates fulfills all
128    requirements:
129      2) Insertion and deletion are O(1) on average.
130      3) The gl_list_iterator, gl_list_iterator_next implementations do
131         not trigger memory allocations, nor other system calls, and are
132         therefore safe to be called from a signal handler.
133         Furthermore, since SIGNAL_SAFE_LIST is defined, the implementation
134         of the destructive functions ensures that the list structure is
135         safe to be traversed at any moment, even when interrupted by an
136         asynchronous signal.
137  */
138
139 /* String equality and hash code functions used by the lists.  */
140
141 static bool
142 string_equals (const void *x1, const void *x2)
143 {
144   const char *s1 = x1;
145   const char *s2 = x2;
146   return strcmp (s1, s2) == 0;
147 }
148
149 #define SIZE_BITS (sizeof (size_t) * CHAR_BIT)
150
151 /* A hash function for NUL-terminated char* strings using
152    the method described by Bruno Haible.
153    See http://www.haible.de/bruno/hashfunc.html.  */
154 static size_t
155 string_hash (const void *x)
156 {
157   const char *s = x;
158   size_t h = 0;
159
160   for (; *s; s++)
161     h = *s + ((h << 9) | (h >> (SIZE_BITS - 9)));
162
163   return h;
164 }
165
166
167 /* The signal handler.  It gets called asynchronously.  */
168 static void
169 cleanup ()
170 {
171   size_t i;
172
173   /* First close all file descriptors to temporary files.  */
174   {
175     gl_list_t fds = descriptors;
176
177     if (fds != NULL)
178       {
179         gl_list_iterator_t iter;
180         const void *element;
181
182         iter = gl_list_iterator (fds);
183         while (gl_list_iterator_next (&iter, &element, NULL))
184           {
185             int fd = (int) (uintptr_t) element;
186             close (fd);
187           }
188         gl_list_iterator_free (&iter);
189       }
190   }
191
192   for (i = 0; i < cleanup_list.tempdir_count; i++)
193     {
194       struct tempdir *dir = cleanup_list.tempdir_list[i];
195
196       if (dir != NULL)
197         {
198           gl_list_iterator_t iter;
199           const void *element;
200
201           /* First cleanup the files in the subdirectories.  */
202           iter = gl_list_iterator (dir->files);
203           while (gl_list_iterator_next (&iter, &element, NULL))
204             {
205               const char *file = (const char *) element;
206               unlink (file);
207             }
208           gl_list_iterator_free (&iter);
209
210           /* Then cleanup the subdirectories.  */
211           iter = gl_list_iterator (dir->subdirs);
212           while (gl_list_iterator_next (&iter, &element, NULL))
213             {
214               const char *subdir = (const char *) element;
215               rmdir (subdir);
216             }
217           gl_list_iterator_free (&iter);
218
219           /* Then cleanup the temporary directory itself.  */
220           rmdir (dir->dirname);
221         }
222     }
223 }
224
225 /* Create a temporary directory.
226    PREFIX is used as a prefix for the name of the temporary directory. It
227    should be short and still give an indication about the program.
228    PARENTDIR can be used to specify the parent directory; if NULL, a default
229    parent directory is used (either $TMPDIR or /tmp or similar).
230    CLEANUP_VERBOSE determines whether errors during explicit cleanup are
231    reported to standard error.
232    Return a fresh 'struct temp_dir' on success.  Upon error, an error message
233    is shown and NULL is returned.  */
234 struct temp_dir *
235 create_temp_dir (const char *prefix, const char *parentdir,
236                  bool cleanup_verbose)
237 {
238   struct tempdir * volatile *tmpdirp = NULL;
239   struct tempdir *tmpdir;
240   size_t i;
241   char *template;
242   char *tmpdirname;
243
244   /* See whether it can take the slot of an earlier temporary directory
245      already cleaned up.  */
246   for (i = 0; i < cleanup_list.tempdir_count; i++)
247     if (cleanup_list.tempdir_list[i] == NULL)
248       {
249         tmpdirp = &cleanup_list.tempdir_list[i];
250         break;
251       }
252   if (tmpdirp == NULL)
253     {
254       /* See whether the array needs to be extended.  */
255       if (cleanup_list.tempdir_count == cleanup_list.tempdir_allocated)
256         {
257           /* Note that we cannot use xrealloc(), because then the cleanup()
258              function could access an already deallocated array.  */
259           struct tempdir * volatile *old_array = cleanup_list.tempdir_list;
260           size_t old_allocated = cleanup_list.tempdir_allocated;
261           size_t new_allocated = 2 * cleanup_list.tempdir_allocated + 1;
262           struct tempdir * volatile *new_array =
263             (struct tempdir * volatile *)
264             xmalloc (new_allocated * sizeof (struct tempdir * volatile));
265
266           if (old_allocated == 0)
267             /* First use of this facility.  Register the cleanup handler.  */
268             at_fatal_signal (&cleanup);
269           else
270             {
271               /* Don't use memcpy() here, because memcpy takes non-volatile
272                  arguments and is therefore not guaranteed to complete all
273                  memory stores before the next statement.  */
274               size_t k;
275
276               for (k = 0; k < old_allocated; k++)
277                 new_array[k] = old_array[k];
278             }
279
280           cleanup_list.tempdir_list = new_array;
281           cleanup_list.tempdir_allocated = new_allocated;
282
283           /* Now we can free the old array.  */
284           if (old_array != NULL)
285             free ((struct tempdir **) old_array);
286         }
287
288       tmpdirp = &cleanup_list.tempdir_list[cleanup_list.tempdir_count];
289       /* Initialize *tmpdirp before incrementing tempdir_count, so that
290          cleanup() will skip this entry before it is fully initialized.  */
291       *tmpdirp = NULL;
292       cleanup_list.tempdir_count++;
293     }
294
295   /* Initialize a 'struct tempdir'.  */
296   tmpdir = (struct tempdir *) xmalloc (sizeof (struct tempdir));
297   tmpdir->dirname = NULL;
298   tmpdir->cleanup_verbose = cleanup_verbose;
299   tmpdir->subdirs = gl_list_create_empty (GL_LINKEDHASH_LIST,
300                                           string_equals, string_hash, false);
301   tmpdir->files = gl_list_create_empty (GL_LINKEDHASH_LIST,
302                                         string_equals, string_hash, false);
303
304   /* Create the temporary directory.  */
305   template = (char *) xallocsa (PATH_MAX);
306   if (path_search (template, PATH_MAX, parentdir, prefix, parentdir == NULL))
307     {
308       error (0, errno,
309              _("cannot find a temporary directory, try setting $TMPDIR"));
310       goto quit;
311     }
312   block_fatal_signals ();
313   tmpdirname = mkdtemp (template);
314   if (tmpdirname != NULL)
315     {
316       tmpdir->dirname = tmpdirname;
317       *tmpdirp = tmpdir;
318     }
319   unblock_fatal_signals ();
320   if (tmpdirname == NULL)
321     {
322       error (0, errno,
323              _("cannot create a temporary directory using template \"%s\""),
324              template);
325       goto quit;
326     }
327   /* Replace tmpdir->dirname with a copy that has indefinite extent.
328      We cannot do this inside the block_fatal_signals/unblock_fatal_signals
329      block because then the cleanup handler would not remove the directory
330      if xstrdup fails.  */
331   tmpdir->dirname = xstrdup (tmpdirname);
332   freesa (template);
333   return (struct temp_dir *) tmpdir;
334
335  quit:
336   freesa (template);
337   return NULL;
338 }
339
340 /* Register the given ABSOLUTE_FILE_NAME as being a file inside DIR, that
341    needs to be removed before DIR can be removed.
342    Should be called before the file ABSOLUTE_FILE_NAME is created.  */
343 void
344 register_temp_file (struct temp_dir *dir,
345                     const char *absolute_file_name)
346 {
347   struct tempdir *tmpdir = (struct tempdir *)dir;
348
349   /* Add absolute_file_name to tmpdir->files, without duplicates.  */
350   if (gl_list_search (tmpdir->files, absolute_file_name) == NULL)
351     gl_list_add_first (tmpdir->files, xstrdup (absolute_file_name));
352 }
353
354 /* Unregister the given ABSOLUTE_FILE_NAME as being a file inside DIR, that
355    needs to be removed before DIR can be removed.
356    Should be called when the file ABSOLUTE_FILE_NAME could not be created.  */
357 void
358 unregister_temp_file (struct temp_dir *dir,
359                       const char *absolute_file_name)
360 {
361   struct tempdir *tmpdir = (struct tempdir *)dir;
362   gl_list_t list = tmpdir->files;
363   gl_list_node_t node;
364
365   node = gl_list_search (list, absolute_file_name);
366   if (node != NULL)
367     {
368       char *old_string = (char *) gl_list_node_value (list, node);
369
370       gl_list_remove_node (list, node);
371       free (old_string);
372     }
373 }
374
375 /* Register the given ABSOLUTE_DIR_NAME as being a subdirectory inside DIR,
376    that needs to be removed before DIR can be removed.
377    Should be called before the subdirectory ABSOLUTE_DIR_NAME is created.  */
378 void
379 register_temp_subdir (struct temp_dir *dir,
380                       const char *absolute_dir_name)
381 {
382   struct tempdir *tmpdir = (struct tempdir *)dir;
383
384   /* Add absolute_dir_name to tmpdir->subdirs, without duplicates.  */
385   if (gl_list_search (tmpdir->subdirs, absolute_dir_name) == NULL)
386     gl_list_add_first (tmpdir->subdirs, xstrdup (absolute_dir_name));
387 }
388
389 /* Unregister the given ABSOLUTE_DIR_NAME as being a subdirectory inside DIR,
390    that needs to be removed before DIR can be removed.
391    Should be called when the subdirectory ABSOLUTE_DIR_NAME could not be
392    created.  */
393 void
394 unregister_temp_subdir (struct temp_dir *dir,
395                         const char *absolute_dir_name)
396 {
397   struct tempdir *tmpdir = (struct tempdir *)dir;
398   gl_list_t list = tmpdir->subdirs;
399   gl_list_node_t node;
400
401   node = gl_list_search (list, absolute_dir_name);
402   if (node != NULL)
403     {
404       char *old_string = (char *) gl_list_node_value (list, node);
405
406       gl_list_remove_node (list, node);
407       free (old_string);
408     }
409 }
410
411 /* Remove a file, with optional error message.  */
412 static void
413 do_unlink (struct temp_dir *dir, const char *absolute_file_name)
414 {
415   if (unlink (absolute_file_name) < 0 && dir->cleanup_verbose
416       && errno != ENOENT)
417     error (0, errno, _("cannot remove temporary file %s"), absolute_file_name);
418 }
419
420 /* Remove a directory, with optional error message.  */
421 static void
422 do_rmdir (struct temp_dir *dir, const char *absolute_dir_name)
423 {
424   if (rmdir (absolute_dir_name) < 0 && dir->cleanup_verbose
425       && errno != ENOENT)
426     error (0, errno,
427            _("cannot remove temporary directory %s"), absolute_dir_name);
428 }
429
430 /* Remove the given ABSOLUTE_FILE_NAME and unregister it.  */
431 void
432 cleanup_temp_file (struct temp_dir *dir,
433                    const char *absolute_file_name)
434 {
435   do_unlink (dir, absolute_file_name);
436   unregister_temp_file (dir, absolute_file_name);
437 }
438
439 /* Remove the given ABSOLUTE_DIR_NAME and unregister it.  */
440 void
441 cleanup_temp_subdir (struct temp_dir *dir,
442                      const char *absolute_dir_name)
443 {
444   do_rmdir (dir, absolute_dir_name);
445   unregister_temp_subdir (dir, absolute_dir_name);
446 }
447
448 /* Remove all registered files and subdirectories inside DIR.  */
449 void
450 cleanup_temp_dir_contents (struct temp_dir *dir)
451 {
452   struct tempdir *tmpdir = (struct tempdir *)dir;
453   gl_list_t list;
454   gl_list_iterator_t iter;
455   const void *element;
456   gl_list_node_t node;
457
458   /* First cleanup the files in the subdirectories.  */
459   list = tmpdir->files;
460   iter = gl_list_iterator (list);
461   while (gl_list_iterator_next (&iter, &element, &node))
462     {
463       char *file = (char *) element;
464
465       do_unlink (dir, file);
466       gl_list_remove_node (list, node);
467       /* Now only we can free file.  */
468       free (file);
469     }
470   gl_list_iterator_free (&iter);
471
472   /* Then cleanup the subdirectories.  */
473   list = tmpdir->subdirs;
474   iter = gl_list_iterator (list);
475   while (gl_list_iterator_next (&iter, &element, &node))
476     {
477       char *subdir = (char *) element;
478
479       do_rmdir (dir, subdir);
480       gl_list_remove_node (list, node);
481       /* Now only we can free subdir.  */
482       free (subdir);
483     }
484   gl_list_iterator_free (&iter);
485 }
486
487 /* Remove all registered files and subdirectories inside DIR and DIR itself.
488    DIR cannot be used any more after this call.  */
489 void
490 cleanup_temp_dir (struct temp_dir *dir)
491 {
492   struct tempdir *tmpdir = (struct tempdir *)dir;
493   size_t i;
494
495   cleanup_temp_dir_contents (dir);
496   do_rmdir (dir, tmpdir->dirname);
497
498   for (i = 0; i < cleanup_list.tempdir_count; i++)
499     if (cleanup_list.tempdir_list[i] == tmpdir)
500       {
501         /* Remove cleanup_list.tempdir_list[i].  */
502         if (i + 1 == cleanup_list.tempdir_count)
503           {
504             while (i > 0 && cleanup_list.tempdir_list[i - 1] == NULL)
505               i--;
506             cleanup_list.tempdir_count = i;
507           }
508         else
509           cleanup_list.tempdir_list[i] = NULL;
510         /* Now only we can free the tmpdir->dirname and tmpdir itself.  */
511         free (tmpdir->dirname);
512         free (tmpdir);
513         return;
514       }
515
516   /* The user passed an invalid DIR argument.  */
517   abort ();
518 }
519
520
521 /* Register a file descriptor to be closed.  */
522 static void
523 register_fd (int fd)
524 {
525   if (descriptors == NULL)
526     descriptors = gl_list_create_empty (GL_LINKEDHASH_LIST, NULL, NULL, false);
527   gl_list_add_first (descriptors, (void *) (uintptr_t) fd);
528 }
529
530 /* Unregister a file descriptor to be closed.  */
531 static void
532 unregister_fd (int fd)
533 {
534   gl_list_t fds = descriptors;
535   gl_list_node_t node;
536
537   if (fds == NULL)
538     /* descriptors should already contain fd.  */
539     abort ();
540   node = gl_list_search (fds, (void *) (uintptr_t) fd);
541   if (node == NULL)
542     /* descriptors should already contain fd.  */
543     abort ();
544   gl_list_remove_node (fds, node);
545 }
546
547 /* Open a temporary file in a temporary directory.
548    Registers the resulting file descriptor to be closed.  */
549 int
550 open_temp (const char *file_name, int flags, mode_t mode)
551 {
552   int fd;
553   int saved_errno;
554
555   block_fatal_signals ();
556   fd = open (file_name, flags, mode);
557   saved_errno = errno;
558   if (fd >= 0)
559     register_fd (fd);
560   unblock_fatal_signals ();
561   errno = saved_errno;
562   return fd;
563 }
564
565 /* Open a temporary file in a temporary directory.
566    Registers the resulting file descriptor to be closed.  */
567 FILE *
568 fopen_temp (const char *file_name, const char *mode)
569 {
570   FILE *fp;
571   int saved_errno;
572
573   block_fatal_signals ();
574   fp = fopen (file_name, mode);
575   saved_errno = errno;
576   if (fp != NULL)
577     {
578       /* It is sufficient to register fileno (fp) instead of the entire fp,
579          because at cleanup time there is no need to do an fflush (fp); a
580          close (fileno (fp)) will be enough.  */
581       int fd = fileno (fp);
582       if (!(fd >= 0))
583         abort ();
584       register_fd (fd);
585     }
586   unblock_fatal_signals ();
587   errno = saved_errno;
588   return fp;
589 }
590
591 /* Close a temporary file in a temporary directory.
592    Unregisters the previously registered file descriptor.  */
593 int
594 close_temp (int fd)
595 {
596   if (fd >= 0)
597     {
598       /* No blocking of signals is needed here, since a double close of a
599          file descriptor is harmless.  */
600       int result = close (fd);
601       int saved_errno = errno;
602
603       /* No race condition here: we assume a single-threaded program, hence
604          fd cannot be re-opened here.  */
605
606       unregister_fd (fd);
607
608       errno = saved_errno;
609       return result;
610     }
611   else
612     return close (fd);
613 }
614
615 /* Close a temporary file in a temporary directory.
616    Unregisters the previously registered file descriptor.  */
617 int
618 fclose_temp (FILE *fp)
619 {
620   int fd = fileno (fp);
621   /* No blocking of signals is needed here, since a double close of a
622      file descriptor is harmless.  */
623   int result = fclose (fp);
624   int saved_errno = errno;
625
626   /* No race condition here: we assume a single-threaded program, hence
627      fd cannot be re-opened here.  */
628
629   unregister_fd (fd);
630
631   errno = saved_errno;
632   return result;
633 }
634
635 #if GNULIB_FWRITEERROR
636 /* Like fwriteerror.
637    Unregisters the previously registered file descriptor.  */
638 int
639 fwriteerror_temp (FILE *fp)
640 {
641   int fd = fileno (fp);
642   /* No blocking of signals is needed here, since a double close of a
643      file descriptor is harmless.  */
644   int result = fwriteerror (fp);
645   int saved_errno = errno;
646
647   /* No race condition here: we assume a single-threaded program, hence
648      fd cannot be re-opened here.  */
649
650   unregister_fd (fd);
651
652   errno = saved_errno;
653   return result;
654 }
655 #endif