Implement window size passing between real tty and virtual console.
[dragonfly/port-amd64.git] / contrib / tar / src / misc.c
blobbdfac31040228ac4438e9733ff48a557e399580f
1 /* Miscellaneous functions, not really specific to GNU tar.
3 Copyright 1988, 1992, 1994, 1995, 1996, 1997, 1999, 2000, 2001 Free
4 Software Foundation, Inc.
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any later
9 version.
11 This program is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
14 Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
20 /* $FreeBSD: src/contrib/tar/src/misc.c,v 1.2.2.2 2002/10/19 09:37:29 sobomax Exp $ */
21 /* $DragonFly: src/contrib/tar/src/Attic/misc.c,v 1.2 2003/06/17 04:24:06 dillon Exp $ */
23 #include "system.h"
24 #include "rmt.h"
25 #include "common.h"
26 #include <quotearg.h>
27 #include <save-cwd.h>
29 static void call_arg_fatal PARAMS ((char const *, char const *))
30 __attribute__ ((noreturn));
32 /* Handling strings. */
34 /* Assign STRING to a copy of VALUE if not zero, or to zero. If
35 STRING was nonzero, it is freed first. */
36 void
37 assign_string (char **string, const char *value)
39 if (*string)
40 free (*string);
41 *string = value ? xstrdup (value) : 0;
44 /* Allocate a copy of the string quoted as in C, and returns that. If
45 the string does not have to be quoted, it returns a null pointer.
46 The allocated copy should normally be freed with free() after the
47 caller is done with it.
49 This is used in one context only: generating the directory file in
50 incremental dumps. The quoted string is not intended for human
51 consumption; it is intended only for unquote_string. The quoting
52 is locale-independent, so that users needn't worry about locale
53 when reading directory files. This means that we can't use
54 quotearg, as quotearg is locale-dependent and is meant for human
55 consumption. */
56 char *
57 quote_copy_string (const char *string)
59 const char *source = string;
60 char *destination = 0;
61 char *buffer = 0;
62 int copying = 0;
64 while (*source)
66 int character = *source++;
68 switch (character)
70 case '\n': case '\\':
71 if (!copying)
73 size_t length = (source - string) - 1;
75 copying = 1;
76 buffer = xmalloc (length + 2 + 2 * strlen (source) + 1);
77 memcpy (buffer, string, length);
78 destination = buffer + length;
80 *destination++ = '\\';
81 *destination++ = character == '\\' ? '\\' : 'n';
82 break;
84 default:
85 if (copying)
86 *destination++ = character;
87 break;
90 if (copying)
92 *destination = '\0';
93 return buffer;
95 return 0;
98 /* Takes a quoted C string (like those produced by quote_copy_string)
99 and turns it back into the un-quoted original. This is done in
100 place. Returns 0 only if the string was not properly quoted, but
101 completes the unquoting anyway.
103 This is used for reading the saved directory file in incremental
104 dumps. It is used for decoding old `N' records (demangling names).
105 But also, it is used for decoding file arguments, would they come
106 from the shell or a -T file, and for decoding the --exclude
107 argument. */
109 unquote_string (char *string)
111 int result = 1;
112 char *source = string;
113 char *destination = string;
115 /* Escape sequences other than \\ and \n are no longer generated by
116 quote_copy_string, but accept them for backwards compatibility,
117 and also because unquote_string is used for purposes other than
118 parsing the output of quote_copy_string. */
120 while (*source)
121 if (*source == '\\')
122 switch (*++source)
124 case '\\':
125 *destination++ = '\\';
126 source++;
127 break;
129 case 'n':
130 *destination++ = '\n';
131 source++;
132 break;
134 case 't':
135 *destination++ = '\t';
136 source++;
137 break;
139 case 'f':
140 *destination++ = '\f';
141 source++;
142 break;
144 case 'b':
145 *destination++ = '\b';
146 source++;
147 break;
149 case 'r':
150 *destination++ = '\r';
151 source++;
152 break;
154 case '?':
155 *destination++ = 0177;
156 source++;
157 break;
159 case '0':
160 case '1':
161 case '2':
162 case '3':
163 case '4':
164 case '5':
165 case '6':
166 case '7':
168 int value = *source++ - '0';
170 if (*source < '0' || *source > '7')
172 *destination++ = value;
173 break;
175 value = value * 8 + *source++ - '0';
176 if (*source < '0' || *source > '7')
178 *destination++ = value;
179 break;
181 value = value * 8 + *source++ - '0';
182 *destination++ = value;
183 break;
186 default:
187 result = 0;
188 *destination++ = '\\';
189 if (*source)
190 *destination++ = *source++;
191 break;
193 else if (source != destination)
194 *destination++ = *source++;
195 else
196 source++, destination++;
198 if (source != destination)
199 *destination = '\0';
200 return result;
203 /* Return nonzero if NAME contains ".." as a path name component. */
205 contains_dot_dot (char const *name)
207 char const *p = name + FILESYSTEM_PREFIX_LEN (name);
209 for (;;)
211 if (p[0] == '.' && p[1] == '.' && (ISSLASH (p[2]) || !p[2]))
212 return 1;
216 if (! *p++)
217 return 0;
219 while (! ISSLASH (*p));
223 if (! *p++)
224 return 0;
226 while ( ISSLASH (*p));
230 /* File handling. */
232 /* Saved names in case backup needs to be undone. */
233 static char *before_backup_name;
234 static char *after_backup_name;
236 /* Some implementations of rmdir let you remove the working directory.
237 Report an error with errno set to zero for obvious cases of this;
238 otherwise call rmdir. */
239 static int
240 safer_rmdir (const char *path)
242 while (path[0] == '.' && ISSLASH (path[1]))
244 path++;
246 do path++;
247 while (ISSLASH (*path));
250 if (! path[0] || (path[0] == '.' && ! path[1]))
252 errno = 0;
253 return -1;
256 return rmdir (path);
259 /* Remove PATH. If PATH is a directory, then if RECURSE is set remove
260 it recursively; otherwise, remove it only if it is empty. Return 0
261 on error, with errno set; if PATH is obviously the working
262 directory return zero with errno set to zero. */
264 remove_any_file (const char *path, int recurse)
266 /* Try unlink first if we are not root, as this saves us a system
267 call in the common case where we're removing a non-directory. */
268 if (! we_are_root)
270 if (unlink (path) == 0)
271 return 1;
272 if (errno != EPERM)
273 return 0;
276 if (safer_rmdir (path) == 0)
277 return 1;
279 switch (errno)
281 case ENOTDIR:
282 return we_are_root && unlink (path) == 0;
284 case 0:
285 case EEXIST:
286 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
287 case ENOTEMPTY:
288 #endif
289 if (recurse)
291 char *directory = savedir (path);
292 char const *entry;
293 size_t entrylen;
295 if (! directory)
296 return 0;
298 for (entry = directory;
299 (entrylen = strlen (entry)) != 0;
300 entry += entrylen + 1)
302 char *path_buffer = new_name (path, entry);
303 int r = remove_any_file (path_buffer, 1);
304 int e = errno;
305 free (path_buffer);
307 if (! r)
309 free (directory);
310 errno = e;
311 return 0;
315 free (directory);
316 return safer_rmdir (path) == 0;
318 break;
321 return 0;
324 /* Check if PATH already exists and make a backup of it right now.
325 Return success (nonzero) only if the backup in either unneeded, or
326 successful. For now, directories are considered to never need
327 backup. If ARCHIVE is nonzero, this is the archive and so, we do
328 not have to backup block or character devices, nor remote entities. */
330 maybe_backup_file (const char *path, int archive)
332 struct stat file_stat;
334 /* Check if we really need to backup the file. */
336 if (archive && _remdev (path))
337 return 1;
339 if (stat (path, &file_stat))
341 if (errno == ENOENT)
342 return 1;
344 stat_error (path);
345 return 0;
348 if (S_ISDIR (file_stat.st_mode))
349 return 1;
351 if (archive && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
352 return 1;
354 assign_string (&before_backup_name, path);
356 /* A run situation may exist between Emacs or other GNU programs trying to
357 make a backup for the same file simultaneously. If theoretically
358 possible, real problems are unlikely. Doing any better would require a
359 convention, GNU-wide, for all programs doing backups. */
361 assign_string (&after_backup_name, 0);
362 after_backup_name = find_backup_file_name (path, backup_type);
363 if (! after_backup_name)
364 xalloc_die ();
366 if (rename (before_backup_name, after_backup_name) == 0)
368 if (verbose_option)
369 fprintf (stdlis, _("Renaming %s to %s\n"),
370 quote_n (0, before_backup_name),
371 quote_n (1, after_backup_name));
372 return 1;
374 else
376 /* The backup operation failed. */
377 int e = errno;
378 ERROR ((0, e, _("%s: Cannot rename to %s"),
379 quotearg_colon (before_backup_name),
380 quote_n (1, after_backup_name)));
381 assign_string (&after_backup_name, 0);
382 return 0;
386 /* Try to restore the recently backed up file to its original name.
387 This is usually only needed after a failed extraction. */
388 void
389 undo_last_backup (void)
391 if (after_backup_name)
393 if (rename (after_backup_name, before_backup_name) != 0)
395 int e = errno;
396 ERROR ((0, e, _("%s: Cannot rename to %s"),
397 quotearg_colon (after_backup_name),
398 quote_n (1, before_backup_name)));
400 if (verbose_option)
401 fprintf (stdlis, _("Renaming %s back to %s\n"),
402 quote_n (0, after_backup_name),
403 quote_n (1, before_backup_name));
404 assign_string (&after_backup_name, 0);
408 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF). */
410 deref_stat (int deref, char const *name, struct stat *buf)
412 return deref ? stat (name, buf) : lstat (name, buf);
415 /* A description of a working directory. */
416 struct wd
418 char const *name;
419 int saved;
420 struct saved_cwd saved_cwd;
423 /* A vector of chdir targets. wd[0] is the initial working directory. */
424 static struct wd *wd;
426 /* The number of working directories in the vector. */
427 static size_t wds;
429 /* The allocated size of the vector. */
430 static size_t wd_alloc;
432 /* DIR is the operand of a -C option; add it to vector of chdir targets,
433 and return the index of its location. */
435 chdir_arg (char const *dir)
437 if (wds == wd_alloc)
439 wd_alloc = 2 * (wd_alloc + 1);
440 wd = xrealloc (wd, sizeof *wd * wd_alloc);
441 if (! wds)
443 wd[wds].name = ".";
444 wd[wds].saved = 0;
445 wds++;
449 /* Optimize the common special case of the working directory,
450 or the working directory as a prefix. */
451 if (dir[0])
453 while (dir[0] == '.' && ISSLASH (dir[1]))
454 for (dir += 2; ISSLASH (*dir); dir++)
455 continue;
456 if (! dir[dir[0] == '.'])
457 return wds - 1;
460 wd[wds].name = dir;
461 wd[wds].saved = 0;
462 return wds++;
465 /* Change to directory I. If I is 0, change to the initial working
466 directory; otherwise, I must be a value returned by chdir_arg. */
467 void
468 chdir_do (int i)
470 static int previous;
472 if (previous != i)
474 struct wd *prev = &wd[previous];
475 struct wd *curr = &wd[i];
477 if (! prev->saved)
479 prev->saved = 1;
480 if (save_cwd (&prev->saved_cwd) != 0)
481 FATAL_ERROR ((0, 0, _("Cannot save working directory")));
484 if (curr->saved)
486 if (restore_cwd (&curr->saved_cwd, curr->name, prev->name))
487 FATAL_ERROR ((0, 0, _("Cannot change working directory")));
489 else
491 if (i && ! ISSLASH (curr->name[0]))
492 chdir_do (i - 1);
493 if (chdir (curr->name) != 0)
494 chdir_fatal (curr->name);
497 previous = i;
501 /* Decode MODE from its binary form in a stat structure, and encode it
502 into a 9-byte string STRING, terminated with a NUL. */
504 void
505 decode_mode (mode_t mode, char *string)
507 *string++ = mode & S_IRUSR ? 'r' : '-';
508 *string++ = mode & S_IWUSR ? 'w' : '-';
509 *string++ = (mode & S_ISUID
510 ? (mode & S_IXUSR ? 's' : 'S')
511 : (mode & S_IXUSR ? 'x' : '-'));
512 *string++ = mode & S_IRGRP ? 'r' : '-';
513 *string++ = mode & S_IWGRP ? 'w' : '-';
514 *string++ = (mode & S_ISGID
515 ? (mode & S_IXGRP ? 's' : 'S')
516 : (mode & S_IXGRP ? 'x' : '-'));
517 *string++ = mode & S_IROTH ? 'r' : '-';
518 *string++ = mode & S_IWOTH ? 'w' : '-';
519 *string++ = (mode & S_ISVTX
520 ? (mode & S_IXOTH ? 't' : 'T')
521 : (mode & S_IXOTH ? 'x' : '-'));
522 *string = '\0';
525 /* Report an error associated with the system call CALL and the
526 optional name NAME. */
527 static void
528 call_arg_error (char const *call, char const *name)
530 int e = errno;
531 ERROR ((0, e, _("%s: Cannot %s"), quotearg_colon (name), call));
534 /* Report a fatal error associated with the system call CALL and
535 the optional file name NAME. */
536 static void
537 call_arg_fatal (char const *call, char const *name)
539 int e = errno;
540 FATAL_ERROR ((0, e, _("%s: Cannot %s"), quotearg_colon (name), call));
543 /* Report a warning associated with the system call CALL and
544 the optional file name NAME. */
545 static void
546 call_arg_warn (char const *call, char const *name)
548 int e = errno;
549 WARN ((0, e, _("%s: Warning: Cannot %s"), quotearg_colon (name), call));
552 void
553 chdir_fatal (char const *name)
555 call_arg_fatal ("chdir", name);
558 void
559 chmod_error_details (char const *name, mode_t mode)
561 int e = errno;
562 ERROR ((0, e, _("%s: Cannot change mode to 0%o"),
563 quotearg_colon (name), mode));
566 void
567 chown_error_details (char const *name, uid_t uid, gid_t gid)
569 int e = errno;
570 ERROR ((0, e, _("%s: Cannot change ownership to uid %lu, gid %lu"),
571 quotearg_colon (name), (unsigned long) uid, (unsigned long) gid));
574 void
575 close_error (char const *name)
577 call_arg_error ("close", name);
580 void
581 close_fatal (char const *name)
583 call_arg_fatal ("close", name);
586 void
587 close_warn (char const *name)
589 call_arg_warn ("close", name);
592 void
593 exec_fatal (char const *name)
595 call_arg_fatal ("exec", name);
598 void
599 link_error (char const *target, char const *source)
601 int e = errno;
602 ERROR ((0, e, _("%s: Cannot hard link to %s"),
603 quotearg_colon (source), quote_n (1, target)));
606 void
607 mkdir_error (char const *name)
609 call_arg_error ("mkdir", name);
612 void
613 mkfifo_error (char const *name)
615 call_arg_error ("mkfifo", name);
618 void
619 mknod_error (char const *name)
621 call_arg_error ("mknod", name);
624 void
625 open_error (char const *name)
627 call_arg_error ("open", name);
630 void
631 open_fatal (char const *name)
633 call_arg_fatal ("open", name);
636 void
637 open_warn (char const *name)
639 call_arg_warn ("open", name);
642 void
643 read_error (char const *name)
645 call_arg_error ("read", name);
648 void
649 read_error_details (char const *name, off_t offset, size_t size)
651 char buf[UINTMAX_STRSIZE_BOUND];
652 int e = errno;
653 ERROR ((0, e,
654 _("%s: Read error at byte %s, reading %lu bytes"),
655 quotearg_colon (name), STRINGIFY_BIGINT (offset, buf),
656 (unsigned long) size));
659 void
660 read_warn_details (char const *name, off_t offset, size_t size)
662 char buf[UINTMAX_STRSIZE_BOUND];
663 int e = errno;
664 WARN ((0, e,
665 _("%s: Warning: Read error at byte %s, reading %lu bytes"),
666 quotearg_colon (name), STRINGIFY_BIGINT (offset, buf),
667 (unsigned long) size));
670 void
671 read_fatal (char const *name)
673 call_arg_fatal ("read", name);
676 void
677 read_fatal_details (char const *name, off_t offset, size_t size)
679 char buf[UINTMAX_STRSIZE_BOUND];
680 int e = errno;
681 FATAL_ERROR ((0, e,
682 _("%s: Read error at byte %s, reading %lu bytes"),
683 quotearg_colon (name), STRINGIFY_BIGINT (offset, buf),
684 (unsigned long) size));
687 void
688 readlink_error (char const *name)
690 call_arg_error ("readlink", name);
693 void
694 readlink_warn (char const *name)
696 call_arg_warn ("readlink", name);
699 void
700 savedir_error (char const *name)
702 call_arg_error ("savedir", name);
705 void
706 savedir_warn (char const *name)
708 call_arg_warn ("savedir", name);
711 void
712 seek_error (char const *name)
714 call_arg_error ("seek", name);
717 void
718 seek_error_details (char const *name, off_t offset)
720 char buf[UINTMAX_STRSIZE_BOUND];
721 int e = errno;
722 ERROR ((0, e, _("%s: Cannot seek to %s"),
723 quotearg_colon (name),
724 STRINGIFY_BIGINT (offset, buf)));
727 void
728 seek_warn (char const *name)
730 call_arg_warn ("seek", name);
733 void
734 seek_warn_details (char const *name, off_t offset)
736 char buf[UINTMAX_STRSIZE_BOUND];
737 int e = errno;
738 WARN ((0, e, _("%s: Warning: Cannot seek to %s"),
739 quotearg_colon (name),
740 STRINGIFY_BIGINT (offset, buf)));
743 void
744 symlink_error (char const *contents, char const *name)
746 int e = errno;
747 ERROR ((0, e, _("%s: Cannot create symlink to %s"),
748 quotearg_colon (name), quote_n (1, contents)));
751 void
752 stat_error (char const *name)
754 call_arg_error ("stat", name);
757 void
758 stat_warn (char const *name)
760 call_arg_warn ("stat", name);
763 void
764 truncate_error (char const *name)
766 call_arg_error ("truncate", name);
769 void
770 truncate_warn (char const *name)
772 call_arg_warn ("truncate", name);
775 void
776 unlink_error (char const *name)
778 call_arg_error ("unlink", name);
781 void
782 utime_error (char const *name)
784 call_arg_error ("utime", name);
787 void
788 waitpid_error (char const *name)
790 call_arg_error ("waitpid", name);
793 void
794 write_error (char const *name)
796 call_arg_error ("write", name);
799 void
800 write_error_details (char const *name, ssize_t status, size_t size)
802 if (status < 0)
803 write_error (name);
804 else
805 ERROR ((0, 0, _("%s: Wrote only %lu of %lu bytes"),
806 name, (unsigned long) status, (unsigned long) record_size));
809 void
810 write_fatal (char const *name)
812 call_arg_fatal ("write", name);
815 void
816 write_fatal_details (char const *name, ssize_t status, size_t size)
818 write_error_details (name, status, size);
819 fatal_exit ();
823 /* Fork, aborting if unsuccessful. */
824 pid_t
825 xfork (void)
827 pid_t p = fork ();
828 if (p == (pid_t) -1)
829 call_arg_fatal ("fork", _("child process"));
830 return p;
833 /* Create a pipe, aborting if unsuccessful. */
834 void
835 xpipe (int fd[2])
837 if (pipe (fd) < 0)
838 call_arg_fatal ("pipe", _("interprocess channel"));
841 /* Return an unambiguous printable representation, allocated in slot N,
842 for NAME, suitable for diagnostics. */
843 char const *
844 quote_n (int n, char const *name)
846 return quotearg_n_style (n, locale_quoting_style, name);
849 /* Return an unambiguous printable representation of NAME, suitable
850 for diagnostics. */
851 char const *
852 quote (char const *name)
854 return quote_n (0, name);