Пример #1
0
void
siginfo_init(struct bsdtar *bsdtar)
{
	struct sigaction sa;

	/* Allocate space for internal structure. */
	if ((bsdtar->siginfo = malloc(sizeof(struct siginfo_data))) == NULL)
		bsdtar_errc(bsdtar, 1, errno, "malloc failed");

	/* Set the strings to NULL so that free() is safe. */
	bsdtar->siginfo->path = bsdtar->siginfo->oper = NULL;

	/* We want to catch SIGINFO, if it exists. */
	sa.sa_handler = siginfo_handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
#ifdef SIGINFO
	if (sigaction(SIGINFO, &sa, &bsdtar->siginfo->siginfo_old))
		bsdtar_errc(bsdtar, 1, errno, "sigaction(SIGINFO) failed");
#endif
#ifdef SIGUSR1
	/* ... and treat SIGUSR1 the same way as SIGINFO. */
	if (sigaction(SIGUSR1, &sa, &bsdtar->siginfo->sigusr1_old))
		bsdtar_errc(bsdtar, 1, errno, "sigaction(SIGUSR1) failed");
#endif
}
Пример #2
0
static void
build_dir(struct bsdtar *bsdtar, const char *dir, const char *diropt)
{
	struct stat sb;
	char * s;
	const char * dirseppos;

	/* We need a directory name and the config option. */
	assert(dir != NULL);
	assert(diropt != NULL); 

	/* Move through *dir and build all parent directories. */
	for (dirseppos = dir; *dirseppos != '\0'; ) {
		/* Move to the next '/', or the end of the string. */
		if ((dirseppos = strchr(dirseppos + 1, '/')) == NULL)
			dirseppos = dir + strlen(dir);

		/* Generate a string containing the parent directory. */
		if (asprintf(&s, "%.*s", (int)(dirseppos - dir), dir) == -1)
			bsdtar_errc(bsdtar, 1, errno, "No Memory");

		/* Does the parent directory exist already? */
		if (stat(s, &sb) == 0)
			goto nextdir;

		/* Did something go wrong? */
		if (errno != ENOENT)
			bsdtar_errc(bsdtar, 1, errno, "stat(%s)", s);

		/* Create the directory. */
		if (mkdir(s, 0700))
			bsdtar_errc(bsdtar, 1, errno, "error creating %s", s);

		/* Tell the user what we did. */
		fprintf(stderr, "Directory %s created for \"%s %s\"\n",
		    s, diropt, dir);

nextdir:
		free(s);
	}

	/* Make sure permissions on the directory are correct. */
	if (stat(dir, &sb))
		bsdtar_errc(bsdtar, 1, errno, "stat(%s)", dir);
	if (sb.st_mode & (S_IRWXG | S_IRWXO)) {
		if (chmod(dir, sb.st_mode & ~(S_IRWXG | S_IRWXO))) {
			bsdtar_errc(bsdtar, 1, errno,
			    "Cannot sanitize permissions on directory: %s",
			    dir);
		}
	}
}
Пример #3
0
void
siginfo_setinfo(struct bsdtar *bsdtar, const char * oper, const char * path,
    int64_t size)
{

	/* Free old operation and path strings. */
	free(bsdtar->siginfo->oper);
	free(bsdtar->siginfo->path);

	/* Duplicate strings and store entry size. */
	if ((bsdtar->siginfo->oper = strdup(oper)) == NULL)
		bsdtar_errc(bsdtar, 1, errno, "Cannot strdup");
	if ((bsdtar->siginfo->path = strdup(path)) == NULL)
		bsdtar_errc(bsdtar, 1, errno, "Cannot strdup");
	bsdtar->siginfo->size = size;
}
Пример #4
0
/* Add a command-line option to the delayed options queue. */
static void
optq_push(struct bsdtar *bsdtar, const char * opt_name, const char * opt_arg)
{
	struct delayedopt * opt;

	/* Create a delayed option structure. */
	if ((opt = malloc(sizeof(struct delayedopt))) == NULL)
		goto enomem;
	if ((opt->opt_name = strdup(opt_name)) == NULL)
		goto enomem;
	if (opt_arg == NULL)
		opt->opt_arg = NULL;
	else if ((opt->opt_arg = strdup(opt_arg)) == NULL)
		goto enomem;
	opt->next = NULL;

	/* Add to queue. */
	*(bsdtar->delopt_tail) = opt;
	bsdtar->delopt_tail = &opt->next;

	/* Success! */
	return;

enomem:
	bsdtar_errc(bsdtar, 1, errno, "Out of memory");
}
Пример #5
0
/*
 * Verify that the mode is correct.
 */
static void
only_mode(struct bsdtar *bsdtar, const char *opt, const char *valid_modes)
{
	if (strchr(valid_modes, bsdtar->mode) == NULL)
		bsdtar_errc(bsdtar, 1, 0,
		    "Option %s is not permitted in mode -%c",
		    opt, bsdtar->mode);
}
Пример #6
0
static void
set_mode(struct bsdtar *bsdtar, char opt)
{
	if (bsdtar->mode != '\0' && bsdtar->mode != opt)
		bsdtar_errc(bsdtar, 1, 0,
		    "Can't specify both -%c and -%c", opt, bsdtar->mode);
	bsdtar->mode = opt;
}
Пример #7
0
static void
initialize_matching(struct bsdtar *bsdtar)
{
	bsdtar->matching = malloc(sizeof(*bsdtar->matching));
	if (bsdtar->matching == NULL)
		bsdtar_errc(bsdtar, 1, errno, "No memory");
	memset(bsdtar->matching, 0, sizeof(*bsdtar->matching));
}
Пример #8
0
/*
 * Archive names specified in file.
 *
 * Unless --null was specified, a line containing exactly "-C" will
 * cause the next line to be a directory to pass to chdir().  If
 * --null is specified, then a line "-C" is just another filename.
 */
void
archive_names_from_file(struct bsdtar *bsdtar, struct archive *a)
{
	bsdtar->archive = a;

	bsdtar->next_line_is_dir = 0;
	process_lines(bsdtar, bsdtar->names_from_file,
	    archive_names_from_file_helper, bsdtar->option_null);
	if (bsdtar->next_line_is_dir)
		bsdtar_errc(bsdtar, 1, errno,
		    "Unexpected end of filename list; "
		    "directory expected after -C");
}
Пример #9
0
static void
set_mode(struct bsdtar * bsdtar, int opt, const char *optstr)
{

	/* Make sure we're not asking tarsnap to do two things at once. */
	if (bsdtar->mode != 0)
		bsdtar_errc(bsdtar, 1, 0,
		    "Can't specify both %s and %s", optstr, bsdtar->modestr);

	/* Set mode. */
	bsdtar->mode = opt;
	bsdtar->modestr = optstr;
}
Пример #10
0
void
test_for_append(struct bsdtar *bsdtar)
{
	struct stat s;

	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
		bsdtar_errc(bsdtar, 1, 0, "no files or directories specified");
	if (bsdtar->filename == NULL)
		bsdtar_errc(bsdtar, 1, 0, "Cannot append to stdout.");

	if (bsdtar->create_compression != 0)
		bsdtar_errc(bsdtar, 1, 0,
		    "Cannot append to %s with compression", bsdtar->filename);

	if (stat(bsdtar->filename, &s) != 0)
		return;

	if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cannot append to %s: not a regular file.",
		    bsdtar->filename);
}
Пример #11
0
/*
 * Add an entry to the dir list for 'u' mode.
 *
 * XXX TODO: Make this fast.
 */
static void
add_dir_list(struct bsdtar *bsdtar, const char *path,
    time_t mtime_sec, int mtime_nsec)
{
	struct archive_dir_entry	*p;

	/*
	 * Search entire list to see if this file has appeared before.
	 * If it has, override the timestamp data.
	 */
	p = bsdtar->archive_dir->head;
	while (p != NULL) {
		if (strcmp(path, p->name)==0) {
			p->mtime_sec = mtime_sec;
			p->mtime_nsec = mtime_nsec;
			return;
		}
		p = p->next;
	}

	p = malloc(sizeof(*p));
	if (p == NULL)
		bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read archive directory");

	p->name = strdup(path);
	if (p->name == NULL)
		bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read archive directory");
	p->mtime_sec = mtime_sec;
	p->mtime_nsec = mtime_nsec;
	p->next = NULL;
	if (bsdtar->archive_dir->tail == NULL) {
		bsdtar->archive_dir->head = bsdtar->archive_dir->tail = p;
	} else {
		bsdtar->archive_dir->tail->next = p;
		bsdtar->archive_dir->tail = p;
	}
}
Пример #12
0
static void
add_pattern(struct bsdtar *bsdtar, struct match **list, const char *pattern)
{
	struct match *match;
	size_t len;

	len = strlen(pattern);
	match = malloc(sizeof(*match) + len + 1);
	if (match == NULL)
		bsdtar_errc(bsdtar, 1, errno, "Out of memory");
	strcpy(match->pattern, pattern);
	/* Both "foo/" and "foo" should match "foo/bar". */
	if (len && match->pattern[len - 1] == '/')
		match->pattern[len - 1] = '\0';
	match->next = *list;
	*list = match;
	match->matches = 0;
}
Пример #13
0
/* Load keys from the specified file.  Return success or failure. */
static int
load_keys(struct bsdtar *bsdtar, const char *path)
{
	uint64_t machinenum;

	/* Load the key file. */
	if (keyfile_read(path, &machinenum, ~0))
		goto err0;

	/* Check the machine number. */
	if ((bsdtar->machinenum != (uint64_t)(-1)) &&
	    (machinenum != bsdtar->machinenum))
		bsdtar_errc(bsdtar, 1, 0,
		    "Key file belongs to wrong machine: %s", path);
	bsdtar->machinenum = machinenum;

	/* Success! */
	return (0);

err0:
	/* Failure! */
	return (-1);
}
Пример #14
0
/* Process options from the specified file, if it exists. */
static void
configfile(struct bsdtar *bsdtar, const char *fname)
{
	struct stat sb;

	/*
	 * If we had --no-config-exclude (or --no-config-include) earlier,
	 * we do not want to process any --exclude (or --include) options
	 * from now onwards.
	 */
	bsdtar->option_no_config_exclude_set =
	    bsdtar->option_no_config_exclude;
	bsdtar->option_no_config_include_set =
	    bsdtar->option_no_config_include;

	/* If the file doesn't exist, do nothing. */
	if (stat(fname, &sb)) {
		if (errno == ENOENT)
			return;

		/*
		 * Something bad happened.  Note that this could occur if
		 * there is no configuration file and part of the path to
		 * where we're looking for a configuration file exists and
		 * is a non-directory (e.g., if /usr/local/etc is a file);
		 * we're going to error out if this happens, since reporting
		 * a spurious error in such an odd circumstance is better
		 * than failing to report an error if there really is a
		 * configuration file.
		 */
		bsdtar_errc(bsdtar, 1, errno, "stat(%s)", fname);
	}

	/* Process the file. */
	process_lines(bsdtar, fname, configfile_helper, 0);
}
Пример #15
0
void
tarsnap_mode_c(struct bsdtar *bsdtar)
{
	struct archive *a;
	size_t i;

	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
		bsdtar_errc(bsdtar, 1, 0, "no files or directories specified");

	for (i = 0; bsdtar->argv[i] != NULL; i++) {
		if (bsdtar->argv[i][0] == '-' && bsdtar->argv[i][1] == '-') {
			bsdtar_warnc(bsdtar, 0,
			    "List of objects to archive includes '%s'."
			    "  This might not be what you intended.",
			    bsdtar->argv[i]);
			break;
		}
	}

	a = archive_write_new();

	/* We only support the pax restricted format. */
	archive_write_set_format_pax_restricted(a);

	/* Set the block size to zero -- we don't want buffering. */
	archive_write_set_bytes_per_block(a, 0);

	/* Open the archive, keeping a cookie for talking to the tape layer. */
	bsdtar->write_cookie = archive_write_open_multitape(a,
	    bsdtar->machinenum, bsdtar->cachedir, bsdtar->tapenames[0],
	    bsdtar->argc_orig, bsdtar->argv_orig,
	    bsdtar->option_print_stats, bsdtar->option_dryrun,
	    bsdtar->creationtime);
	if (bsdtar->write_cookie == NULL)
		bsdtar_errc(bsdtar, 1, 0, "%s", archive_error_string(a));

	/*
	 * Remember the device and inode numbers of the cache directory, so
	 * that we can skip is in write_hierarchy().
	 */
	if (getdevino(a, bsdtar->cachedir,
	    &bsdtar->cachedir_dev, &bsdtar->cachedir_ino))
		bsdtar_errc(bsdtar, 1, 0, "%s", archive_error_string(a));

	/* If the chunkification cache is enabled, read it. */
	if ((bsdtar->cachecrunch < 2) && (bsdtar->cachedir != NULL)) {
		bsdtar->chunk_cache = ccache_read(bsdtar->cachedir);
		if (bsdtar->chunk_cache == NULL)
			bsdtar_errc(bsdtar, 1, errno, "Error reading cache");
	}

	write_archive(a, bsdtar);

	/*
	 * If this isn't a dry run and we're running with the chunkification
	 * cache enabled, write the cache back to disk.
	 */
	if ((bsdtar->option_dryrun == 0) && (bsdtar->cachecrunch < 2)) {
		if (ccache_write(bsdtar->chunk_cache, bsdtar->cachedir))
			bsdtar_errc(bsdtar, 1, errno, "Error writing cache");
	}

	/* Free the chunkification cache. */
	if (bsdtar->cachecrunch < 2)
		ccache_free(bsdtar->chunk_cache);
}
Пример #16
0
int
main(int argc, char **argv)
{
	struct bsdtar		*bsdtar;
	int			 opt;
	char			 possible_help_request;
	char			 buff[16];
	char			 cachedir[PATH_MAX + 1];
	struct passwd		*pws;
	char			*conffile;
	const char		*missingkey;
	time_t			 now;
	size_t 			 i;

	WARNP_INIT;

	/* Use a pointer for consistency. */
	bsdtar = bsdtar_init();

#if defined(_WIN32) && !defined(__CYGWIN__)
	/* Make sure open() function will be used with a binary mode. */
	/* on cygwin, we need something similar, but instead link against */
	/* a special startup object, binmode.o */
	_set_fmode(_O_BINARY);
#endif

	/* Need bsdtar->progname before calling bsdtar_warnc. */
	if (*argv == NULL)
		bsdtar->progname = "tarsnap";
	else {
#if defined(_WIN32) && !defined(__CYGWIN__)
		bsdtar->progname = strrchr(*argv, '\\');
#else
		bsdtar->progname = strrchr(*argv, '/');
#endif
		if (bsdtar->progname != NULL)
			bsdtar->progname++;
		else
			bsdtar->progname = *argv;
	}

	/* We don't have a machine # yet. */
	bsdtar->machinenum = (uint64_t)(-1);

	/* Allocate space for archive names; at most argc of them. */
	if ((bsdtar->tapenames = malloc(argc * sizeof(const char *))) == NULL)
		bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");
	bsdtar->ntapes = 0;

	/* Allocate space for config file names; at most argc of them. */
	if ((bsdtar->configfiles = malloc(argc * sizeof(const char *))) == NULL)
		bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");
	bsdtar->nconfigfiles = 0;

	time(&now);
	bsdtar->creationtime = now;

	if (setlocale(LC_ALL, "") == NULL)
		bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
#if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
	bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
#endif
	possible_help_request = 0;

	/* Initialize key cache.  We don't have any keys yet. */
	if (crypto_keys_init())
		exit(1);

	/*
	 * Make stdout line-buffered (if possible) so that operations such as
	 * "tarsnap --list-archives | more" will run more smoothly.  The only
	 * downside to this is a slight performance cost; but we don't write
	 * enough data to stdout for that to matter.
	 */
	setvbuf(stdout, NULL, _IONBF, 0);

	/*
	 * Unless specified otherwise, we consider ourselves to be
	 * constructing a snapshot of the disk as it is right now.
	 */
	/*
	 * POSIX doesn't provide any mechanism for distinguishing between
	 * an error and the time (time_t)(-1).  Since we only use this to
	 * avoid race conditions in the chunkification cache (i.e., so
	 * that we can determine if a file has been modified since it was
	 * last backed up), and hopefully nobody will have any files with
	 * negative last-modified dates, an error return of (-1) can be
	 * handled the same was as a legitimate return of (-1): Nothing
	 * gets cached.
	 */
	bsdtar->snaptime = time(NULL);

	/* Store original argument vector. */
	bsdtar->argc_orig = argc;
	bsdtar->argv_orig = argv;

	/* Look up the current user and his home directory. */
	if ((pws = getpwuid(geteuid())) != NULL)
		if ((bsdtar->homedir = strdup(pws->pw_dir)) == NULL)
			bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");

	/* Look up uid of current user for future reference */
	bsdtar->user_uid = geteuid();

	/* Default: preserve mod time on extract */
	bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;

	/* Default: Perform basic security checks. */
	bsdtar->extract_flags |= SECURITY;

	/* Defaults for root user: */
	if (bsdtar_is_privileged(bsdtar)) {
		/* --same-owner */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
		/* -p */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
	}

	bsdtar->argv = argv;
	bsdtar->argc = argc;

	/* We gather some options in a 'delayed options queue'. */
	bsdtar->delopt = NULL;
	bsdtar->delopt_tail = &bsdtar->delopt;

	/*
	 * Comments following each option indicate where that option
	 * originated:  SUSv2, POSIX, GNU tar, star, etc.  If there's
	 * no such comment, then I don't know of anyone else who
	 * implements that option.
	 */
	while ((opt = bsdtar_getopt(bsdtar)) != -1) {
		switch (opt) {
		case OPTION_AGGRESSIVE_NETWORKING: /* tarsnap */
			optq_push(bsdtar, "aggressive-networking", NULL);
			break;
		case 'B': /* GNU tar */
			/* libarchive doesn't need this; just ignore it. */
			break;
		case 'C': /* GNU tar */
			if (strlen(bsdtar->optarg) == 0)
				bsdtar_errc(bsdtar, 1, 0,
				    "Meaningless option: -C ''");

			set_chdir(bsdtar, bsdtar->optarg);
			break;
		case 'c': /* SUSv2 */
			set_mode(bsdtar, opt, "-c");
			break;
		case OPTION_CACHEDIR: /* multitar */
			optq_push(bsdtar, "cachedir", bsdtar->optarg);
			break;
		case OPTION_CHECK_LINKS: /* GNU tar */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_CHECKPOINT_BYTES: /* tarsnap */
			optq_push(bsdtar, "checkpoint-bytes", bsdtar->optarg);
			break;
		case OPTION_CHROOT: /* NetBSD */
			bsdtar->option_chroot = 1;
			break;
		case OPTION_CONFIGFILE:
			bsdtar->configfiles[bsdtar->nconfigfiles++] =
			    bsdtar->optarg;
			break;
		case OPTION_CREATIONTIME: /* tarsnap */
			errno = 0;
			bsdtar->creationtime = strtol(bsdtar->optarg,
			    NULL, 0);
			if ((errno) || (bsdtar->creationtime == 0))
				bsdtar_errc(bsdtar, 1, 0,
				    "Invalid --creationtime argument: %s",
				    bsdtar->optarg);
			break;
		case OPTION_CSV_FILE: /* tarsnap */
			if (bsdtar->option_csv_filename != NULL)
				bsdtar_errc(bsdtar, 1, errno,
				    "Two --csv-file options given.\n");
			if ((bsdtar->option_csv_filename = strdup(
			    bsdtar->optarg)) == NULL)
				bsdtar_errc(bsdtar, 1, errno, "Out of memory");
			break;
		case 'd': /* multitar */
			set_mode(bsdtar, opt, "-d");
			break;
		case OPTION_DISK_PAUSE: /* tarsnap */
			optq_push(bsdtar, "disk-pause", bsdtar->optarg);
			break;
		case OPTION_DRYRUN: /* tarsnap */
			bsdtar->option_dryrun = 1;
			break;
		case OPTION_EXCLUDE: /* GNU tar */
			optq_push(bsdtar, "exclude", bsdtar->optarg);
			break;
		case 'f': /* multitar */
			bsdtar->tapenames[bsdtar->ntapes++] = bsdtar->optarg;
			break;
		case OPTION_FSCK: /* multitar */
			set_mode(bsdtar, opt, "--fsck");
			break;
		case OPTION_FSCK_PRUNE: /* multitar */
			set_mode(bsdtar, opt, "--fsck-prune");
			break;
		case 'H': /* BSD convention */
			bsdtar->symlink_mode = 'H';
			break;
		case 'h': /* Linux Standards Base, gtar; synonym for -L */
			bsdtar->symlink_mode = 'L';
			/* Hack: -h by itself is the "help" command. */
			possible_help_request = 1;
			break;
		case OPTION_HELP: /* GNU tar, others */
			long_help(bsdtar);
			exit(0);
			break;
		case OPTION_HUMANIZE_NUMBERS: /* tarsnap */
			optq_push(bsdtar, "humanize-numbers", NULL);
			break;
		case 'I': /* GNU tar */
			/*
			 * TODO: Allow 'names' to come from an archive,
			 * not just a text file.  Design a good UI for
			 * allowing names and mode/owner to be read
			 * from an archive, with contents coming from
			 * disk.  This can be used to "refresh" an
			 * archive or to design archives with special
			 * permissions without having to create those
			 * permissions on disk.
			 */
			bsdtar->names_from_file = bsdtar->optarg;
			break;
		case OPTION_INCLUDE:
			optq_push(bsdtar, "include", bsdtar->optarg);
			break;
		case OPTION_INSANE_FILESYSTEMS:
			optq_push(bsdtar, "insane-filesystems", NULL);
			break;
		case 'k': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
			break;
		case OPTION_KEEP_GOING: /* tarsnap */
			bsdtar->option_keep_going = 1;
			break;
		case OPTION_KEEP_NEWER_FILES: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
			break;
		case OPTION_KEYFILE: /* tarsnap */
			optq_push(bsdtar, "keyfile", bsdtar->optarg);
			break;
		case 'L': /* BSD convention */
			bsdtar->symlink_mode = 'L';
			break;
	        case 'l': /* SUSv2 and GNU tar beginning with 1.16 */
			/* GNU tar 1.13  used -l for --one-file-system */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_LIST_ARCHIVES: /* multitar */
			set_mode(bsdtar, opt, "--list-archives");
			break;
		case OPTION_LOWMEM: /* tarsnap */
			optq_push(bsdtar, "lowmem", NULL);
			break;
		case 'm': /* SUSv2 */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
			break;
		case OPTION_MAXBW: /* tarsnap */
			optq_push(bsdtar, "maxbw", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE_DOWN: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate-down", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE_UP: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate-up", bsdtar->optarg);
			break;
		case 'n': /* GNU tar */
			bsdtar->option_no_subdirs = 1;
			break;
	        /*
		 * Selecting files by time:
		 *    --newer-?time='date' Only files newer than 'date'
		 *    --newer-?time-than='file' Only files newer than time
		 *         on specified file (useful for incremental backups)
		 * TODO: Add corresponding "older" options to reverse these.
		 */
		case OPTION_NEWER_CTIME: /* GNU tar */
			bsdtar->newer_ctime_sec = get_date(now, bsdtar->optarg);
			break;
		case OPTION_NEWER_CTIME_THAN:
			{
				struct stat st;
				if (stat(bsdtar->optarg, &st) != 0)
					bsdtar_errc(bsdtar, 1, 0,
					    "Can't open file %s", bsdtar->optarg);
				bsdtar->newer_ctime_sec = st.st_ctime;
				bsdtar->newer_ctime_nsec =
				    ARCHIVE_STAT_CTIME_NANOS(&st);
			}
			break;
		case OPTION_NEWER_MTIME: /* GNU tar */
			bsdtar->newer_mtime_sec = get_date(now, bsdtar->optarg);
			break;
		case OPTION_NEWER_MTIME_THAN:
			{
				struct stat st;
				if (stat(bsdtar->optarg, &st) != 0)
					bsdtar_errc(bsdtar, 1, 0,
					    "Can't open file %s", bsdtar->optarg);
				bsdtar->newer_mtime_sec = st.st_mtime;
				bsdtar->newer_mtime_nsec =
				    ARCHIVE_STAT_MTIME_NANOS(&st);
			}
			break;
		case OPTION_NODUMP: /* star */
			optq_push(bsdtar, "nodump", NULL);
			break;
		case OPTION_NOISY_WARNINGS: /* tarsnap */
			tarsnap_opt_noisy_warnings = 1;
			break;
		case OPTION_NORMALMEM:
			optq_push(bsdtar, "normalmem", NULL);
			break;
		case OPTION_NO_AGGRESSIVE_NETWORKING:
			optq_push(bsdtar, "no-aggressive-networking", NULL);
			break;
		case OPTION_NO_CONFIG_EXCLUDE:
			optq_push(bsdtar, "no-config-exclude", NULL);
			break;
		case OPTION_NO_CONFIG_INCLUDE:
			optq_push(bsdtar, "no-config-include", NULL);
			break;
		case OPTION_NO_DEFAULT_CONFIG:
			bsdtar->option_no_default_config = 1;
			break;
		case OPTION_NO_DISK_PAUSE:
			optq_push(bsdtar, "no-disk-pause", NULL);
			break;
		case OPTION_NO_HUMANIZE_NUMBERS:
			optq_push(bsdtar, "no-humanize-numbers", NULL);
			break;
		case OPTION_NO_INSANE_FILESYSTEMS:
			optq_push(bsdtar, "no-insane-filesystems", NULL);
			break;
		case OPTION_NO_MAXBW:
			optq_push(bsdtar, "no-maxbw", NULL);
			break;
		case OPTION_NO_MAXBW_RATE_DOWN:
			optq_push(bsdtar, "no-maxbw-rate-down", NULL);
			break;
		case OPTION_NO_MAXBW_RATE_UP:
			optq_push(bsdtar, "no-maxbw-rate-up", NULL);
			break;
		case OPTION_NO_NODUMP:
			optq_push(bsdtar, "no-nodump", NULL);
			break;
		case OPTION_NO_PRINT_STATS:
			optq_push(bsdtar, "no-print-stats", NULL);
			break;
		case OPTION_NO_QUIET:
			optq_push(bsdtar, "no-quiet", NULL);
			break;
		case OPTION_NO_RETRY_FOREVER:
			optq_push(bsdtar, "no-retry-forever", NULL);
			break;
		case OPTION_NO_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_NO_SNAPTIME:
			optq_push(bsdtar, "no-snaptime", NULL);
			break;
		case OPTION_NO_STORE_ATIME:
			optq_push(bsdtar, "no-store-atime", NULL);
			break;
		case OPTION_NO_TOTALS:
			optq_push(bsdtar, "no-totals", NULL);
			break;
		case OPTION_NUKE: /* tarsnap */
			set_mode(bsdtar, opt, "--nuke");
			break;
		case OPTION_NULL: /* GNU tar */
			bsdtar->option_null++;
			break;
		case OPTION_NUMERIC_OWNER: /* GNU tar */
			bsdtar->option_numeric_owner++;
			break;
		case 'O': /* GNU tar */
			bsdtar->option_stdout = 1;
			break;
		case 'o':
			bsdtar->option_no_owner = 1;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
			bsdtar->option_dont_traverse_mounts = 1;
			break;
		case 'P': /* GNU tar */
			bsdtar->extract_flags &= ~SECURITY;
			bsdtar->option_absolute_paths = 1;
			break;
		case 'p': /* GNU tar, star */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_PRINT_STATS: /* multitar */
			bsdtar->option_print_stats = 1;
			break;
		case 'q': /* FreeBSD GNU tar --fast-read, NetBSD -q */
			bsdtar->option_fast_read = 1;
			break;
		case OPTION_QUIET:
			optq_push(bsdtar, "quiet", NULL);
			break;
		case 'r': /* multitar */
			set_mode(bsdtar, opt, "-r");
			break;
		case OPTION_RECOVER:
			set_mode(bsdtar, opt, "--recover");
			break;
		case OPTION_RETRY_FOREVER:
			optq_push(bsdtar, "retry-forever", NULL);
			break;
		case OPTION_SNAPTIME: /* multitar */
			optq_push(bsdtar, "snaptime", bsdtar->optarg);
			break;
		case OPTION_STORE_ATIME: /* multitar */
			optq_push(bsdtar, "store-atime", NULL);
			break;
		case 'S': /* NetBSD pax-as-tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_SPARSE;
			break;
		case 's': /* NetBSD pax-as-tar */
#if HAVE_REGEX_H
			add_substitution(bsdtar, bsdtar->optarg);
#else
			bsdtar_warnc(bsdtar, 0,
			    "-s is not supported by this version of tarsnap");
			usage(bsdtar);
#endif
			break;
		case OPTION_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
			errno = 0;
			bsdtar->strip_components = strtol(bsdtar->optarg,
			    NULL, 0);
			if (errno)
				bsdtar_errc(bsdtar, 1, 0,
				    "Invalid --strip-components argument: %s",
				    bsdtar->optarg);
			break;
		case 'T': /* GNU tar */
			bsdtar->names_from_file = bsdtar->optarg;
			break;
		case 't': /* SUSv2 */
			set_mode(bsdtar, opt, "-t");
			bsdtar->verbose++;
			break;
		case OPTION_TOTALS: /* GNU tar */
			optq_push(bsdtar, "totals", NULL);
			break;
		case 'U': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
			bsdtar->option_unlink_first = 1;
			break;
		case 'v': /* SUSv2 */
			bsdtar->verbose++;
			break;
		case OPTION_VERSION: /* GNU convention */
			version();
			break;
		case OPTION_VERYLOWMEM: /* tarsnap */
			optq_push(bsdtar, "verylowmem", NULL);
			break;
#if 0
		/*
		 * The -W longopt feature is handled inside of
		 * bsdtar_getopt(), so -W is not available here.
		 */
		case 'W': /* Obscure GNU convention. */
			break;
#endif
		case 'w': /* SUSv2 */
			bsdtar->option_interactive = 1;
			break;
		case 'X': /* GNU tar */
			if (exclude_from_file(bsdtar, bsdtar->optarg))
				bsdtar_errc(bsdtar, 1, 0,
				    "failed to process exclusions from file %s",
				    bsdtar->optarg);
			break;
		case 'x': /* SUSv2 */
			set_mode(bsdtar, opt, "-x");
			break;
		default:
			usage(bsdtar);
		}
	}

	/*
	 * Sanity-check options.
	 */

	/*
	 * If --print-stats was specified but no mode was set, then
	 * --print-stats *is* the mode.
	 */
	if ((bsdtar->mode == '\0') && (bsdtar->option_print_stats == 1))
		set_mode(bsdtar, OPTION_PRINT_STATS, "--print-stats");

	/* If no "real" mode was specified, treat -h as --help. */
	if ((bsdtar->mode == '\0') && possible_help_request) {
		long_help(bsdtar);
		exit(0);
	}

	/*
	 * If we're doing a dry run and the user hasn't specified an archive
	 * name via -f, use a fake name.  This will result in the statistics
	 * printed by --print-stats being a few bytes off, since the archive
	 * name is included in the metadata block... but we're going to be a
	 * few bytes off anyway since the command line, including "--dry-run"
	 * is included in the metadata.
	 */
	if (bsdtar->option_dryrun && (bsdtar->ntapes == 0))
		bsdtar->tapenames[bsdtar->ntapes++] = "(dry-run)";

	/* At this point we must have a mode set. */
	if (bsdtar->mode == '\0')
		bsdtar_errc(bsdtar, 1, 0,
		    "Must specify one of -c, -d, -r, -t, -x,"
		    " --list-archives, --print-stats,"
		    " --fsck, --fsck-prune, or --nuke");

	/* Process "delayed" command-line options which we queued earlier. */
	while (bsdtar->delopt != NULL) {
		dooption(bsdtar, bsdtar->delopt->opt_name,
		    bsdtar->delopt->opt_arg, 0);
		optq_pop(bsdtar);
	}

	/* Process config files passed on the command line. */
	for (i = 0; i < bsdtar->nconfigfiles; i++)
		configfile(bsdtar, bsdtar->configfiles[i]);

	/* If we do not have --no-default-config, process default configs. */
	if (bsdtar->option_no_default_config == 0) {
		/* Process options from ~/.tarsnaprc. */
		if (bsdtar->homedir != NULL) {
			if (asprintf(&conffile, "%s/.tarsnaprc",
			    bsdtar->homedir) == -1)
				bsdtar_errc(bsdtar, 1, errno, "No memory");

			configfile(bsdtar, conffile);

			/* Free string allocated by asprintf. */
			free(conffile);
		}

		/* Process options from system-wide tarsnap.conf. */
		configfile(bsdtar, ETC_TARSNAP_CONF);
	}

	/* Continue with more sanity-checking. */
	if ((bsdtar->ntapes == 0) &&
	    (bsdtar->mode != OPTION_PRINT_STATS &&
	     bsdtar->mode != OPTION_LIST_ARCHIVES &&
	     bsdtar->mode != OPTION_RECOVER &&
	     bsdtar->mode != OPTION_FSCK &&
	     bsdtar->mode != OPTION_FSCK_PRUNE &&
	     bsdtar->mode != OPTION_NUKE))
		bsdtar_errc(bsdtar, 1, 0,
		    "Archive name must be specified");
	if ((bsdtar->ntapes > 1) &&
	    (bsdtar->mode != OPTION_PRINT_STATS &&
	     bsdtar->mode != 'd'))
		bsdtar_errc(bsdtar, 1, 0,
		    "Option -f may only be specified once in mode %s",
		    bsdtar->modestr);
	if ((bsdtar->mode == 'c') &&
	    (strlen(bsdtar->tapenames[0]) > 1023))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cannot create an archive with a name > 1023 characters");
	if ((bsdtar->mode == 'c') &&
	    (strlen(bsdtar->tapenames[0]) == 0))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cannot create an archive with an empty name");
	if ((bsdtar->cachedir == NULL) &&
	    (((bsdtar->mode == 'c') && (!bsdtar->option_dryrun)) ||
	     bsdtar->mode == 'd' ||
	     bsdtar->mode == OPTION_RECOVER ||
	     bsdtar->mode == OPTION_FSCK ||
	     bsdtar->mode == OPTION_FSCK_PRUNE ||
	     bsdtar->mode == OPTION_PRINT_STATS))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cache directory must be specified for %s",
		    bsdtar->modestr);
	if (tarsnap_opt_aggressive_networking != 0) {
		if ((bsdtar->bwlimit_rate_up != 0) ||
		    (bsdtar->bwlimit_rate_down != 0)) {
			bsdtar_warnc(bsdtar, 0,
			    "--aggressive-networking is incompatible with"
			    " --maxbw-rate options;\n"
			    "         disabling --aggressive-networking");
			tarsnap_opt_aggressive_networking = 0;
		}
	}

	/*
	 * The -f option doesn't make sense for --list-archives, --fsck,
	 * --fsck-prune, or --nuke.
	 */
	if ((bsdtar->ntapes > 0) &&
	    (bsdtar->mode != OPTION_PRINT_STATS))
		only_mode(bsdtar, "-f", "cxtdr");

	/*
	 * These options don't make sense for the "delete" and "convert to
	 * tar" modes.
	 */
	if (bsdtar->pending_chdir)
		only_mode(bsdtar, "-C", "cxt");
	if (bsdtar->names_from_file)
		only_mode(bsdtar, "-T", "cxt");
	if (bsdtar->newer_ctime_sec || bsdtar->newer_ctime_nsec)
		only_mode(bsdtar, "--newer", "cxt");
	if (bsdtar->newer_mtime_sec || bsdtar->newer_mtime_nsec)
		only_mode(bsdtar, "--newer-mtime", "cxt");
	if (bsdtar->option_absolute_paths)
		only_mode(bsdtar, "-P", "cxt");
	if (bsdtar->option_null)
		only_mode(bsdtar, "--null", "cxt");

	/* Check options only permitted in certain modes. */
	if (bsdtar->option_dont_traverse_mounts)
		only_mode(bsdtar, "--one-file-system", "c");
	if (bsdtar->option_fast_read)
		only_mode(bsdtar, "--fast-read", "xt");
	if (bsdtar->option_no_subdirs)
		only_mode(bsdtar, "-n", "c");
	if (bsdtar->option_no_owner)
		only_mode(bsdtar, "-o", "x");
	if (bsdtar->option_stdout)
		only_mode(bsdtar, "-O", "xt");
	if (bsdtar->option_unlink_first)
		only_mode(bsdtar, "-U", "x");
	if (bsdtar->option_warn_links)
		only_mode(bsdtar, "--check-links", "c");
	if (bsdtar->option_dryrun)
		only_mode(bsdtar, "--dry-run", "c");

	/* Check other parameters only permitted in certain modes. */
	if (bsdtar->symlink_mode != '\0') {
		strcpy(buff, "-?");
		buff[1] = bsdtar->symlink_mode;
		only_mode(bsdtar, buff, "c");
	}
	if (bsdtar->strip_components != 0)
		only_mode(bsdtar, "--strip-components", "xt");

	/*
	 * If the keyfile in the config file is invalid but we're doing a
	 * dryrun, continue anyway (and don't use a cachedir).
	 */
	if (bsdtar->config_file_keyfile_failed && bsdtar->option_dryrun &&
	    bsdtar->cachedir != NULL) {
		bsdtar_warnc(bsdtar, 0,
		    "Ignoring cachedir due to missing or invalid "
		    "keyfile in config file.");
		free(bsdtar->cachedir);
		bsdtar->cachedir = NULL;
	}

	/*
	 * Canonicalize the path to the cache directories.  This is
	 * necessary since the tar code can change directories.
	 */
	if (bsdtar->cachedir != NULL) {
		build_dir(bsdtar, bsdtar->cachedir, "--cachedir");
		if (realpath(bsdtar->cachedir, cachedir) == NULL)
			bsdtar_errc(bsdtar, 1, errno, "realpath(%s)",
			    bsdtar->cachedir);
		free(bsdtar->cachedir);
		if ((bsdtar->cachedir = strdup(cachedir)) == NULL)
			bsdtar_errc(bsdtar, 1, errno, "Out of memory");
	}

	/* If we're running --fsck, figure out which key to use. */
	if (bsdtar->mode == OPTION_FSCK) {
		if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_PUT) == NULL)
			bsdtar->mode = OPTION_FSCK_WRITE;
		else if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE) == NULL)
			bsdtar->mode = OPTION_FSCK_DELETE;
		else
			bsdtar_errc(bsdtar, 1, 0,
			    "The write or delete authorization key is"
			    " required for --fsck but is not available");
	}

	/* If we're running --recover, figure out which key to use. */
	if (bsdtar->mode == OPTION_RECOVER) {
		if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_PUT) == NULL)
			bsdtar->mode = OPTION_RECOVER_WRITE;
		else if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE) == NULL)
			bsdtar->mode = OPTION_RECOVER_DELETE;
		else
			bsdtar_errc(bsdtar, 1, 0,
			    "The write or delete authorization key is"
			    " required for --recover but is not available");
	}

	/* Make sure we have whatever keys we're going to need. */
	if (bsdtar->have_keys == 0) {
		if (!bsdtar->option_dryrun) {
			bsdtar_errc(bsdtar, 1, 0,
			    "Keys must be provided via --keyfile option");
		} else {
			if (bsdtar->cachedir != NULL) {
				bsdtar_errc(bsdtar, 1, 0,
				    "Option mismatch for --dry-run: cachedir"
				    " specified but no keyfile");
			}
			if (crypto_keys_generate(CRYPTO_KEYMASK_USER))
				bsdtar_errc(bsdtar, 1, 0,
				    "Error generating keys");
			if (bsdtar->option_print_stats)
				bsdtar_warnc(bsdtar, 0,
				    "Performing dry-run archival without keys\n"
				    "         (sizes may be slightly "
				    "inaccurate)");
		}
	}

	missingkey = NULL;
	switch (bsdtar->mode) {
	case 'c':
		if (argv_has_archive_directive(bsdtar))
			missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE | CRYPTO_KEYMASK_READ);
		else
			missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE);
		break;
	case OPTION_RECOVER_WRITE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE);
		break;
	case 'd':
	case OPTION_FSCK_PRUNE:
	case OPTION_FSCK_DELETE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ |
		    CRYPTO_KEYMASK_AUTH_DELETE);
		break;
	case OPTION_FSCK_WRITE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ |
		    CRYPTO_KEYMASK_AUTH_PUT);
		break;
	case OPTION_NUKE:
	case OPTION_RECOVER_DELETE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE);
		break;
	case OPTION_PRINT_STATS:
		/* We don't need keys for printing global stats. */
		if (bsdtar->ntapes == 0)
			break;

		/* FALLTHROUGH */
	case OPTION_LIST_ARCHIVES:
	case 'r':
	case 't':
	case 'x':
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ);
		break;
	}
	if (missingkey != NULL)
		bsdtar_errc(bsdtar, 1, 0,
		    "The %s key is required for %s but is not available",
		    missingkey, bsdtar->modestr);

	/* Tell the network layer how much bandwidth to use. */
	if (bsdtar->bwlimit_rate_up == 0)
		bsdtar->bwlimit_rate_up = 1000000000.;
	if (bsdtar->bwlimit_rate_down == 0)
		bsdtar->bwlimit_rate_down = 1000000000.;
	network_bwlimit(bsdtar->bwlimit_rate_down, bsdtar->bwlimit_rate_up);

	/* Perform the requested operation. */
	switch(bsdtar->mode) {
	case 'c':
		tarsnap_mode_c(bsdtar);
		break;
	case 'd':
		tarsnap_mode_d(bsdtar);
		break;
	case OPTION_FSCK_DELETE:
		tarsnap_mode_fsck(bsdtar, 0, 1);
		break;
	case OPTION_FSCK_PRUNE:
		tarsnap_mode_fsck(bsdtar, 1, 1);
		break;
	case OPTION_FSCK_WRITE:
		tarsnap_mode_fsck(bsdtar, 0, 0);
		break;
	case OPTION_PRINT_STATS:
		tarsnap_mode_print_stats(bsdtar);
		break;
	case OPTION_RECOVER_DELETE:
		tarsnap_mode_recover(bsdtar, 1);
		break;
	case OPTION_RECOVER_WRITE:
		tarsnap_mode_recover(bsdtar, 0);
		break;
	case OPTION_LIST_ARCHIVES:
		tarsnap_mode_list_archives(bsdtar);
		break;
	case OPTION_NUKE:
		tarsnap_mode_nuke(bsdtar);
		break;
	case 'r':
		tarsnap_mode_r(bsdtar);
		break;
	case 't':
		tarsnap_mode_t(bsdtar);
		break;
	case 'x':
		tarsnap_mode_x(bsdtar);
		break;
	}

#ifdef DEBUG_SELECTSTATS
	double N, mu, va, max;

	network_getselectstats(&N, &mu, &va, &max);
	fprintf(stderr, "Time-between-select-calls statistics:\n");
	fprintf(stderr, "N = %6g   mu = %12g ms  "
	    "va = %12g ms^2  max = %12g ms\n",
	    N, mu * 1000, va * 1000000, max * 1000);
#endif

#ifdef PROFILE
	/*
	 * If we're compiling with profiling turned on, chdir to a directory
	 * into which we're likely to be able to write to before exiting.
	 */
	if (bsdtar->cachedir != NULL)
		chdir(cachedir);
#endif

	if (bsdtar->return_value != 0)
		bsdtar_warnc(bsdtar, 0,
		    "Error exit delayed from previous errors.");
	return (bsdtar->return_value);
}
Пример #17
0
/* Process a line of configuration file or a command-line option. */
static void
dooption(struct bsdtar *bsdtar, const char * conf_opt,
    const char * conf_arg, int fromconffile)
{
	struct stat st;
	char *eptr;

	if (strcmp(conf_opt, "aggressive-networking") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_aggressive_networking_set)
			goto optset;

		tarsnap_opt_aggressive_networking = 1;
		bsdtar->option_aggressive_networking_set = 1;
	} else if (strcmp(conf_opt, "cachedir") == 0) {
		if (bsdtar->cachedir != NULL)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		if ((bsdtar->cachedir = strdup(conf_arg)) == NULL)
			bsdtar_errc(bsdtar, 1, errno, "Out of memory");
	} else if (strcmp(conf_opt, "checkpoint-bytes") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (tarsnap_opt_checkpointbytes != (uint64_t)(-1))
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		if (humansize_parse(conf_arg, &tarsnap_opt_checkpointbytes))
			bsdtar_errc(bsdtar, 1, 0,
			    "Cannot parse #bytes per checkpoint: %s",
			    conf_arg);
		if (tarsnap_opt_checkpointbytes < 1000000)
			bsdtar_errc(bsdtar, 1, 0,
			    "checkpoint-bytes value must be at least 1M");
	} else if (strcmp(conf_opt, "disk-pause") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_disk_pause_set)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		bsdtar->disk_pause = strtol(conf_arg, NULL, 0);
		bsdtar->option_disk_pause_set = 1;
	} else if (strcmp(conf_opt, "exclude") == 0) {
		if (bsdtar->option_no_config_exclude_set)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		if (exclude(bsdtar, conf_arg))
			bsdtar_errc(bsdtar, 1, 0,
			    "Couldn't exclude %s", conf_arg);
	} else if (strcmp(conf_opt, "humanize-numbers") == 0) {
		if (bsdtar->option_humanize_numbers_set)
			goto optset;

		tarsnap_opt_humanize_numbers = 1;
		bsdtar->option_humanize_numbers_set = 1;
	} else if (strcmp(conf_opt, "include") == 0) {
		if (bsdtar->option_no_config_include_set)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		if (include(bsdtar, conf_arg))
			bsdtar_errc(bsdtar, 1, 0,
			    "Failed to add %s to inclusion list", conf_arg);
	} else if (strcmp(conf_opt, "insane-filesystems") == 0) {
		if (bsdtar->option_insane_filesystems_set)
			goto optset;

		bsdtar->option_insane_filesystems = 1;
		bsdtar->option_insane_filesystems_set = 1;
	} else if (strcmp(conf_opt, "keyfile") == 0) {
		if (bsdtar->have_keys)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		if (load_keys(bsdtar, conf_arg) == 0)
			bsdtar->have_keys = 1;
		else {
			if (fromconffile && bsdtar->option_dryrun)
				bsdtar->config_file_keyfile_failed = 1;
			else {
				bsdtar_errc(bsdtar, 1, errno,
				    "Cannot read key file: %s", conf_arg);
			}
		}
	} else if (strcmp(conf_opt, "lowmem") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_cachecrunch_set)
			goto optset;

		bsdtar->cachecrunch = 1;
		bsdtar->option_cachecrunch_set = 1;
	} else if (strcmp(conf_opt, "maxbw") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_maxbw_set)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		if (humansize_parse(conf_arg, &tarsnap_opt_maxbytesout))
			bsdtar_errc(bsdtar, 1, 0,
			    "Cannot parse bandwidth limit: %s", conf_arg);
		bsdtar->option_maxbw_set = 1;
	} else if (strcmp(conf_opt, "maxbw-rate") == 0) {
		dooption(bsdtar, "maxbw-rate-down", conf_arg, fromconffile);
		dooption(bsdtar, "maxbw-rate-up", conf_arg, fromconffile);
	} else if (strcmp(conf_opt, "maxbw-rate-down") == 0) {
		if (bsdtar->option_maxbw_rate_down_set)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		bsdtar->bwlimit_rate_down = strtod(conf_arg, &eptr);
		if ((*eptr != '\0') ||
		    (bsdtar->bwlimit_rate_down < 8000) ||
		    (bsdtar->bwlimit_rate_down > 1000000000.))
			bsdtar_errc(bsdtar, 1, 0,
			    "Invalid bandwidth rate limit: %s", conf_arg);
		bsdtar->option_maxbw_rate_down_set = 1;
	} else if (strcmp(conf_opt, "maxbw-rate-up") == 0) {
		if (bsdtar->option_maxbw_rate_up_set)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		bsdtar->bwlimit_rate_up = strtod(conf_arg, &eptr);
		if ((*eptr != '\0') ||
		    (bsdtar->bwlimit_rate_up < 8000) ||
		    (bsdtar->bwlimit_rate_up > 1000000000.))
			bsdtar_errc(bsdtar, 1, 0,
			    "Invalid bandwidth rate limit: %s", conf_arg);
		bsdtar->option_maxbw_rate_up_set = 1;
	} else if (strcmp(conf_opt, "nodump") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_nodump_set)
			goto optset;

		bsdtar->option_honor_nodump = 1;
		bsdtar->option_nodump_set = 1;
	} else if (strcmp(conf_opt, "normalmem") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_cachecrunch_set)
			goto optset;

		bsdtar->option_cachecrunch_set = 1;
	} else if (strcmp(conf_opt, "no-aggressive-networking") == 0) {
		if (bsdtar->option_aggressive_networking_set)
			goto optset;

		bsdtar->option_aggressive_networking_set = 1;
	} else if (strcmp(conf_opt, "no-config-exclude") == 0) {
		if (bsdtar->option_no_config_exclude)
			goto optset;

		bsdtar->option_no_config_exclude = 1;
	} else if (strcmp(conf_opt, "no-config-include") == 0) {
		if (bsdtar->option_no_config_include)
			goto optset;

		bsdtar->option_no_config_include = 1;
	} else if (strcmp(conf_opt, "no-disk-pause") == 0) {
		if (bsdtar->option_disk_pause_set)
			goto optset;

		bsdtar->option_disk_pause_set = 1;
	} else if (strcmp(conf_opt, "no-humanize-numbers") == 0) {
		if (bsdtar->option_humanize_numbers_set)
			goto optset;

		bsdtar->option_humanize_numbers_set = 1;
	} else if (strcmp(conf_opt, "no-insane-filesystems") == 0) {
		if (bsdtar->option_insane_filesystems_set)
			goto optset;

		bsdtar->option_insane_filesystems_set = 1;
	} else if (strcmp(conf_opt, "no-maxbw") == 0) {
		if (bsdtar->option_maxbw_set)
			goto optset;

		bsdtar->option_maxbw_set = 1;
	} else if (strcmp(conf_opt, "no-maxbw-rate-down") == 0) {
		if (bsdtar->option_maxbw_rate_down_set)
			goto optset;

		bsdtar->option_maxbw_rate_down_set = 1;
	} else if (strcmp(conf_opt, "no-maxbw-rate-up") == 0) {
		if (bsdtar->option_maxbw_rate_up_set)
			goto optset;

		bsdtar->option_maxbw_rate_up_set = 1;
	} else if (strcmp(conf_opt, "no-nodump") == 0) {
		if (bsdtar->option_nodump_set)
			goto optset;

		bsdtar->option_nodump_set = 1;
	} else if (strcmp(conf_opt, "no-print-stats") == 0) {
		if (bsdtar->option_print_stats_set)
			goto optset;

		bsdtar->option_print_stats_set = 1;
	} else if (strcmp(conf_opt, "no-quiet") == 0) {
		if (bsdtar->option_quiet_set)
			goto optset;

		bsdtar->option_quiet_set = 1;
	} else if (strcmp(conf_opt, "no-retry-forever") == 0) {
		if (bsdtar->option_retry_forever_set)
			goto optset;

		bsdtar->option_retry_forever_set = 1;
	} else if (strcmp(conf_opt, "no-snaptime") == 0) {
		if (bsdtar->option_snaptime_set)
			goto optset;

		bsdtar->option_snaptime_set = 1;
	} else if (strcmp(conf_opt, "no-store-atime") == 0) {
		if (bsdtar->option_store_atime_set)
			goto optset;

		bsdtar->option_store_atime_set = 1;
	} else if (strcmp(conf_opt, "no-totals") == 0) {
		if (bsdtar->option_totals_set)
			goto optset;

		bsdtar->option_totals_set = 1;
	} else if (strcmp(conf_opt, "print-stats") == 0) {
		if ((bsdtar->mode != 'c') && (bsdtar->mode != 'd'))
			goto badmode;
		if (bsdtar->option_print_stats_set)
			goto optset;

		bsdtar->option_print_stats = 1;
		bsdtar->option_print_stats_set = 1;
	} else if (strcmp(conf_opt, "quiet") == 0) {
		if (bsdtar->option_quiet_set)
			goto optset;

		bsdtar->option_quiet = 1;
		bsdtar->option_quiet_set = 1;
	} else if (strcmp(conf_opt, "retry-forever") == 0) {
		if (bsdtar->option_retry_forever_set)
			goto optset;

		tarsnap_opt_retry_forever = 1;
		bsdtar->option_retry_forever_set = 1;
	} else if (strcmp(conf_opt, "snaptime") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_snaptime_set)
			goto optset;
		if (conf_arg == NULL)
			goto needarg;

		if (stat(conf_arg, &st) != 0)
			bsdtar_errc(bsdtar, 1, 0,
			    "Can't stat file %s", conf_arg);
		bsdtar->snaptime = st.st_ctime;
		bsdtar->option_snaptime_set = 1;
	} else if (strcmp(conf_opt, "store-atime") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_store_atime_set)
			goto optset;

		bsdtar->option_store_atime = 1;
		bsdtar->option_store_atime_set = 1;
	} else if (strcmp(conf_opt, "totals") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_totals_set)
			goto optset;

		bsdtar->option_totals = 1;
		bsdtar->option_totals_set = 1;
	} else if (strcmp(conf_opt, "verylowmem") == 0) {
		if (bsdtar->mode != 'c')
			goto badmode;
		if (bsdtar->option_cachecrunch_set)
			goto optset;

		bsdtar->cachecrunch = 2;
		bsdtar->option_cachecrunch_set = 1;
	} else {
		goto badopt;
	}
	return;

badmode:
	/* Option not relevant in this mode. */
	if (fromconffile == 0) {
		bsdtar_errc(bsdtar, 1, 0,
		    "Option --%s is not permitted in mode %s",
		    conf_opt, bsdtar->modestr);
	}
	return;

optset:
	/* Option specified multiple times. */
	if (fromconffile == 0) {
		usage(bsdtar);
	}
	return;

needarg:
	/* Option needs an argument. */
	bsdtar_errc(bsdtar, 1, 0,
	    "Argument required for configuration file option: %s", conf_opt);

badopt:
	/* No such option. */
	bsdtar_errc(bsdtar, 1, 0,
	    "Unrecognized configuration file option: \"%s\"", conf_opt);
}
Пример #18
0
int
main(int argc, char **argv)
{
	struct bsdtar		*bsdtar, bsdtar_storage;
	const struct option	*option;
	int			 opt, t;
	char			 option_o;
	char			 possible_help_request;
	char			 buff[16];

	/*
	 * Use a pointer for consistency, but stack-allocated storage
	 * for ease of cleanup.
	 */
	bsdtar = &bsdtar_storage;
	memset(bsdtar, 0, sizeof(*bsdtar));
	bsdtar->fd = -1; /* Mark as "unused" */
	option_o = 0;

	/* Need bsdtar->progname before calling bsdtar_warnc. */
	if (*argv == NULL)
		bsdtar->progname = "bsdtar";
	else {
		bsdtar->progname = strrchr(*argv, '/');
		if (bsdtar->progname != NULL)
			bsdtar->progname++;
		else
			bsdtar->progname = *argv;
	}

	if (setlocale(LC_ALL, "") == NULL)
		bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
#if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
	bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
#endif
	possible_help_request = 0;

	/* Look up uid of current user for future reference */
	bsdtar->user_uid = geteuid();

	/* Default: open tape drive. */
	bsdtar->filename = getenv("TAPE");
	if (bsdtar->filename == NULL)
		bsdtar->filename = _PATH_DEFTAPE;

	/* Default: preserve mod time on extract */
	bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;

	/* Default: Perform basic security checks. */
	bsdtar->extract_flags |= SECURITY;

	/* Defaults for root user: */
	if (bsdtar->user_uid == 0) {
		/* --same-owner */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
		/* -p */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
	}

	/* Rewrite traditional-style tar arguments, if used. */
	argv = rewrite_argv(bsdtar, &argc, argv, tar_opts);

	bsdtar->argv = argv;
	bsdtar->argc = argc;

	/* Process all remaining arguments now. */
	/*
	 * Comments following each option indicate where that option
	 * originated:  SUSv2, POSIX, GNU tar, star, etc.  If there's
	 * no such comment, then I don't know of anyone else who
	 * implements that option.
	 */
	while ((opt = bsdtar_getopt(bsdtar, tar_opts, &option)) != -1) {
		switch (opt) {
		case 'B': /* GNU tar */
			/* libarchive doesn't need this; just ignore it. */
			break;
		case 'b': /* SUSv2 */
			t = atoi(optarg);
			if (t <= 0 || t > 1024)
				bsdtar_errc(bsdtar, 1, 0,
				    "Argument to -b is out of range (1..1024)");
			bsdtar->bytes_per_block = 512 * t;
			break;
		case 'C': /* GNU tar */
			set_chdir(bsdtar, optarg);
			break;
		case 'c': /* SUSv2 */
			set_mode(bsdtar, opt);
			break;
		case OPTION_CHECK_LINKS: /* GNU tar */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_CHROOT: /* NetBSD */
			bsdtar->option_chroot = 1;
			break;
		case OPTION_EXCLUDE: /* GNU tar */
			if (exclude(bsdtar, optarg))
				bsdtar_errc(bsdtar, 1, 0,
				    "Couldn't exclude %s\n", optarg);
			break;
		case OPTION_FORMAT: /* GNU tar, others */
			bsdtar->create_format = optarg;
			break;
		case 'f': /* SUSv2 */
			bsdtar->filename = optarg;
			if (strcmp(bsdtar->filename, "-") == 0)
				bsdtar->filename = NULL;
			break;
		case 'H': /* BSD convention */
			bsdtar->symlink_mode = 'H';
			break;
		case 'h': /* Linux Standards Base, gtar; synonym for -L */
			bsdtar->symlink_mode = 'L';
			/* Hack: -h by itself is the "help" command. */
			possible_help_request = 1;
			break;
		case OPTION_HELP: /* GNU tar, others */
			long_help(bsdtar);
			exit(0);
			break;
		case 'I': /* GNU tar */
			/*
			 * TODO: Allow 'names' to come from an archive,
			 * not just a text file.  Design a good UI for
			 * allowing names and mode/owner to be read
			 * from an archive, with contents coming from
			 * disk.  This can be used to "refresh" an
			 * archive or to design archives with special
			 * permissions without having to create those
			 * permissions on disk.
			 */
			bsdtar->names_from_file = optarg;
			break;
		case OPTION_INCLUDE:
			/*
			 * Noone else has the @archive extension, so
			 * noone else needs this to filter entries
			 * when transforming archives.
			 */
			if (include(bsdtar, optarg))
				bsdtar_errc(bsdtar, 1, 0,
				    "Failed to add %s to inclusion list",
				    optarg);
			break;
		case 'j': /* GNU tar */
#if HAVE_LIBBZ2
			if (bsdtar->create_compression != '\0')
				bsdtar_errc(bsdtar, 1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
#else
			bsdtar_warnc(bsdtar, 0, "-j compression not supported by this version of bsdtar");
			usage(bsdtar);
#endif
			break;
		case 'k': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
			break;
		case OPTION_KEEP_NEWER_FILES: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
			break;
		case 'L': /* BSD convention */
			bsdtar->symlink_mode = 'L';
			break;
	        case 'l': /* SUSv2 and GNU tar beginning with 1.16 */
			/* GNU tar 1.13  used -l for --one-file-system */
			bsdtar->option_warn_links = 1;
			break;
		case 'm': /* SUSv2 */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
			break;
		case 'n': /* GNU tar */
			bsdtar->option_no_subdirs = 1;
			break;
	        /*
		 * Selecting files by time:
		 *    --newer-?time='date' Only files newer than 'date'
		 *    --newer-?time-than='file' Only files newer than time
		 *         on specified file (useful for incremental backups)
		 * TODO: Add corresponding "older" options to reverse these.
		 */
		case OPTION_NEWER_CTIME: /* GNU tar */
			bsdtar->newer_ctime_sec = get_date(optarg);
			break;
		case OPTION_NEWER_CTIME_THAN:
			{
				struct stat st;
				if (stat(optarg, &st) != 0)
					bsdtar_errc(bsdtar, 1, 0,
					    "Can't open file %s", optarg);
				bsdtar->newer_ctime_sec = st.st_ctime;
				bsdtar->newer_ctime_nsec =
				    ARCHIVE_STAT_CTIME_NANOS(&st);
			}
			break;
		case OPTION_NEWER_MTIME: /* GNU tar */
			bsdtar->newer_mtime_sec = get_date(optarg);
			break;
		case OPTION_NEWER_MTIME_THAN:
			{
				struct stat st;
				if (stat(optarg, &st) != 0)
					bsdtar_errc(bsdtar, 1, 0,
					    "Can't open file %s", optarg);
				bsdtar->newer_mtime_sec = st.st_mtime;
				bsdtar->newer_mtime_nsec =
				    ARCHIVE_STAT_MTIME_NANOS(&st);
			}
			break;
		case OPTION_NODUMP: /* star */
			bsdtar->option_honor_nodump = 1;
			break;
		case OPTION_NO_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_NULL: /* GNU tar */
			bsdtar->option_null++;
			break;
		case OPTION_NUMERIC_OWNER: /* GNU tar */
			bsdtar->option_numeric_owner++;
			break;
		case 'O': /* GNU tar */
			bsdtar->option_stdout = 1;
			break;
		case 'o': /* SUSv2 and GNU conflict here, but not fatally */
			option_o = 1; /* Record it and resolve it later. */
			break;
		case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
			bsdtar->option_dont_traverse_mounts = 1;
			break;
#if 0
		/*
		 * The common BSD -P option is not necessary, since
		 * our default is to archive symlinks, not follow
		 * them.  This is convenient, as -P conflicts with GNU
		 * tar anyway.
		 */
		case 'P': /* BSD convention */
			/* Default behavior, no option necessary. */
			break;
#endif
		case 'P': /* GNU tar */
			bsdtar->extract_flags &= ~SECURITY;
			bsdtar->option_absolute_paths = 1;
			break;
		case 'p': /* GNU tar, star */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_POSIX: /* GNU tar */
			bsdtar->create_format = "pax";
			break;
		case 'q': /* FreeBSD GNU tar --fast-read, NetBSD -q */
			bsdtar->option_fast_read = 1;
			break;
		case 'r': /* SUSv2 */
			set_mode(bsdtar, opt);
			break;
		case 'S': /* NetBSD pax-as-tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_SPARSE;
			break;
		case 's': /* NetBSD pax-as-tar */
#if HAVE_REGEX_H
			add_substitution(bsdtar, optarg);
#else
			bsdtar_warnc(bsdtar, 0, "-s is not supported by this version of bsdtar");
			usage(bsdtar);
#endif
			break;
		case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
			bsdtar->strip_components = atoi(optarg);
			break;
		case 'T': /* GNU tar */
			bsdtar->names_from_file = optarg;
			break;
		case 't': /* SUSv2 */
			set_mode(bsdtar, opt);
			bsdtar->verbose++;
			break;
		case OPTION_TOTALS: /* GNU tar */
			bsdtar->option_totals++;
			break;
		case 'U': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
			bsdtar->option_unlink_first = 1;
			break;
		case 'u': /* SUSv2 */
			set_mode(bsdtar, opt);
			break;
		case 'v': /* SUSv2 */
			bsdtar->verbose++;
			break;
		case OPTION_VERSION: /* GNU convention */
			version();
			break;
#if 0
		/*
		 * The -W longopt feature is handled inside of
		 * bsdtar_getop(), so -W is not available here.
		 */
		case 'W': /* Obscure, but useful GNU convention. */
			break;
#endif
		case 'w': /* SUSv2 */
			bsdtar->option_interactive = 1;
			break;
		case 'X': /* GNU tar */
			if (exclude_from_file(bsdtar, optarg))
				bsdtar_errc(bsdtar, 1, 0,
				    "failed to process exclusions from file %s",
				    optarg);
			break;
		case 'x': /* SUSv2 */
			set_mode(bsdtar, opt);
			break;
		case 'y': /* FreeBSD version of GNU tar */
#if HAVE_LIBBZ2
			if (bsdtar->create_compression != '\0')
				bsdtar_errc(bsdtar, 1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
#else
			bsdtar_warnc(bsdtar, 0, "-y compression not supported by this version of bsdtar");
			usage(bsdtar);
#endif
			break;
		case 'Z': /* GNU tar */
			if (bsdtar->create_compression != '\0')
				bsdtar_errc(bsdtar, 1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
			break;
		case 'z': /* GNU tar, star, many others */
#if HAVE_LIBZ
			if (bsdtar->create_compression != '\0')
				bsdtar_errc(bsdtar, 1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
#else
			bsdtar_warnc(bsdtar, 0, "-z compression not supported by this version of bsdtar");
			usage(bsdtar);
#endif
			break;
		case OPTION_USE_COMPRESS_PROGRAM:
			bsdtar->compress_program = optarg;
			break;
		default:
			usage(bsdtar);
		}
	}

	/*
	 * Sanity-check options.
	 */

	/* If no "real" mode was specified, treat -h as --help. */
	if ((bsdtar->mode == '\0') && possible_help_request) {
		long_help(bsdtar);
		exit(0);
	}

	/* Otherwise, a mode is required. */
	if (bsdtar->mode == '\0')
		bsdtar_errc(bsdtar, 1, 0,
		    "Must specify one of -c, -r, -t, -u, -x");

	/* Check boolean options only permitted in certain modes. */
	if (bsdtar->option_dont_traverse_mounts)
		only_mode(bsdtar, "--one-file-system", "cru");
	if (bsdtar->option_fast_read)
		only_mode(bsdtar, "--fast-read", "xt");
	if (bsdtar->option_honor_nodump)
		only_mode(bsdtar, "--nodump", "cru");
	if (option_o > 0) {
		switch (bsdtar->mode) {
		case 'c':
			/*
			 * In GNU tar, -o means "old format."  The
			 * "ustar" format is the closest thing
			 * supported by libarchive.
			 */
			bsdtar->create_format = "ustar";
			/* TODO: bsdtar->create_format = "v7"; */
			break;
		case 'x':
			/* POSIX-compatible behavior. */
			bsdtar->option_no_owner = 1;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		default:
			only_mode(bsdtar, "-o", "xc");
			break;
		}
	}
	if (bsdtar->option_no_subdirs)
		only_mode(bsdtar, "-n", "cru");
	if (bsdtar->option_stdout)
		only_mode(bsdtar, "-O", "xt");
	if (bsdtar->option_unlink_first)
		only_mode(bsdtar, "-U", "x");
	if (bsdtar->option_warn_links)
		only_mode(bsdtar, "--check-links", "cr");

	/* Check other parameters only permitted in certain modes. */
	if (bsdtar->create_compression != '\0') {
		strcpy(buff, "-?");
		buff[1] = bsdtar->create_compression;
		only_mode(bsdtar, buff, "cxt");
	}
	if (bsdtar->create_format != NULL)
		only_mode(bsdtar, "--format", "cru");
	if (bsdtar->symlink_mode != '\0') {
		strcpy(buff, "-?");
		buff[1] = bsdtar->symlink_mode;
		only_mode(bsdtar, buff, "cru");
	}
	if (bsdtar->strip_components != 0)
		only_mode(bsdtar, "--strip-components", "xt");

	bsdtar->argc -= optind;
	bsdtar->argv += optind;

	switch(bsdtar->mode) {
	case 'c':
		tar_mode_c(bsdtar);
		break;
	case 'r':
		tar_mode_r(bsdtar);
		break;
	case 't':
		tar_mode_t(bsdtar);
		break;
	case 'u':
		tar_mode_u(bsdtar);
		break;
	case 'x':
		tar_mode_x(bsdtar);
		break;
	}

	cleanup_exclusions(bsdtar);
#if HAVE_REGEX_H
	cleanup_substitution(bsdtar);
#endif

	if (bsdtar->return_value != 0)
		bsdtar_warnc(bsdtar, 0,
		    "Error exit delayed from previous errors.");
	return (bsdtar->return_value);
}
Пример #19
0
/* Process a line of configuration file. */
static int
configfile_helper(struct bsdtar *bsdtar, const char *line)
{
	char * conf_opt;
	char * conf_arg;
	size_t optlen;
	char * conf_arg_malloced;
	size_t len;

	/* Skip any leading whitespace. */
	while ((line[0] == ' ') || (line[0] == '\t'))
		line++;

	/* Ignore comments and blank lines. */
	if ((line[0] == '#') || (line[0] == '\0'))
		return (0);

	/* Duplicate line. */
	if ((conf_opt = strdup(line)) == NULL)
		bsdtar_errc(bsdtar, 1, errno, "Out of memory");

	/*
	 * Detect any trailing whitespace.  This could happen before string
	 * duplication, but to reduce the number of diffs to a later version,
	 * we'll do it here.
	 */
	len = strlen(conf_opt);
	if ((len > 0) &&
	    ((conf_opt[len - 1] == ' ') || (conf_opt[len - 1] == '\t'))) {
		bsdtar_warnc(bsdtar, 0,
		    "option contains trailing whitespace; future behaviour"
		    " may change for:\n    %s", line);
	}

	/* Split line into option and argument if possible. */
	optlen = strcspn(conf_opt, " \t");

	/* Is there an argument? */
	if (conf_opt[optlen]) {
		/* NUL-terminate the option name. */
		conf_opt[optlen] = '\0';

		/* Find the start of the argument. */
		conf_arg = conf_opt + optlen + 1;
		conf_arg += strspn(conf_arg, " \t");

		/*
		 * If the line is whitespace-terminated, there might not be
		 * an argument here after all.
		 */
		if (conf_arg[0] == '\0')
			conf_arg = NULL;
	} else {
		/* No argument. */
		conf_arg = NULL;
	}

	/*
	 * If we have an argument which starts with ~, and ${HOME} is
	 * defined, expand ~ to $HOME.
	 */
	if ((conf_arg != NULL) && (conf_arg[0] == '~') &&
	    (bsdtar->homedir != NULL)) {
		/* Construct expanded argument string. */
		if (asprintf(&conf_arg_malloced, "%s%s",
		    bsdtar->homedir, &conf_arg[1]) == -1)
			bsdtar_errc(bsdtar, 1, errno, "Out of memory");

		/* Use the expanded argument string hereafter. */
		conf_arg = conf_arg_malloced;
	} else {
		conf_arg_malloced = NULL;
	}

	/* Process the configuration option. */
	dooption(bsdtar, conf_opt, conf_arg, 1);

	/* Free expanded argument or NULL. */
	free(conf_arg_malloced);

	/* Free memory allocated by strdup. */
	free(conf_opt);

	return (0);
}
Пример #20
0
void
tar_mode_c(struct bsdtar *bsdtar)
{
	struct archive *a;
	int r;

	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
		bsdtar_errc(bsdtar, 1, 0, "no files or directories specified");

	a = archive_write_new();

	/* Support any format that the library supports. */
	if (bsdtar->create_format == NULL) {
		r = archive_write_set_format_pax_restricted(a);
		bsdtar->create_format = "pax restricted";
	} else {
		r = archive_write_set_format_by_name(a, bsdtar->create_format);
	}
	if (r != ARCHIVE_OK) {
		fprintf(stderr, "Can't use format %s: %s\n",
		    bsdtar->create_format,
		    archive_error_string(a));
		usage(bsdtar);
	}

	/*
	 * If user explicitly set the block size, then assume they
	 * want the last block padded as well.  Otherwise, use the
	 * default block size and accept archive_write_open_file()'s
	 * default padding decisions.
	 */
	if (bsdtar->bytes_per_block != 0) {
		archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
		archive_write_set_bytes_in_last_block(a,
		    bsdtar->bytes_per_block);
	} else
		archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);

	if (bsdtar->compress_program) {
		archive_write_set_compression_program(a, bsdtar->compress_program);
	} else {
		switch (bsdtar->create_compression) {
		case 0:
			archive_write_set_compression_none(a);
			break;
#ifdef HAVE_LIBBZ2
		case 'j': case 'y':
			archive_write_set_compression_bzip2(a);
			break;
#endif
#ifdef HAVE_LIBLZMA
		case 'J':
			archive_write_set_compression_xz(a);
			break;
		case OPTION_LZMA:
			archive_write_set_compression_lzma(a);
			break;
#endif
#ifdef HAVE_LIBZ
		case 'z':
			archive_write_set_compression_gzip(a);
			break;
#endif
		case 'Z':
			archive_write_set_compression_compress(a);
			break;
		default:
			bsdtar_errc(bsdtar, 1, 0,
			    "Unrecognized compression option -%c",
			    bsdtar->create_compression);
		}
	}

	if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
		bsdtar_errc(bsdtar, 1, 0, archive_error_string(a));
	if (ARCHIVE_OK != archive_write_open_file(a, bsdtar->filename))
		bsdtar_errc(bsdtar, 1, 0, archive_error_string(a));
	write_archive(a, bsdtar);
}
Пример #21
0
static int
bsdtar_getopt(struct bsdtar *bsdtar, const char *optstring,
    const struct option **poption)
{
	char *p, *q;
	const struct option *option;
	int opt;
	int option_index;
	size_t option_length;

	option_index = -1;
	*poption = NULL;

#ifdef HAVE_GETOPT_LONG
	opt = getopt_long(bsdtar->argc, bsdtar->argv, optstring,
	    tar_longopts, &option_index);
	if (option_index > -1)
		*poption = tar_longopts + option_index;
#else
	opt = getopt(bsdtar->argc, bsdtar->argv, optstring);
#endif

	/* Support long options through -W longopt=value */
	if (opt == 'W') {
		p = optarg;
		q = strchr(optarg, '=');
		if (q != NULL) {
			option_length = (size_t)(q - p);
			optarg = q + 1;
		} else {
			option_length = strlen(p);
			optarg = NULL;
		}
		option = tar_longopts;
		while (option->name != NULL &&
		    (strlen(option->name) < option_length ||
		    strncmp(p, option->name, option_length) != 0 )) {
			option++;
		}

		if (option->name != NULL) {
			*poption = option;
			opt = option->val;

			/* If the first match was exact, we're done. */
			if (strncmp(p, option->name, strlen(option->name)) == 0) {
				while (option->name != NULL)
					option++;
			} else {
				/* Check if there's another match. */
				option++;
				while (option->name != NULL &&
				    (strlen(option->name) < option_length ||
				    strncmp(p, option->name, option_length) != 0)) {
					option++;
				}
			}
			if (option->name != NULL)
				bsdtar_errc(bsdtar, 1, 0,
				    "Ambiguous option %s "
				    "(matches both %s and %s)",
				    p, (*poption)->name, option->name);

			if ((*poption)->has_arg == required_argument
			    && optarg == NULL)
				bsdtar_errc(bsdtar, 1, 0,
				    "Option \"%s\" requires argument", p);
		} else {
			opt = '?';
			/* TODO: Set up a fake 'struct option' for
			 * error reporting... ? ? ? */
		}
	}

	return (opt);
}
Пример #22
0
/*
 * Add the file or dir hierarchy named by 'path' to the archive
 */
static void
write_hierarchy(struct bsdtar *bsdtar, struct archive *a, const char *path)
{
	struct archive_entry *entry = NULL, *spare_entry = NULL;
	struct tree *tree;
	char symlink_mode = bsdtar->symlink_mode;
	dev_t first_dev = 0;
	int dev_recorded = 0;
	int tree_ret;
	dev_t last_dev = 0;
	char * fstype;

	tree = tree_open(path);

	if (!tree) {
		bsdtar_warnc(bsdtar, errno, "%s: Cannot open", path);
		bsdtar->return_value = 1;
		return;
	}

	while ((tree_ret = tree_next(tree))) {
		int r;
		const char *name = tree_current_path(tree);
		const struct stat *st = NULL; /* info to use for this entry */
		const struct stat *lst = NULL; /* lstat() information */
		int descend;

		if (truncate_archive(bsdtar))
			break;
		if (checkpoint_archive(bsdtar, 0))
			exit(1);
		disk_pause(bsdtar);
		if (network_select(0))
			exit(1);

		if (tree_ret == TREE_ERROR_FATAL)
			bsdtar_errc(bsdtar, 1, tree_errno(tree),
			    "%s: Unable to continue traversing directory tree",
			    name);
		if (tree_ret == TREE_ERROR_DIR) {
			bsdtar_warnc(bsdtar, errno,
			    "%s: Couldn't visit directory", name);
			bsdtar->return_value = 1;
		}
		if (tree_ret != TREE_REGULAR)
			continue;

		/*
		 * If this file/dir is excluded by a filename
		 * pattern, skip it.
		 */
		if (excluded(bsdtar, name))
			continue;

		/*
		 * Get lstat() info from the tree library.
		 */
		lst = tree_current_lstat(tree);
		if (lst == NULL) {
			/* Couldn't lstat(); must not exist. */
			bsdtar_warnc(bsdtar, errno, "%s: Cannot stat", name);
			/* Return error if files disappear during traverse. */
			bsdtar->return_value = 1;
			continue;
		}

		/*
		 * Distinguish 'L'/'P'/'H' symlink following.
		 */
		switch(symlink_mode) {
		case 'H':
			/* 'H': After the first item, rest like 'P'. */
			symlink_mode = 'P';
			/* 'H': First item (from command line) like 'L'. */
			/* FALLTHROUGH */
		case 'L':
			/* 'L': Do descend through a symlink to dir. */
			descend = tree_current_is_dir(tree);
			/* 'L': Follow symlinks to files. */
			archive_read_disk_set_symlink_logical(bsdtar->diskreader);
			/* 'L': Archive symlinks as targets, if we can. */
			st = tree_current_stat(tree);
			if (st != NULL)
				break;
			/* If stat fails, we have a broken symlink;
			 * in that case, don't follow the link. */
			/* FALLTHROUGH */
		default:
			/* 'P': Don't descend through a symlink to dir. */
			descend = tree_current_is_physical_dir(tree);
			/* 'P': Don't follow symlinks to files. */
			archive_read_disk_set_symlink_physical(bsdtar->diskreader);
			/* 'P': Archive symlinks as symlinks. */
			st = lst;
			break;
		}

		if (bsdtar->option_no_subdirs)
			descend = 0;

		/*
		 * If user has asked us not to cross mount points,
		 * then don't descend into a dir on a different
		 * device.
		 */
		if (!dev_recorded) {
			last_dev = first_dev = lst->st_dev;
			dev_recorded = 1;
		}
		if (bsdtar->option_dont_traverse_mounts) {
			if (lst->st_dev != first_dev)
				descend = 0;
		}

		/*
		 * If the user did not specify --insane-filesystems, do not
		 * cross into a new filesystem which is known to be synthetic.
		 * Note that we will archive synthetic filesystems if we are
		 * explicitly told to do so.
		 */
		if ((bsdtar->option_insane_filesystems == 0) &&
		    (descend != 0) &&
		    (lst->st_dev != last_dev)) {
			fstype = getfstype(tree_current_access_path(tree));
			if (fstype == NULL)
				bsdtar_errc(bsdtar, 1, errno,
				    "%s: Error getting filesystem type",
				    name);
			if (getfstype_issynthetic(fstype)) {
				if (!bsdtar->option_quiet)
					bsdtar_warnc(bsdtar, 0,
					    "Not descending into filesystem of type %s: %s",
					    fstype, name);
				descend = 0;
			} else {
				/* This device is ok to archive. */
				last_dev = lst->st_dev;
			}
			free(fstype);
		}

		/*
		 * In -u mode, check that the file is newer than what's
		 * already in the archive; in all modes, obey --newerXXX flags.
		 */
		if (!new_enough(bsdtar, name, st)) {
			if (!descend)
				continue;
			if (bsdtar->option_interactive &&
			    !yes("add '%s'", name))
				continue;
			tree_descend(tree);
			continue;
		}

		archive_entry_free(entry);
		entry = archive_entry_new();

		archive_entry_set_pathname(entry, name);
		archive_entry_copy_sourcepath(entry,
		    tree_current_access_path(tree));

		/* Populate the archive_entry with metadata from the disk. */
		/* XXX TODO: Arrange to open a regular file before
		 * calling this so we can pass in an fd and shorten
		 * the race to query metadata.  The linkify dance
		 * makes this more complex than it might sound. */
		r = archive_read_disk_entry_from_file(bsdtar->diskreader,
		    entry, -1, st);
		if (r != ARCHIVE_OK)
			bsdtar_warnc(bsdtar, archive_errno(bsdtar->diskreader),
			    "%s", archive_error_string(bsdtar->diskreader));
		if (r < ARCHIVE_WARN)
			continue;

		/* XXX TODO: Just use flag data from entry; avoid the
		 * duplicate check here. */

		/*
		 * If this file/dir is flagged "nodump" and we're
		 * honoring such flags, skip this file/dir.
		 */
#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
		/* BSD systems store flags in struct stat */
		if (bsdtar->option_honor_nodump &&
		    (lst->st_flags & UF_NODUMP))
			continue;
#endif

#if defined(EXT2_NODUMP_FL)
		/* Linux uses ioctl to read flags. */
		if (bsdtar->option_honor_nodump) {
			unsigned long fflags, dummy;
			archive_entry_fflags(entry, &fflags, &dummy);
			if (fflags & EXT2_NODUMP_FL)
				continue;
		}
#endif

		/*
		 * Don't back up the cache directory or any files inside it.
		 */
		if ((lst->st_ino == bsdtar->cachedir_ino) &&
		    (lst->st_dev == bsdtar->cachedir_dev)) {
			if (!bsdtar->option_quiet)
				bsdtar_warnc(bsdtar, 0,
				    "Not adding cache directory to archive: %s",
				name);
			continue;
		}

		/*
		 * If the user vetoes this file/directory, skip it.
		 * We want this to be fairly late; if some other
		 * check would veto this file, we shouldn't bother
		 * the user with it.
		 */
		if (bsdtar->option_interactive &&
		    !yes("add '%s'", name))
			continue;

		/* Note: if user vetoes, we won't descend. */
		if (descend)
			tree_descend(tree);

		/*
		 * Rewrite the pathname to be archived.  If rewrite
		 * fails, skip the entry.
		 */
		if (edit_pathname(bsdtar, entry))
			continue;

		/*
		 * If this is a socket, skip the entry: POSIX requires that
		 * pax(1) emit a "diagnostic message" (i.e., warning) that
		 * sockets cannot be archived, but this can make backups of
		 * running systems very noisy.
		 */
		if (S_ISSOCK(st->st_mode))
			continue;

		/* Display entry as we process it.
		 * This format is required by SUSv2. */
		if (bsdtar->verbose)
			safe_fprintf(stderr, "a %s",
			    archive_entry_pathname(entry));

		/*
		 * If the user hasn't specifically asked to have the access
		 * time stored, zero it.  At the moment this usually only
		 * matters for files which have flags set, since the "posix
		 * restricted" format doesn't store access times for most
		 * other files.
		 */
		if (bsdtar->option_store_atime == 0)
			archive_entry_set_atime(entry, 0, 0);

		/* Non-regular files get archived with zero size. */
		if (!S_ISREG(st->st_mode))
			archive_entry_set_size(entry, 0);

		/* Record what we're doing, for SIGINFO / SIGUSR1. */
		siginfo_setinfo(bsdtar, "adding",
		    archive_entry_pathname(entry), archive_entry_size(entry));
		archive_entry_linkify(bsdtar->resolver, &entry, &spare_entry);

		/* Handle SIGINFO / SIGUSR1 request if one was made. */
		siginfo_printinfo(bsdtar, 0);

		while (entry != NULL) {
			write_entry_backend(bsdtar, a, entry, st,
			    tree_current_realpath(tree));
			archive_entry_free(entry);
			entry = spare_entry;
			spare_entry = NULL;
		}

		if (bsdtar->verbose)
			fprintf(stderr, "\n");
	}
	archive_entry_free(entry);
	if (tree_close(tree))
		bsdtar_errc(bsdtar, 1, 0, "Error traversing directory tree");
}
Пример #23
0
/*
 * Same as 'c', except we only support tar or empty formats in
 * uncompressed files on disk.
 */
void
tar_mode_r(struct bsdtar *bsdtar)
{
	off_t	end_offset;
	int	format;
	struct archive *a;
	struct archive_entry *entry;
	int	r;

	/* Sanity-test some arguments and the file. */
	test_for_append(bsdtar);

	format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;

	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT, 0666);
	if (bsdtar->fd < 0)
		bsdtar_errc(bsdtar, 1, errno,
		    "Cannot open %s", bsdtar->filename);

	a = archive_read_new();
	archive_read_support_compression_all(a);
	archive_read_support_format_tar(a);
	archive_read_support_format_gnutar(a);
	r = archive_read_open_fd(a, bsdtar->fd, 10240);
	if (r != ARCHIVE_OK)
		bsdtar_errc(bsdtar, 1, archive_errno(a),
		    "Can't read archive %s: %s", bsdtar->filename,
		    archive_error_string(a));
	while (0 == archive_read_next_header(a, &entry)) {
		if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
			archive_read_finish(a);
			close(bsdtar->fd);
			bsdtar_errc(bsdtar, 1, 0,
			    "Cannot append to compressed archive.");
		}
		/* Keep going until we hit end-of-archive */
		format = archive_format(a);
	}

	end_offset = archive_read_header_position(a);
	archive_read_finish(a);

	/* Re-open archive for writing */
	a = archive_write_new();
	archive_write_set_compression_none(a);
	/*
	 * Set the format to be used for writing.  To allow people to
	 * extend empty files, we need to allow them to specify the format,
	 * which opens the possibility that they will specify a format that
	 * doesn't match the existing format.  Hence, the following bit
	 * of arcane ugliness.
	 */

	if (bsdtar->create_format != NULL) {
		/* If the user requested a format, use that, but ... */
		archive_write_set_format_by_name(a,
		    bsdtar->create_format);
		/* ... complain if it's not compatible. */
		format &= ARCHIVE_FORMAT_BASE_MASK;
		if (format != (int)(archive_format(a) & ARCHIVE_FORMAT_BASE_MASK)
		    && format != ARCHIVE_FORMAT_EMPTY) {
			bsdtar_errc(bsdtar, 1, 0,
			    "Format %s is incompatible with the archive %s.",
			    bsdtar->create_format, bsdtar->filename);
		}
	} else {
		/*
		 * Just preserve the current format, with a little care
		 * for formats that libarchive can't write.
		 */
		if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
			/* TODO: When gtar supports pax, use pax restricted. */
			format = ARCHIVE_FORMAT_TAR_USTAR;
		if (format == ARCHIVE_FORMAT_EMPTY)
			format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
		archive_write_set_format(a, format);
	}
	lseek(bsdtar->fd, end_offset, SEEK_SET); /* XXX check return val XXX */
	if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
		bsdtar_errc(bsdtar, 1, 0, archive_error_string(a));
	if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
		bsdtar_errc(bsdtar, 1, 0, archive_error_string(a));

	write_archive(a, bsdtar); /* XXX check return val XXX */

	close(bsdtar->fd);
	bsdtar->fd = -1;
}
Пример #24
0
void
tar_mode_u(struct bsdtar *bsdtar)
{
	off_t			 end_offset;
	struct archive		*a;
	struct archive_entry	*entry;
	int			 format;
	struct archive_dir_entry	*p;
	struct archive_dir	 archive_dir;

	bsdtar->archive_dir = &archive_dir;
	memset(&archive_dir, 0, sizeof(archive_dir));

	format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;

	/* Sanity-test some arguments and the file. */
	test_for_append(bsdtar);

	bsdtar->fd = open(bsdtar->filename, O_RDWR);
	if (bsdtar->fd < 0)
		bsdtar_errc(bsdtar, 1, errno,
		    "Cannot open %s", bsdtar->filename);

	a = archive_read_new();
	archive_read_support_compression_all(a);
	archive_read_support_format_tar(a);
	archive_read_support_format_gnutar(a);
	if (archive_read_open_fd(a, bsdtar->fd,
	    bsdtar->bytes_per_block != 0 ? bsdtar->bytes_per_block :
		DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
		bsdtar_errc(bsdtar, 1, 0,
		    "Can't open %s: %s", bsdtar->filename,
		    archive_error_string(a));
	}

	/* Build a list of all entries and their recorded mod times. */
	while (0 == archive_read_next_header(a, &entry)) {
		if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
			archive_read_finish(a);
			close(bsdtar->fd);
			bsdtar_errc(bsdtar, 1, 0,
			    "Cannot append to compressed archive.");
		}
		add_dir_list(bsdtar, archive_entry_pathname(entry),
		    archive_entry_mtime(entry),
		    archive_entry_mtime_nsec(entry));
		/* Record the last format determination we see */
		format = archive_format(a);
		/* Keep going until we hit end-of-archive */
	}

	end_offset = archive_read_header_position(a);
	archive_read_finish(a);

	/* Re-open archive for writing. */
	a = archive_write_new();
	archive_write_set_compression_none(a);
	/*
	 * Set format to same one auto-detected above, except that
	 * we don't write GNU tar format, so use ustar instead.
	 */
	if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
		format = ARCHIVE_FORMAT_TAR_USTAR;
	archive_write_set_format(a, format);
	if (bsdtar->bytes_per_block != 0) {
		archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
		archive_write_set_bytes_in_last_block(a,
		    bsdtar->bytes_per_block);
	} else
		archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);
	lseek(bsdtar->fd, end_offset, SEEK_SET);
	ftruncate(bsdtar->fd, end_offset);
	if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
		bsdtar_errc(bsdtar, 1, 0, archive_error_string(a));
	if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
		bsdtar_errc(bsdtar, 1, 0, archive_error_string(a));

	write_archive(a, bsdtar);

	close(bsdtar->fd);
	bsdtar->fd = -1;

	while (bsdtar->archive_dir->head != NULL) {
		p = bsdtar->archive_dir->head->next;
		free(bsdtar->archive_dir->head->name);
		free(bsdtar->archive_dir->head);
		bsdtar->archive_dir->head = p;
	}
	bsdtar->archive_dir->tail = NULL;
}
Пример #25
0
/*
 * Write user-specified files/dirs to opened archive.
 */
static void
write_archive(struct archive *a, struct bsdtar *bsdtar)
{
	const char *arg;
	struct archive_entry *entry, *sparse_entry;

	/* We want to catch SIGINFO and SIGUSR1. */
	siginfo_init(bsdtar);

	/* Allocate a buffer for file data. */
	if ((bsdtar->buff = malloc(FILEDATABUFLEN)) == NULL)
		bsdtar_errc(bsdtar, 1, 0, "cannot allocate memory");

	if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
		bsdtar_errc(bsdtar, 1, 0, "cannot create link resolver");
	archive_entry_linkresolver_set_strategy(bsdtar->resolver,
	    archive_format(a));
	if ((bsdtar->diskreader = archive_read_disk_new()) == NULL)
		bsdtar_errc(bsdtar, 1, 0, "Cannot create read_disk object");
	archive_read_disk_set_standard_lookup(bsdtar->diskreader);

	if (bsdtar->names_from_file != NULL)
		archive_names_from_file(bsdtar, a);

	while (*bsdtar->argv) {
		arg = *bsdtar->argv;
		if (arg[0] == '-' && arg[1] == 'C') {
			arg += 2;
			if (*arg == '\0') {
				bsdtar->argv++;
				arg = *bsdtar->argv;
				if (arg == NULL) {
					bsdtar_warnc(bsdtar, 1, 0,
					    "Missing argument for -C");
					bsdtar->return_value = 1;
					goto cleanup;
				}
			}
			set_chdir(bsdtar, arg);
		} else {
			if (*arg != '/' && (arg[0] != '@' || arg[1] != '/'))
				do_chdir(bsdtar); /* Handle a deferred -C */
			if (*arg == '@') {
				if (append_archive_filename(bsdtar, a,
				    arg + 1) != 0)
					break;
			} else
#if defined(_WIN32) && !defined(__CYGWIN__)
				write_hierarchy_win(bsdtar, a, arg,
				    write_hierarchy);
#else
				write_hierarchy(bsdtar, a, arg);
#endif
		}
		bsdtar->argv++;
	}

	entry = NULL;
	archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
	while (entry != NULL) {
		write_entry_backend(bsdtar, a, entry);
		archive_entry_free(entry);
		entry = NULL;
		archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
	}

	if (archive_write_close(a)) {
		bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
		bsdtar->return_value = 1;
	}

cleanup:
	/* Free file data buffer. */
	free(bsdtar->buff);
	archive_entry_linkresolver_free(bsdtar->resolver);
	bsdtar->resolver = NULL;
	archive_read_finish(bsdtar->diskreader);
	bsdtar->diskreader = NULL;

	if (bsdtar->option_totals) {
		fprintf(stderr, "Total bytes written: " BSDTAR_FILESIZE_PRINTF "\n",
		    (BSDTAR_FILESIZE_TYPE)archive_position_compressed(a));
	}

	archive_write_finish(a);

	/* Restore old SIGINFO + SIGUSR1 handlers. */
	siginfo_done(bsdtar);
}
Пример #26
0
/*
 * Add the file or dir hierarchy named by 'path' to the archive
 */
static void
write_hierarchy(struct bsdtar *bsdtar, struct archive *a, const char *path)
{
	struct archive_entry *entry = NULL, *spare_entry = NULL;
	struct tree *tree;
	char symlink_mode = bsdtar->symlink_mode;
	dev_t first_dev = 0;
	int dev_recorded = 0;
	int tree_ret;

	tree = tree_open(path);

	if (!tree) {
		bsdtar_warnc(bsdtar, errno, "%s: Cannot open", path);
		bsdtar->return_value = 1;
		return;
	}

	while ((tree_ret = tree_next(tree))) {
		int r;
		const char *name = tree_current_path(tree);
		const struct stat *st = NULL; /* info to use for this entry */
		const struct stat *lst = NULL; /* lstat() information */
		int descend;

		if (tree_ret == TREE_ERROR_FATAL)
			bsdtar_errc(bsdtar, 1, tree_errno(tree),
			    "%s: Unable to continue traversing directory tree",
			    name);
		if (tree_ret == TREE_ERROR_DIR) {
			bsdtar_warnc(bsdtar, errno,
			    "%s: Couldn't visit directory", name);
			bsdtar->return_value = 1;
		}
		if (tree_ret != TREE_REGULAR)
			continue;

		/*
		 * If this file/dir is excluded by a filename
		 * pattern, skip it.
		 */
		if (excluded(bsdtar, name))
			continue;

		/*
		 * Get lstat() info from the tree library.
		 */
		lst = tree_current_lstat(tree);
		if (lst == NULL) {
			/* Couldn't lstat(); must not exist. */
			bsdtar_warnc(bsdtar, errno, "%s: Cannot stat", name);
			/* Return error if files disappear during traverse. */
			bsdtar->return_value = 1;
			continue;
		}

		/*
		 * Distinguish 'L'/'P'/'H' symlink following.
		 */
		switch(symlink_mode) {
		case 'H':
			/* 'H': After the first item, rest like 'P'. */
			symlink_mode = 'P';
			/* 'H': First item (from command line) like 'L'. */
			/* FALLTHROUGH */
		case 'L':
			/* 'L': Do descend through a symlink to dir. */
			descend = tree_current_is_dir(tree);
			/* 'L': Follow symlinks to files. */
			archive_read_disk_set_symlink_logical(bsdtar->diskreader);
			/* 'L': Archive symlinks as targets, if we can. */
			st = tree_current_stat(tree);
			if (st != NULL)
				break;
			/* If stat fails, we have a broken symlink;
			 * in that case, don't follow the link. */
			/* FALLTHROUGH */
		default:
			/* 'P': Don't descend through a symlink to dir. */
			descend = tree_current_is_physical_dir(tree);
			/* 'P': Don't follow symlinks to files. */
			archive_read_disk_set_symlink_physical(bsdtar->diskreader);
			/* 'P': Archive symlinks as symlinks. */
			st = lst;
			break;
		}

		/*
		 * If user has asked us not to cross mount points,
		 * then don't descend into into a dir on a different
		 * device.
		 */
		if (!dev_recorded) {
			first_dev = lst->st_dev;
			dev_recorded = 1;
		}
		if (bsdtar->option_dont_traverse_mounts) {
			if (lst->st_dev != first_dev)
				descend = 0;
		}

		/*
		 * In -u mode, check that the file is newer than what's
		 * already in the archive; in all modes, obey --newerXXX flags.
		 */
		if (!new_enough(bsdtar, name, st))
			continue;

		archive_entry_free(entry);
		entry = archive_entry_new();

		archive_entry_set_pathname(entry, name);
		archive_entry_copy_sourcepath(entry,
		    tree_current_access_path(tree));

		/* Populate the archive_entry with metadata from the disk. */
		/* XXX TODO: Arrange to open a regular file before
		 * calling this so we can pass in an fd and shorten
		 * the race to query metadata.  The linkify dance
		 * makes this more complex than it might sound. */
		r = archive_read_disk_entry_from_file(bsdtar->diskreader,
		    entry, -1, st);
		if (r != ARCHIVE_OK)
			bsdtar_warnc(bsdtar, archive_errno(bsdtar->diskreader),
			    archive_error_string(bsdtar->diskreader));
		if (r < ARCHIVE_WARN)
			continue;

		/* XXX TODO: Just use flag data from entry; avoid the
		 * duplicate check here. */

		/*
		 * If this file/dir is flagged "nodump" and we're
		 * honoring such flags, skip this file/dir.
		 */
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
		/* BSD systems store flags in struct stat */
		if (bsdtar->option_honor_nodump &&
		    (lst->st_flags & UF_NODUMP))
			continue;
#endif

#if defined(EXT2_IOC_GETFLAGS) && defined(EXT2_NODUMP_FL)
		/* Linux uses ioctl to read flags. */
		if (bsdtar->option_honor_nodump) {
			int fd = open(name, O_RDONLY | O_NONBLOCK);
			if (fd >= 0) {
				unsigned long fflags;
				int r = ioctl(fd, EXT2_IOC_GETFLAGS, &fflags);
				close(fd);
				if (r >= 0 && (fflags & EXT2_NODUMP_FL))
					continue;
			}
		}
#endif

		/*
		 * If the user vetoes this file/directory, skip it.
		 * We want this to be fairly late; if some other
		 * check would veto this file, we shouldn't bother
		 * the user with it.
		 */
		if (bsdtar->option_interactive &&
		    !yes("add '%s'", name))
			continue;

		/* Note: if user vetoes, we won't descend. */
		if (descend && !bsdtar->option_no_subdirs)
			tree_descend(tree);

		/*
		 * Rewrite the pathname to be archived.  If rewrite
		 * fails, skip the entry.
		 */
		if (edit_pathname(bsdtar, entry))
			continue;

		/* Display entry as we process it.
		 * This format is required by SUSv2. */
		if (bsdtar->verbose)
			safe_fprintf(stderr, "a %s",
			    archive_entry_pathname(entry));

		/* Non-regular files get archived with zero size. */
		if (!S_ISREG(st->st_mode))
			archive_entry_set_size(entry, 0);

		/* Record what we're doing, for SIGINFO / SIGUSR1. */
		siginfo_setinfo(bsdtar, "adding",
		    archive_entry_pathname(entry), archive_entry_size(entry));
		archive_entry_linkify(bsdtar->resolver, &entry, &spare_entry);

		/* Handle SIGINFO / SIGUSR1 request if one was made. */
		siginfo_printinfo(bsdtar, 0);

		while (entry != NULL) {
			write_entry_backend(bsdtar, a, entry);
			archive_entry_free(entry);
			entry = spare_entry;
			spare_entry = NULL;
		}

		if (bsdtar->verbose)
			fprintf(stderr, "\n");
	}
	archive_entry_free(entry);
	tree_close(tree);
}
Пример #27
0
/*
 * Handle 'x' and 't' modes.
 */
static void
read_archive(struct bsdtar *bsdtar, char mode)
{
	FILE			 *out;
	struct archive		 *a;
	struct archive_entry	 *entry;
	const struct stat	 *st;
	int			  r;

	while (*bsdtar->argv) {
		include(bsdtar, *bsdtar->argv);
		bsdtar->argv++;
	}

	if (bsdtar->names_from_file != NULL)
		include_from_file(bsdtar, bsdtar->names_from_file);

	a = archive_read_new();
	if (bsdtar->compress_program != NULL)
		archive_read_support_compression_program(a, bsdtar->compress_program);
	else
		archive_read_support_compression_all(a);
	archive_read_support_format_all(a);
	if (archive_read_open_file(a, bsdtar->filename,
	    bsdtar->bytes_per_block != 0 ? bsdtar->bytes_per_block :
	    DEFAULT_BYTES_PER_BLOCK))
		bsdtar_errc(bsdtar, 1, 0, "Error opening archive: %s",
		    archive_error_string(a));

	do_chdir(bsdtar);
	for (;;) {
		/* Support --fast-read option */
		if (bsdtar->option_fast_read &&
		    unmatched_inclusions(bsdtar) == 0)
			break;

		r = archive_read_next_header(a, &entry);
		if (r == ARCHIVE_EOF)
			break;
		if (r < ARCHIVE_OK)
			bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
		if (r <= ARCHIVE_WARN)
			bsdtar->return_value = 1;
		if (r == ARCHIVE_RETRY) {
			/* Retryable error: try again */
			bsdtar_warnc(bsdtar, 0, "Retrying...");
			continue;
		}
		if (r == ARCHIVE_FATAL)
			break;

		/*
		 * Exclude entries that are too old.
		 */
		st = archive_entry_stat(entry);
		if (bsdtar->newer_ctime_sec > 0) {
			if (st->st_ctime < bsdtar->newer_ctime_sec)
				continue; /* Too old, skip it. */
			if (st->st_ctime == bsdtar->newer_ctime_sec
			    && ARCHIVE_STAT_CTIME_NANOS(st)
			    <= bsdtar->newer_ctime_nsec)
				continue; /* Too old, skip it. */
		}
		if (bsdtar->newer_mtime_sec > 0) {
			if (st->st_mtime < bsdtar->newer_mtime_sec)
				continue; /* Too old, skip it. */
			if (st->st_mtime == bsdtar->newer_mtime_sec
			    && ARCHIVE_STAT_MTIME_NANOS(st)
			    <= bsdtar->newer_mtime_nsec)
				continue; /* Too old, skip it. */
		}

		/*
		 * Note that pattern exclusions are checked before
		 * pathname rewrites are handled.  This gives more
		 * control over exclusions, since rewrites always lose
		 * information.  (For example, consider a rewrite
		 * s/foo[0-9]/foo/.  If we check exclusions after the
		 * rewrite, there would be no way to exclude foo1/bar
		 * while allowing foo2/bar.)
		 */
		if (excluded(bsdtar, archive_entry_pathname(entry)))
			continue; /* Excluded by a pattern test. */

		/*
		 * Modify the pathname as requested by the user.  We
		 * do this for -t as well to give users a way to
		 * preview the effects of their rewrites.  We also do
		 * this before extraction security checks (including
		 * leading '/' removal).  Note that some rewrite
		 * failures prevent extraction.
		 */
		if (edit_pathname(bsdtar, entry))
			continue; /* Excluded by a rewrite failure. */

		if (mode == 't') {
			/* Perversely, gtar uses -O to mean "send to stderr"
			 * when used with -t. */
			out = bsdtar->option_stdout ? stderr : stdout;

			if (bsdtar->verbose < 2)
				safe_fprintf(out, "%s",
				    archive_entry_pathname(entry));
			else
				list_item_verbose(bsdtar, out, entry);
			fflush(out);
			r = archive_read_data_skip(a);
			if (r == ARCHIVE_WARN) {
				fprintf(out, "\n");
				bsdtar_warnc(bsdtar, 0, "%s",
				    archive_error_string(a));
			}
			if (r == ARCHIVE_RETRY) {
				fprintf(out, "\n");
				bsdtar_warnc(bsdtar, 0, "%s",
				    archive_error_string(a));
			}
			if (r == ARCHIVE_FATAL) {
				fprintf(out, "\n");
				bsdtar_warnc(bsdtar, 0, "%s",
				    archive_error_string(a));
				bsdtar->return_value = 1;
				break;
			}
			fprintf(out, "\n");
		} else {
			if (bsdtar->option_interactive &&
			    !yes("extract '%s'", archive_entry_pathname(entry)))
				continue;

			/*
			 * Format here is from SUSv2, including the
			 * deferred '\n'.
			 */
			if (bsdtar->verbose) {
				safe_fprintf(stderr, "x %s",
				    archive_entry_pathname(entry));
				fflush(stderr);
			}
			if (bsdtar->option_stdout)
				r = archive_read_data_into_fd(a, 1);
			else
				r = archive_read_extract(a, entry,
				    bsdtar->extract_flags);
			if (r != ARCHIVE_OK) {
				if (!bsdtar->verbose)
					safe_fprintf(stderr, "%s",
					    archive_entry_pathname(entry));
				safe_fprintf(stderr, ": %s",
				    archive_error_string(a));
				if (!bsdtar->verbose)
					fprintf(stderr, "\n");
				bsdtar->return_value = 1;
			}
			if (bsdtar->verbose)
				fprintf(stderr, "\n");
			if (r == ARCHIVE_FATAL)
				break;
		}
	}

	if (bsdtar->verbose > 2)
		fprintf(stdout, "Archive Format: %s,  Compression: %s\n",
		    archive_format_name(a), archive_compression_name(a));

	archive_read_finish(a);
}
Пример #28
0
/*
 * Write user-specified files/dirs to opened archive.
 */
static void
write_archive(struct archive *a, struct bsdtar *bsdtar)
{
	struct sigaction sa;
	const char *arg;
	struct archive_entry *entry, *sparse_entry;

	/* We want to catch SIGINFO and SIGUSR1. */
	siginfo_init(bsdtar);

	/* We also want to catch SIGQUIT and ^Q. */
	if (sigquit_init())
		exit(1);

	/* And SIGUSR2, too. */
	sa.sa_handler = sigusr2_handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if (sigaction(SIGUSR2, &sa, NULL))
		bsdtar_errc(bsdtar, 1, 0, "cannot install signal handler");

	/* Allocate a buffer for file data. */
	if ((bsdtar->buff = malloc(FILEDATABUFLEN)) == NULL)
		bsdtar_errc(bsdtar, 1, 0, "cannot allocate memory");

	if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
		bsdtar_errc(bsdtar, 1, 0, "cannot create link resolver");
	archive_entry_linkresolver_set_strategy(bsdtar->resolver,
	    archive_format(a));
	if ((bsdtar->diskreader = archive_read_disk_new()) == NULL)
		bsdtar_errc(bsdtar, 1, 0, "Cannot create read_disk object");
	archive_read_disk_set_standard_lookup(bsdtar->diskreader);

	if (bsdtar->names_from_file != NULL)
		archive_names_from_file(bsdtar, a);

	while (*bsdtar->argv) {
		if (truncate_archive(bsdtar))
			break;
		if (checkpoint_archive(bsdtar, 0))
			exit(1);

		arg = *bsdtar->argv;
		if (arg[0] == '-' && arg[1] == 'C') {
			arg += 2;
			if (*arg == '\0') {
				bsdtar->argv++;
				arg = *bsdtar->argv;
				if (arg == NULL) {
					bsdtar_warnc(bsdtar, 0,
					    "Missing argument for -C");
					bsdtar->return_value = 1;
					goto cleanup;
				}
				if (*arg == '\0') {
					bsdtar_warnc(bsdtar, 0,
					    "Meaningless argument for -C: ''");
					bsdtar->return_value = 1;
					goto cleanup;
				}
			}
			set_chdir(bsdtar, arg);
		} else {
			if (arg[0] != '/' &&
			    (arg[0] != '@' || arg[1] != '/') &&
			    (arg[0] != '@' || arg[1] != '@'))
				do_chdir(bsdtar); /* Handle a deferred -C */
			if (arg[0] == '@' && arg[1] == '@') {
				if (append_archive_tarsnap(bsdtar, a,
				    arg + 2) != 0)
					break;
			} else if (arg[0] == '@') {
				if (append_archive_filename(bsdtar, a,
				    arg + 1) != 0)
					break;
			} else
#if defined(_WIN32) && !defined(__CYGWIN__)
				write_hierarchy_win(bsdtar, a, arg,
				    write_hierarchy);
#else
				write_hierarchy(bsdtar, a, arg);
#endif
		}
		bsdtar->argv++;
	}

	/*
	 * This code belongs to bsdtar and is used when writing archives in
	 * "new cpio" format.  It has no effect in tarsnap, since tarsnap
	 * doesn't write archives in this format; but I'm leaving it in to
	 * make the diffs smaller.
	 */
	entry = NULL;
	archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
	while (entry != NULL) {
		write_entry_backend(bsdtar, a, entry, NULL, NULL);
		archive_entry_free(entry);
		entry = NULL;
		archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
	}

	if (archive_write_close(a)) {
		bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
		bsdtar->return_value = 1;
	}

cleanup:
	/* Free file data buffer. */
	free(bsdtar->buff);
	archive_entry_linkresolver_free(bsdtar->resolver);
	bsdtar->resolver = NULL;
	archive_read_finish(bsdtar->diskreader);
	bsdtar->diskreader = NULL;

	if (bsdtar->option_totals && (bsdtar->return_value == 0)) {
		fprintf(stderr, "Total bytes written: " BSDTAR_FILESIZE_PRINTF "\n",
		    (BSDTAR_FILESIZE_TYPE)archive_position_compressed(a));
	}

	archive_write_finish(a);

	/* Restore old SIGINFO + SIGUSR1 handlers. */
	siginfo_done(bsdtar);
}