+/* Assuming DIR is the working directory, open FILE, using FLAGS to
+ control the open. A null DIR means to use ".". If we are low on
+ file descriptors, try to release one or more from DIR's parents to
+ reuse it. */
+int
+subfile_open (struct tar_stat_info const *dir, char const *file, int flags)
+{
+ int fd;
+
+ static bool initialized;
+ if (! initialized)
+ {
+ /* Initialize any tables that might be needed when file
+ descriptors are exhausted, and whose initialization might
+ require a file descriptor. This includes the system message
+ catalog and tar's message catalog. */
+ initialized = true;
+ strerror (ENOENT);
+ gettext ("");
+ }
+
+ while ((fd = openat (dir ? dir->fd : chdir_fd, file, flags)) < 0
+ && open_failure_recover (dir))
+ continue;
+ return fd;
+}
+
+/* Restore the file descriptor for ST->parent, if it was temporarily
+ closed to conserve file descriptors. On failure, set the file
+ descriptor to the negative of the corresponding errno value. Call
+ this every time a subdirectory is ascended from. */
+void
+restore_parent_fd (struct tar_stat_info const *st)
+{
+ struct tar_stat_info *parent = st->parent;
+ if (parent && ! parent->fd)
+ {
+ int parentfd = openat (st->fd, "..", open_searchdir_flags);
+ struct stat parentstat;
+
+ if (parentfd < 0)
+ parentfd = - errno;
+ else if (! (fstat (parentfd, &parentstat) == 0
+ && parent->stat.st_ino == parentstat.st_ino
+ && parent->stat.st_dev == parentstat.st_dev))
+ {
+ close (parentfd);
+ parentfd = IMPOSTOR_ERRNO;
+ }
+
+ if (parentfd < 0)
+ {
+ int origfd = openat (chdir_fd, parent->orig_file_name,
+ open_searchdir_flags);
+ if (0 <= origfd)
+ {
+ if (fstat (parentfd, &parentstat) == 0
+ && parent->stat.st_ino == parentstat.st_ino
+ && parent->stat.st_dev == parentstat.st_dev)
+ parentfd = origfd;
+ else
+ close (origfd);
+ }
+ }