+/* Download to a guest file to a local temporary file. Refuse to
+ * download the guest file if it is larger than max_size. The caller
+ * is responsible for deleting the temporary file after use.
+ */
+static int
+download_to_tmp (guestfs_h *g, const char *filename,
+ char *localtmp, int64_t max_size)
+{
+ int fd;
+ char buf[32];
+ int64_t size;
+
+ size = guestfs_filesize (g, filename);
+ if (size == -1)
+ /* guestfs_filesize failed and has already set error in handle */
+ return -1;
+ if (size > max_size) {
+ error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
+ filename, size);
+ return -1;
+ }
+
+ fd = mkstemp (localtmp);
+ if (fd == -1) {
+ perrorf (g, "mkstemp");
+ return -1;
+ }
+
+ snprintf (buf, sizeof buf, "/dev/fd/%d", fd);
+
+ if (guestfs_download (g, filename, buf) == -1) {
+ close (fd);
+ unlink (localtmp);
+ return -1;
+ }
+
+ if (close (fd) == -1) {
+ perrorf (g, "close: %s", localtmp);
+ unlink (localtmp);
+ return -1;
+ }
+
+ return 0;
+}
+