2 * Copyright (C) 2009-2011 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35 #include "xvasprintf.h"
41 /* Currently open libguestfs handle. */
47 int keys_from_stdin = 0;
49 const char *libvirt_uri = NULL;
52 static const char *backup_extension = NULL;
53 static const char *perl_expr = NULL;
55 static void edit (const char *filename, const char *root);
56 static char *edit_interactively (const char *tmpfile);
57 static char *edit_non_interactively (const char *tmpfile);
58 static int is_windows (guestfs_h *g, const char *root);
59 static char *windows_path (guestfs_h *g, const char *root, const char *filename);
60 static char *generate_random_name (const char *filename);
61 static char *generate_backup_name (const char *filename);
64 bad_cast (char const *s)
69 static void __attribute__((noreturn))
72 if (status != EXIT_SUCCESS)
73 fprintf (stderr, _("Try `%s --help' for more information.\n"),
77 _("%s: Edit a file in a virtual machine\n"
78 "Copyright (C) 2009-2011 Red Hat Inc.\n"
80 " %s [--options] -d domname file [file ...]\n"
81 " %s [--options] -a disk.img [-a disk.img ...] file [file ...]\n"
83 " -a|--add image Add image\n"
84 " -b|--backup .ext Backup original as original.ext\n"
85 " -c|--connect uri Specify libvirt URI for -d option\n"
86 " -d|--domain guest Add disks from libvirt guest\n"
87 " --echo-keys Don't turn off echo for passphrases\n"
88 " -e|--expr expr Non-interactive editing using Perl expr\n"
89 " --format[=raw|..] Force disk format for -a option\n"
90 " --help Display brief help\n"
91 " --keys-from-stdin Read passphrases from stdin\n"
92 " -v|--verbose Verbose messages\n"
93 " -V|--version Display version and exit\n"
94 " -x Trace libguestfs API calls\n"
95 "For more information, see the manpage %s(1).\n"),
96 program_name, program_name, program_name,
103 main (int argc, char *argv[])
105 /* Set global program name that is not polluted with libtool artifacts. */
106 set_program_name (argv[0]);
108 setlocale (LC_ALL, "");
109 bindtextdomain (PACKAGE, LOCALEBASEDIR);
110 textdomain (PACKAGE);
112 /* We use random(3) below. */
113 srandom (time (NULL));
115 enum { HELP_OPTION = CHAR_MAX + 1 };
117 static const char *options = "a:b:c:d:e:vVx";
118 static const struct option long_options[] = {
119 { "add", 1, 0, 'a' },
120 { "backup", 1, 0, 'b' },
121 { "connect", 1, 0, 'c' },
122 { "domain", 1, 0, 'd' },
123 { "echo-keys", 0, 0, 0 },
124 { "expr", 1, 0, 'e' },
125 { "format", 2, 0, 0 },
126 { "help", 0, 0, HELP_OPTION },
127 { "keys-from-stdin", 0, 0, 0 },
128 { "verbose", 0, 0, 'v' },
129 { "version", 0, 0, 'V' },
132 struct drv *drvs = NULL;
134 const char *format = NULL;
139 g = guestfs_create ();
141 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
145 argv[0] = bad_cast (program_name);
148 c = getopt_long (argc, argv, options, long_options, &option_index);
152 case 0: /* options which are long only */
153 if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
155 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
157 } else if (STREQ (long_options[option_index].name, "format")) {
158 if (!optarg || STREQ (optarg, ""))
163 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
164 program_name, long_options[option_index].name, option_index);
174 if (backup_extension) {
175 fprintf (stderr, _("%s: -b option given multiple times\n"),
179 backup_extension = optarg;
192 fprintf (stderr, _("%s: -e option given multiple times\n"),
200 usage (EXIT_SUCCESS);
215 usage (EXIT_SUCCESS);
218 usage (EXIT_FAILURE);
222 /* Old-style syntax? There were no -a or -d options in the old
223 * virt-edit which is how we detect this.
226 /* argc - 1 because last parameter is the single filename. */
227 while (optind < argc - 1) {
228 if (strchr (argv[optind], '/') ||
229 access (argv[optind], F_OK) == 0) { /* simulate -a option */
230 drv = malloc (sizeof (struct drv));
236 drv->a.filename = argv[optind];
237 drv->a.format = NULL;
240 } else { /* simulate -d option */
241 drv = malloc (sizeof (struct drv));
247 drv->d.guest = argv[optind];
256 /* These are really constants, but they have to be variables for the
257 * options parsing code. Assert here that they have known-good
260 assert (read_only == 0);
261 assert (inspector == 1);
264 /* User must specify at least one filename on the command line. */
265 if (optind >= argc || argc - optind < 1)
266 usage (EXIT_FAILURE);
268 /* User must have specified some drives. */
270 usage (EXIT_FAILURE);
273 add_drives (drvs, 'a');
275 if (guestfs_launch (g) == -1)
280 /* Free up data structures, no longer needed after this point. */
283 /* Get root mountpoint. */
284 roots = guestfs_inspect_get_roots (g);
287 /* see fish/inspect.c:inspect_mount */
288 assert (roots[0] != NULL && roots[1] == NULL);
292 while (optind < argc) {
293 edit (argv[optind], root);
299 /* Cleanly unmount the disks after editing. */
300 if (guestfs_umount_all (g) == -1 || guestfs_sync (g) == -1)
309 edit (const char *filename, const char *root)
311 char *filename_to_free = NULL;
312 const char *tmpdir = guestfs_tmpdir ();
313 char tmpfile[strlen (tmpdir) + 32];
314 sprintf (tmpfile, "%s/virteditXXXXXX", tmpdir);
317 char *upload_from = NULL;
318 char *newname = NULL;
319 char *backupname = NULL;
321 /* Windows? Special handling is required. */
322 if (is_windows (g, root))
323 filename = filename_to_free = windows_path (g, root, filename);
325 /* Download the file to a temporary. */
326 fd = mkstemp (tmpfile);
332 snprintf (fdbuf, sizeof fdbuf, "/dev/fd/%d", fd);
334 if (guestfs_download (g, filename, fdbuf) == -1)
337 if (close (fd) == -1) {
343 upload_from = edit_interactively (tmpfile);
345 upload_from = edit_non_interactively (tmpfile);
347 /* We don't always need to upload: upload_from could be NULL because
348 * the user closed the editor without changing the file.
351 /* Upload to a new file in the same directory, so if it fails we
352 * don't end up with a partially written file. Give the new file
353 * a completely random name so we have only a tiny chance of
354 * overwriting some existing file.
356 newname = generate_random_name (filename);
358 if (guestfs_upload (g, upload_from, newname) == -1)
361 /* Backup or overwrite the file. */
362 if (backup_extension) {
363 backupname = generate_backup_name (filename);
364 if (guestfs_mv (g, filename, backupname) == -1)
367 if (guestfs_mv (g, newname, filename) == -1)
372 free (filename_to_free);
384 edit_interactively (const char *tmpfile)
386 struct utimbuf times;
387 struct stat oldstat, newstat;
393 /* Set the time back a few seconds on the original file. This is so
394 * that if the user is very fast at editing, or if EDITOR is an
395 * automatic editor, then the edit might happen within the 1 second
396 * granularity of mtime, and we would think the file hasn't changed.
398 if (stat (tmpfile, &oldstat) == -1) {
403 times.actime = oldstat.st_atime - 5;
404 times.modtime = oldstat.st_mtime - 5;
405 if (utime (tmpfile, ×) == -1) {
410 if (stat (tmpfile, &oldstat) == -1) {
415 editor = getenv ("EDITOR");
419 if (asprintf (&cmd, "%s %s", editor, tmpfile) == -1) {
425 fprintf (stderr, "%s\n", cmd);
428 if (r == -1 || WEXITSTATUS (r) != 0)
433 if (stat (tmpfile, &newstat) == -1) {
438 if (oldstat.st_ctime == newstat.st_ctime &&
439 oldstat.st_mtime == newstat.st_mtime) {
440 printf ("File not changed.\n");
444 ret = strdup (tmpfile);
454 edit_non_interactively (const char *tmpfile)
456 char *cmd, *outfile, *ret;
459 assert (perl_expr != NULL);
461 /* Pass the expression to Perl via the environment. This sidesteps
462 * any quoting problems with the already complex Perl command line.
464 setenv ("virt_edit_expr", perl_expr, 1);
466 /* Call out to a canned Perl script. */
470 "$expr = $ENV{virt_edit_expr}; "
475 " print STDOUT $_ or die \"print: $!\"; "
477 "close STDOUT or die \"close: $!\"; "
479 tmpfile, tmpfile) == -1) {
485 fprintf (stderr, "%s\n", cmd);
488 if (r == -1 || WEXITSTATUS (r) != 0)
493 if (asprintf (&outfile, "%s.out", tmpfile) == -1) {
498 if (rename (outfile, tmpfile) == -1) {
505 ret = strdup (tmpfile);
511 return ret; /* caller will free */
515 is_windows (guestfs_h *g, const char *root)
520 type = guestfs_inspect_get_type (g, root);
524 w = STREQ (type, "windows");
529 static void mount_drive_letter (char drive_letter, const char *root);
532 windows_path (guestfs_h *g, const char *root, const char *path)
537 /* If there is a drive letter, rewrite the path. */
538 if (c_isalpha (path[0]) && path[1] == ':') {
539 char drive_letter = c_tolower (path[0]);
540 /* This returns the newly allocated string. */
541 mount_drive_letter (drive_letter, root);
542 ret = strdup (path + 2);
563 /* Blindly convert any backslashes into forward slashes. Is this good? */
564 for (i = 0; i < strlen (ret); ++i)
568 char *t = guestfs_case_sensitive_path (g, ret);
576 mount_drive_letter (char drive_letter, const char *root)
582 /* Resolve the drive letter using the drive mappings table. */
583 drives = guestfs_inspect_get_drive_mappings (g, root);
584 if (drives == NULL || drives[0] == NULL) {
585 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
591 for (i = 0; drives[i] != NULL; i += 2) {
592 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
593 device = drives[i+1];
598 if (device == NULL) {
599 fprintf (stderr, _("%s: drive '%c:' not found.\n"),
600 program_name, drive_letter);
604 /* Unmount current disk and remount device. */
605 if (guestfs_umount_all (g) == -1)
608 if (guestfs_mount_options (g, "", device, "/") == -1)
611 for (i = 0; drives[i] != NULL; ++i)
614 /* Don't need to free (device) because that string was in the
622 char c[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
623 return c[random () % (sizeof c - 1)];
627 generate_random_name (const char *filename)
632 ret = malloc (strlen (filename) + 16);
637 strcpy (ret, filename);
639 p = strrchr (ret, '/');
643 /* Because of "+ 16" above, there should be enough space in the
644 * output buffer to write 8 random characters here.
646 for (i = 0; i < 8; ++i)
647 *p++ = random_char ();
650 return ret; /* caller will free */
654 generate_backup_name (const char *filename)
658 assert (backup_extension != NULL);
660 if (asprintf (&ret, "%s%s", filename, backup_extension) == -1) {
665 return ret; /* caller will free */