edit: Allow Windows-style drive letters and paths to be used.
[libguestfs.git] / tools / virt-edit
1 #!/usr/bin/perl -w
2 # virt-edit
3 # Copyright (C) 2009-2011 Red Hat Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 use warnings;
20 use strict;
21
22 use Sys::Guestfs;
23 use Sys::Guestfs::Lib qw(open_guest);
24 use Pod::Usage;
25 use Getopt::Long;
26 use File::Temp qw/tempfile/;
27 use File::Basename;
28 use Locale::TextDomain 'libguestfs';
29
30 =encoding utf8
31
32 =head1 NAME
33
34 virt-edit - Edit a file in a virtual machine
35
36 =head1 SYNOPSIS
37
38  virt-edit [--options] domname file
39
40  virt-edit [--options] disk.img [disk.img ...] file
41
42  virt-edit [domname|disk.img] file -e 'expr'
43
44 =head1 WARNING
45
46 You must I<not> use C<virt-edit> on live virtual machines.  If you do
47 this, you risk disk corruption in the VM.  C<virt-edit> tries to stop
48 you from doing this, but doesn't catch all cases.
49
50 =head1 DESCRIPTION
51
52 C<virt-edit> is a command line tool to edit C<file> where C<file>
53 exists in the named virtual machine (or disk image).
54
55 If you want to just view a file, use L<virt-cat(1)>.
56
57 For more complex cases you should look at the L<guestfish(1)> tool
58 (see L</USING GUESTFISH> below).
59
60 C<virt-edit> cannot be used to create a new file, nor to edit
61 multiple files.  L<guestfish(1)> can do that and much more.
62
63 =head1 EXAMPLES
64
65 Edit the named files interactively:
66
67  virt-edit mydomain /boot/grub/grub.conf
68
69  virt-edit mydomain /etc/passwd
70
71 For Windows guests, some Windows paths are understood:
72
73  virt-edit mywindomain 'c:\autoexec.bat'
74
75 You can also edit files non-interactively (see
76 L</NON-INTERACTIVE EDITING> below).
77 To change the init default level to 5:
78
79  virt-edit mydomain /etc/inittab -e 's/^id:.*/id:5:initdefault:/'
80
81 =head1 OPTIONS
82
83 =over 4
84
85 =cut
86
87 my $help;
88
89 =item B<--help>
90
91 Display brief help.
92
93 =cut
94
95 my $version;
96
97 =item B<--version>
98
99 Display version number and exit.
100
101 =cut
102
103 my $backup;
104
105 =item B<--backup extension> | B<-b extension>
106
107 Create a backup of the original file I<in the guest disk image>.
108 The backup has the original filename with C<extension> added.
109
110 Usually the first character of C<extension> would be a dot C<.>
111 so you would write:
112
113  virt-edit -b .orig [etc]
114
115 By default, no backup file is made.
116
117 =cut
118
119 my $uri;
120
121 =item B<--connect URI> | B<-c URI>
122
123 If using libvirt, connect to the given I<URI>.  If omitted, then we
124 connect to the default libvirt hypervisor.
125
126 If you specify guest block devices directly, then libvirt is not used
127 at all.
128
129 =cut
130
131 my $format;
132
133 =item B<--format> raw
134
135 Specify the format of disk images given on the command line.  If this
136 is omitted then the format is autodetected from the content of the
137 disk image.
138
139 If disk images are requested from libvirt, then this program asks
140 libvirt for this information.  In this case, the value of the format
141 parameter is ignored.
142
143 If working with untrusted raw-format guest disk images, you should
144 ensure the format is always specified.
145
146 =cut
147
148 my $expr;
149
150 =item B<--expr EXPR> | B<-e EXPR>
151
152 Instead of launching the external editor, non-interactively
153 apply the Perl expression C<EXPR> to each line in the file.
154 See L</NON-INTERACTIVE EDITING> below.
155
156 Be careful to properly quote the expression to prevent it from
157 being altered by the shell.
158
159 =back
160
161 =cut
162
163 GetOptions ("help|?" => \$help,
164             "version" => \$version,
165             "connect|c=s" => \$uri,
166             "format=s" => \$format,
167             "expr|e=s" => \$expr,
168             "backup|b=s" => \$backup,
169     ) or pod2usage (2);
170 pod2usage (1) if $help;
171 if ($version) {
172     my $g = Sys::Guestfs->new ();
173     my %h = $g->version ();
174     print "$h{major}.$h{minor}.$h{release}$h{extra}\n";
175     exit
176 }
177
178 pod2usage (__"virt-edit: no image, VM names or filenames to edit given")
179     if @ARGV <= 1;
180
181 my $filename = pop @ARGV;
182
183 my $g;
184 if ($uri) {
185     $g = open_guest (\@ARGV, address => $uri, rw => 1, format => $format);
186 } else {
187     $g = open_guest (\@ARGV, rw => 1, format => $format);
188 }
189
190 $g->launch ();
191
192 my @roots = $g->inspect_os ();
193 if (@roots == 0) {
194     die __x("{prog}: No operating system could be detected inside this disk image.\n\nThis may be because the file is not a disk image, or is not a virtual machine\nimage, or because the OS type is not understood by libguestfs.\n\nIf you feel this is an error, please file a bug report including as much\ninformation about the disk image as possible.\n",
195             prog => basename ($0));
196 }
197 if (@roots > 1) {
198     die __x("{prog}: multiboot operating systems are not supported.\n",
199             prog => basename ($0))
200 }
201 my $root = $roots[0];
202 my %fses = $g->inspect_get_mountpoints ($root);
203 my @fses = sort { length $a <=> length $b } keys %fses;
204 foreach (@fses) {
205     $g->mount_options ("", $fses{$_}, $_);
206 }
207
208 # Special handling for Windows filenames.
209 $filename = windows_path ($g, $root, $filename)
210     if $g->inspect_get_type ($root) eq "windows";
211
212 my ($fh, $tempname) = tempfile (UNLINK => 1);
213 my $fddev = "/dev/fd/" . fileno ($fh);
214
215 # Allow this to fail in case eg. the file does not exist.
216 $g->download ($filename, $fddev);
217
218 close $fh or die "close: $!";
219
220 my $do_upload = $tempname;
221
222 if (!defined $expr) {
223     # Interactively edit the file.
224     my $oldctime = (stat ($tempname))[10];
225
226     my $editor = $ENV{EDITOR};
227     $editor ||= "vi";
228     system ("$editor $tempname") == 0
229         or die "edit failed: $editor: $?";
230
231     my $newctime = (stat ($tempname))[10];
232
233     if ($oldctime == $newctime) {
234         $do_upload = undef;
235         print __"File not changed.\n";
236     }
237 } else {
238     my ($fh, $tempout) = tempfile (UNLINK => 1);
239
240     # Apply a Perl expression to the lines of the file.
241     open IFILE, $tempname or die "$tempname: $!";
242     my $lineno = 0;
243     while (<IFILE>) {
244         $lineno++;
245         eval $expr;
246         die if $@;
247         print $fh $_ or die "print: $!";
248     }
249     close $fh or die "close: $!";
250
251     $do_upload = $tempout;
252 }
253
254 if (defined $do_upload) {
255     # Upload to a new file, so if it fails we don't end up with
256     # a partially written file.  Give the new file a completely
257     # random name so we have only a tiny chance of overwriting
258     # some existing file.
259     my $dirname = $filename;
260     $dirname =~ s{/[^/]+$}{/};
261
262     my @chars = ('a'..'z', 'A'..'Z', '0'..'9');
263     my $newname = $dirname;
264     foreach (0..7) {
265         $newname .= $chars[rand @chars];
266     }
267
268     $g->upload ($do_upload, $newname);
269
270     # Backup or overwrite?
271     $g->mv ($filename, "$filename$backup") if defined $backup;
272     $g->mv ($newname, $filename);
273
274     $g->umount_all ();
275     $g->sync ();
276 }
277
278 undef $g;
279
280 =head1 NON-INTERACTIVE EDITING
281
282 C<virt-edit> normally calls out to C<$EDITOR> (or vi) so
283 the system administrator can interactively edit the file.
284
285 There are two ways also to use C<virt-edit> from scripts in order to
286 make automated edits to files.  (Note that although you I<can> use
287 C<virt-edit> like this, it's less error-prone to write scripts
288 directly using the libguestfs API and Augeas for configuration file
289 editing.)
290
291 The first method is to temporarily set C<$EDITOR> to any script or
292 program you want to run.  The script is invoked as C<$EDITOR tmpfile>
293 and it should update C<tmpfile> in place however it likes.
294
295 The second method is to use the C<-e> parameter of C<virt-edit> to run
296 a short Perl snippet in the style of L<sed(1)>.  For example to
297 replace all instances of C<foo> with C<bar> in a file:
298
299  virt-edit domname filename -e 's/foo/bar/'
300
301 The full power of Perl regular expressions can be used (see
302 L<perlre(1)>).  For example to delete root's password you could do:
303
304  virt-edit domname /etc/passwd -e 's/^root:.*?:/root::/'
305
306 What really happens is that the snippet is evaluated as a Perl
307 expression for each line of the file.  The line, including the final
308 C<\n>, is passed in C<$_> and the expression should update C<$_> or
309 leave it unchanged.
310
311 To delete a line, set C<$_> to the empty string.  For example, to
312 delete the C<apache> user account from the password file you can do:
313
314  virt-edit mydomain /etc/passwd -e '$_ = "" if /^apache:/'
315
316 To insert a line, prepend or append it to C<$_>.  However appending
317 lines to the end of the file is rather difficult this way since there
318 is no concept of "last line of the file" - your expression just
319 doesn't get called again.  You might want to use the first method
320 (setting C<$EDITOR>) if you want to do this.
321
322 The variable C<$lineno> contains the current line number.
323 As is traditional, the first line in the file is number C<1>.
324
325 The return value from the expression is ignored, but the expression
326 may call C<die> in order to abort the whole program, leaving the
327 original file untouched.
328
329 Remember when matching the end of a line that C<$_> may contain the
330 final C<\n>, or (for DOS files) C<\r\n>, or if the file does not end
331 with a newline then neither of these.  Thus to match or substitute
332 some text at the end of a line, use this regular expression:
333
334  /some text(\r?\n)?$/
335
336 Alternately, use the perl C<chomp> function, being careful not to
337 chomp C<$_> itself (since that would remove all newlines from the
338 file):
339
340  my $m = $_; chomp $m; $m =~ /some text$/
341
342 =head1 WINDOWS PATHS
343
344 C<virt-edit> has a limited ability to understand Windows drive letters
345 and paths (eg. C<E:\foo\bar.txt>).
346
347 If and only if the guest is running Windows then:
348
349 =over 4
350
351 =item *
352
353 Drive letter prefixes like C<C:> are resolved against the
354 Windows Registry to the correct filesystem.
355
356 =item *
357
358 Any backslash (C<\>) characters in the path are replaced
359 with forward slashes so that libguestfs can process it.
360
361 =item *
362
363 The path is resolved case insensitively to locate the file
364 that should be edited.
365
366 =back
367
368 There are some known shortcomings:
369
370 =over 4
371
372 =item *
373
374 Some NTFS symbolic links may not be followed correctly.
375
376 =item *
377
378 NTFS junction points that cross filesystems are not followed.
379
380 =back
381
382 =cut
383
384 sub windows_path
385 {
386     my $g = shift;
387     my $root = shift;
388     my $filename = shift;
389
390     # Deal with drive letters.
391     if ($filename =~ /^([a-z]):(.*)/i) {
392         $filename = $2;
393         my $drive_letter = $1;
394
395         # Look up the drive letter in the drive mapping table.  We
396         # have to do a case insensitive comparison, the slow way.
397         my $device;
398         my %drives = $g->inspect_get_drive_mappings ($root);
399         foreach (keys %drives) {
400             if (lc $_ eq lc $drive_letter) {
401                 $device = $drives{$_};
402                 last;
403             }
404         }
405
406         die __x("virt-edit: drive '{x}:' not found\n", x => $drive_letter)
407             unless defined $device;
408
409         # Unmount current disk and remount $device.
410         $g->umount_all ();
411         $g->mount_options ("", $device, "/");
412     }
413
414     # Replace any backslashes in the rest of the path with
415     # forward slashes.
416     $filename =~ s{\\}{/}g;
417
418     # If the user put \foo on the command line without quoting it
419     # properly, then we'll see that here as a bare path.  Add a more
420     # descriptive error message here.
421     if (substr ($filename, 0, 1) ne "/") {
422         die __x("virt-edit: '{f}' does not start with a / or \\ character.
423 If you are using Windows style paths with backslashes like C:\\foo.txt
424 then don't forget that you must quote them with single quotes to
425 prevent the shell from munging the backslashes.\n",
426                 f => $filename)
427     }
428
429     # Case sensitivity.
430     $filename = $g->case_sensitive_path ($filename);
431
432     return $filename;
433 }
434
435 =head1 USING GUESTFISH
436
437 L<guestfish(1)> is a more powerful, lower level tool which you can use
438 when C<virt-edit> doesn't work.
439
440 Using C<virt-edit> is approximately equivalent to doing:
441
442  guestfish --rw -i -d domname edit /file
443
444 where C<domname> is the name of the libvirt guest, and C</file> is the
445 full path to the file.
446
447 The command above uses libguestfs's guest inspection feature and so
448 does not work on guests that libguestfs cannot inspect, or on things
449 like arbitrary disk images that don't contain guests.  To edit a file
450 on a disk image directly, use:
451
452  guestfish --rw -a disk.img -m /dev/sda1 edit /file
453
454 where C<disk.img> is the disk image, C</dev/sda1> is the filesystem
455 within the disk image to edit, and C</file> is the full path to the
456 file.
457
458 C<virt-edit> cannot create new files.  Use the guestfish commands
459 C<touch>, C<write> or C<upload> instead:
460
461  guestfish --rw -i -d domname touch /newfile
462
463  guestfish --rw -i -d domname write /newfile "new content"
464
465  guestfish --rw -i -d domname upload localfile /newfile
466
467 C<virt-edit> cannot edit multiple files, but guestfish can
468 do it like this:
469
470  guestfish --rw -i -d domname edit /file1 : edit /file2
471
472 =cut
473
474 exit 0;
475
476 =head1 ENVIRONMENT VARIABLES
477
478 =over 4
479
480 =item C<EDITOR>
481
482 If set, this string is used as the editor.  It may contain arguments,
483 eg. C<"emacs -nw">
484
485 If not set, C<vi> is used.
486
487 =back
488
489 =head1 SHELL QUOTING
490
491 Libvirt guest names can contain arbitrary characters, some of which
492 have meaning to the shell such as C<#> and space.  You may need to
493 quote or escape these characters on the command line.  See the shell
494 manual page L<sh(1)> for details.
495
496 =head1 SEE ALSO
497
498 L<guestfs(3)>,
499 L<guestfish(1)>,
500 L<virt-cat(1)>,
501 L<virt-copy-in(1)>,
502 L<virt-tar-in(1)>,
503 L<Sys::Guestfs(3)>,
504 L<Sys::Guestfs::Lib(3)>,
505 L<Sys::Virt(3)>,
506 L<http://libguestfs.org/>,
507 L<perl(1)>,
508 L<perlre(1)>.
509
510 =head1 AUTHOR
511
512 Richard W.M. Jones L<http://people.redhat.com/~rjones/>
513
514 =head1 COPYRIGHT
515
516 Copyright (C) 2009-2011 Red Hat Inc.
517
518 This program is free software; you can redistribute it and/or modify
519 it under the terms of the GNU General Public License as published by
520 the Free Software Foundation; either version 2 of the License, or
521 (at your option) any later version.
522
523 This program is distributed in the hope that it will be useful,
524 but WITHOUT ANY WARRANTY; without even the implied warranty of
525 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
526 GNU General Public License for more details.
527
528 You should have received a copy of the GNU General Public License
529 along with this program; if not, write to the Free Software
530 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.