re-mark 1.29b-2 as not yet uploaded (merge madness!)
[debian/tar] / gnu / backupfile.c
1 /* backupfile.c -- make Emacs style backup file names
2
3    Copyright (C) 1990-2006, 2009-2015 Free Software Foundation, Inc.
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 3 of the License, or
8    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Paul Eggert and David MacKenzie.
19    Some algorithms adapted from GNU Emacs.  */
20
21 #include <config.h>
22
23 #include "backupfile.h"
24
25 #include "argmatch.h"
26 #include "dirname.h"
27 #include "xalloc.h"
28
29 #include <errno.h>
30 #include <stdbool.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include <limits.h>
35
36 #include <unistd.h>
37
38 #include "dirent--.h"
39 #ifndef _D_EXACT_NAMLEN
40 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
41 #endif
42 #if D_INO_IN_DIRENT
43 # define REAL_DIR_ENTRY(dp) ((dp)->d_ino != 0)
44 #else
45 # define REAL_DIR_ENTRY(dp) 1
46 #endif
47
48 #if ! (HAVE_PATHCONF && defined _PC_NAME_MAX)
49 # define pathconf(file, option) (errno = -1)
50 #endif
51
52 #ifndef _POSIX_NAME_MAX
53 # define _POSIX_NAME_MAX 14
54 #endif
55 #ifndef SIZE_MAX
56 # define SIZE_MAX ((size_t) -1)
57 #endif
58
59 #if defined _XOPEN_NAME_MAX
60 # define NAME_MAX_MINIMUM _XOPEN_NAME_MAX
61 #else
62 # define NAME_MAX_MINIMUM _POSIX_NAME_MAX
63 #endif
64
65 #ifndef HAVE_DOS_FILE_NAMES
66 # define HAVE_DOS_FILE_NAMES 0
67 #endif
68 #ifndef HAVE_LONG_FILE_NAMES
69 # define HAVE_LONG_FILE_NAMES 0
70 #endif
71
72 /* ISDIGIT differs from isdigit, as follows:
73    - Its arg may be any int or unsigned int; it need not be an unsigned char
74      or EOF.
75    - It's typically faster.
76    POSIX says that only '0' through '9' are digits.  Prefer ISDIGIT to
77    ISDIGIT unless it's important to use the locale's definition
78    of "digit" even when the host does not conform to POSIX.  */
79 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
80
81 /* The extension added to file names to produce a simple (as opposed
82    to numbered) backup file name. */
83 char const *simple_backup_suffix = "~";
84
85
86 /* If FILE (which was of length FILELEN before an extension was
87    appended to it) is too long, replace the extension with the single
88    char E.  If the result is still too long, remove the char just
89    before E.  */
90
91 static void
92 check_extension (char *file, size_t filelen, char e)
93 {
94   char *base = last_component (file);
95   size_t baselen = base_len (base);
96   size_t baselen_max = HAVE_LONG_FILE_NAMES ? 255 : NAME_MAX_MINIMUM;
97
98   if (HAVE_DOS_FILE_NAMES || NAME_MAX_MINIMUM < baselen)
99     {
100       /* The new base name is long enough to require a pathconf check.  */
101       long name_max;
102
103       /* Temporarily modify the buffer into its parent directory name,
104          invoke pathconf on the directory, and then restore the buffer.  */
105       char tmp[sizeof "."];
106       memcpy (tmp, base, sizeof ".");
107       strcpy (base, ".");
108       errno = 0;
109       name_max = pathconf (file, _PC_NAME_MAX);
110       if (0 <= name_max || errno == 0)
111         {
112           long size = baselen_max = name_max;
113           if (name_max != size)
114             baselen_max = SIZE_MAX;
115         }
116       memcpy (base, tmp, sizeof ".");
117     }
118
119   if (HAVE_DOS_FILE_NAMES && baselen_max <= 12)
120     {
121       /* Live within DOS's 8.3 limit.  */
122       char *dot = strchr (base, '.');
123       if (!dot)
124         baselen_max = 8;
125       else
126         {
127           char const *second_dot = strchr (dot + 1, '.');
128           baselen_max = (second_dot
129                          ? second_dot - base
130                          : dot + 1 - base + 3);
131         }
132     }
133
134   if (baselen_max < baselen)
135     {
136       baselen = file + filelen - base;
137       if (baselen_max <= baselen)
138         baselen = baselen_max - 1;
139       base[baselen] = e;
140       base[baselen + 1] = '\0';
141     }
142 }
143
144 /* Returned values for NUMBERED_BACKUP.  */
145
146 enum numbered_backup_result
147   {
148     /* The new backup name is the same length as an existing backup
149        name, so it's valid for that directory.  */
150     BACKUP_IS_SAME_LENGTH,
151
152     /* Some backup names already exist, but the returned name is longer
153        than any of them, and its length should be checked.  */
154     BACKUP_IS_LONGER,
155
156     /* There are no existing backup names.  The new name's length
157        should be checked.  */
158     BACKUP_IS_NEW
159   };
160
161 /* *BUFFER contains a file name.  Store into *BUFFER the next backup
162    name for the named file, with a version number greater than all the
163    existing numbered backups.  Reallocate *BUFFER as necessary; its
164    initial allocated size is BUFFER_SIZE, which must be at least 4
165    bytes longer than the file name to make room for the initially
166    appended ".~1".  FILELEN is the length of the original file name.
167    The returned value indicates what kind of backup was found.  If an
168    I/O or other read error occurs, use the highest backup number that
169    was found.  */
170
171 static enum numbered_backup_result
172 numbered_backup (char **buffer, size_t buffer_size, size_t filelen)
173 {
174   enum numbered_backup_result result = BACKUP_IS_NEW;
175   DIR *dirp;
176   struct dirent *dp;
177   char *buf = *buffer;
178   size_t versionlenmax = 1;
179   char *base = last_component (buf);
180   size_t base_offset = base - buf;
181   size_t baselen = base_len (base);
182
183   /* Temporarily modify the buffer into its parent directory name,
184      open the directory, and then restore the buffer.  */
185   char tmp[sizeof "."];
186   memcpy (tmp, base, sizeof ".");
187   strcpy (base, ".");
188   dirp = opendir (buf);
189   memcpy (base, tmp, sizeof ".");
190   strcpy (base + baselen, ".~1~");
191
192   if (!dirp)
193     return result;
194
195   while ((dp = readdir (dirp)) != NULL)
196     {
197       char const *p;
198       char *q;
199       bool all_9s;
200       size_t versionlen;
201       size_t new_buflen;
202
203       if (! REAL_DIR_ENTRY (dp) || _D_EXACT_NAMLEN (dp) < baselen + 4)
204         continue;
205
206       if (memcmp (buf + base_offset, dp->d_name, baselen + 2) != 0)
207         continue;
208
209       p = dp->d_name + baselen + 2;
210
211       /* Check whether this file has a version number and if so,
212          whether it is larger.  Use string operations rather than
213          integer arithmetic, to avoid problems with integer overflow.  */
214
215       if (! ('1' <= *p && *p <= '9'))
216         continue;
217       all_9s = (*p == '9');
218       for (versionlen = 1; ISDIGIT (p[versionlen]); versionlen++)
219         all_9s &= (p[versionlen] == '9');
220
221       if (! (p[versionlen] == '~' && !p[versionlen + 1]
222              && (versionlenmax < versionlen
223                  || (versionlenmax == versionlen
224                      && memcmp (buf + filelen + 2, p, versionlen) <= 0))))
225         continue;
226
227       /* This directory has the largest version number seen so far.
228          Append this highest numbered extension to the file name,
229          prepending '0' to the number if it is all 9s.  */
230
231       versionlenmax = all_9s + versionlen;
232       result = (all_9s ? BACKUP_IS_LONGER : BACKUP_IS_SAME_LENGTH);
233       new_buflen = filelen + 2 + versionlenmax + 1;
234       if (buffer_size <= new_buflen)
235         {
236           buf = xnrealloc (buf, 2, new_buflen);
237           buffer_size = new_buflen * 2;
238         }
239       q = buf + filelen;
240       *q++ = '.';
241       *q++ = '~';
242       *q = '0';
243       q += all_9s;
244       memcpy (q, p, versionlen + 2);
245
246       /* Add 1 to the version number.  */
247
248       q += versionlen;
249       while (*--q == '9')
250         *q = '0';
251       ++*q;
252     }
253
254   closedir (dirp);
255   *buffer = buf;
256   return result;
257 }
258
259 /* Return the name of the new backup file for the existing file FILE,
260    allocated with malloc.  Report an error and fail if out of memory.
261    Do not call this function if backup_type == no_backups.  */
262
263 char *
264 find_backup_file_name (char const *file, enum backup_type backup_type)
265 {
266   size_t filelen = strlen (file);
267   char *s;
268   size_t ssize;
269   bool simple = true;
270
271   /* Allow room for simple or ".~N~" backups.  The guess must be at
272      least sizeof ".~1~", but otherwise will be adjusted as needed.  */
273   size_t simple_backup_suffix_size = strlen (simple_backup_suffix) + 1;
274   size_t backup_suffix_size_guess = simple_backup_suffix_size;
275   enum { GUESS = sizeof ".~12345~" };
276   if (backup_suffix_size_guess < GUESS)
277     backup_suffix_size_guess = GUESS;
278
279   ssize = filelen + backup_suffix_size_guess + 1;
280   s = xmalloc (ssize);
281   memcpy (s, file, filelen + 1);
282
283   if (backup_type != simple_backups)
284     switch (numbered_backup (&s, ssize, filelen))
285       {
286       case BACKUP_IS_SAME_LENGTH:
287         return s;
288
289       case BACKUP_IS_LONGER:
290         simple = false;
291         break;
292
293       case BACKUP_IS_NEW:
294         simple = (backup_type == numbered_existing_backups);
295         break;
296       }
297
298   if (simple)
299     memcpy (s + filelen, simple_backup_suffix, simple_backup_suffix_size);
300   check_extension (s, filelen, '~');
301   return s;
302 }
303
304 static char const * const backup_args[] =
305 {
306   /* In a series of synonyms, present the most meaningful first, so
307      that argmatch_valid be more readable. */
308   "none", "off",
309   "simple", "never",
310   "existing", "nil",
311   "numbered", "t",
312   NULL
313 };
314
315 static const enum backup_type backup_types[] =
316 {
317   no_backups, no_backups,
318   simple_backups, simple_backups,
319   numbered_existing_backups, numbered_existing_backups,
320   numbered_backups, numbered_backups
321 };
322
323 /* Ensure that these two vectors have the same number of elements,
324    not counting the final NULL in the first one.  */
325 ARGMATCH_VERIFY (backup_args, backup_types);
326
327 /* Return the type of backup specified by VERSION.
328    If VERSION is NULL or the empty string, return numbered_existing_backups.
329    If VERSION is invalid or ambiguous, fail with a diagnostic appropriate
330    for the specified CONTEXT.  Unambiguous abbreviations are accepted.  */
331
332 enum backup_type
333 get_version (char const *context, char const *version)
334 {
335   if (version == 0 || *version == 0)
336     return numbered_existing_backups;
337   else
338     return XARGMATCH (context, version, backup_args, backup_types);
339 }
340
341
342 /* Return the type of backup specified by VERSION.
343    If VERSION is NULL, use the value of the envvar VERSION_CONTROL.
344    If the specified string is invalid or ambiguous, fail with a diagnostic
345    appropriate for the specified CONTEXT.
346    Unambiguous abbreviations are accepted.  */
347
348 enum backup_type
349 xget_version (char const *context, char const *version)
350 {
351   if (version && *version)
352     return get_version (context, version);
353   else
354     return get_version ("$VERSION_CONTROL", getenv ("VERSION_CONTROL"));
355 }