Escape filname printout properly, by Anthony Liguori and Julian Seward.
[qemu] / qemu-img.c
1 /*
2  * QEMU disk image utility
3  * 
4  * Copyright (c) 2003-2006 Fabrice Bellard
5  * 
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "vl.h"
25
26 #ifdef _WIN32
27 #include <windows.h>
28 #endif
29
30 void *get_mmap_addr(unsigned long size)
31 {
32     return NULL;
33 }
34
35 void qemu_free(void *ptr)
36 {
37     free(ptr);
38 }
39
40 void *qemu_malloc(size_t size)
41 {
42     return malloc(size);
43 }
44
45 void *qemu_mallocz(size_t size)
46 {
47     void *ptr;
48     ptr = qemu_malloc(size);
49     if (!ptr)
50         return NULL;
51     memset(ptr, 0, size);
52     return ptr;
53 }
54
55 char *qemu_strdup(const char *str)
56 {
57     char *ptr;
58     ptr = qemu_malloc(strlen(str) + 1);
59     if (!ptr)
60         return NULL;
61     strcpy(ptr, str);
62     return ptr;
63 }
64
65 void pstrcpy(char *buf, int buf_size, const char *str)
66 {
67     int c;
68     char *q = buf;
69
70     if (buf_size <= 0)
71         return;
72
73     for(;;) {
74         c = *str++;
75         if (c == 0 || q >= buf + buf_size - 1)
76             break;
77         *q++ = c;
78     }
79     *q = '\0';
80 }
81
82 /* strcat and truncate. */
83 char *pstrcat(char *buf, int buf_size, const char *s)
84 {
85     int len;
86     len = strlen(buf);
87     if (len < buf_size) 
88         pstrcpy(buf + len, buf_size - len, s);
89     return buf;
90 }
91
92 int strstart(const char *str, const char *val, const char **ptr)
93 {
94     const char *p, *q;
95     p = str;
96     q = val;
97     while (*q != '\0') {
98         if (*p != *q)
99             return 0;
100         p++;
101         q++;
102     }
103     if (ptr)
104         *ptr = p;
105     return 1;
106 }
107
108 void term_printf(const char *fmt, ...)
109 {
110     va_list ap;
111     va_start(ap, fmt);
112     vprintf(fmt, ap);
113     va_end(ap);
114 }
115
116 void term_print_filename(const char *filename)
117 {
118     term_printf(filename);
119 }
120
121 void __attribute__((noreturn)) error(const char *fmt, ...) 
122 {
123     va_list ap;
124     va_start(ap, fmt);
125     fprintf(stderr, "qemu-img: ");
126     vfprintf(stderr, fmt, ap);
127     fprintf(stderr, "\n");
128     exit(1);
129     va_end(ap);
130 }
131
132 static void format_print(void *opaque, const char *name)
133 {
134     printf(" %s", name);
135 }
136
137 void help(void)
138 {
139     printf("qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2006 Fabrice Bellard\n"
140            "usage: qemu-img command [command options]\n"
141            "QEMU disk image utility\n"
142            "\n"
143            "Command syntax:\n"
144            "  create [-e] [-b base_image] [-f fmt] filename [size]\n"
145            "  commit [-f fmt] filename\n"
146            "  convert [-c] [-e] [-f fmt] filename [-O output_fmt] output_filename\n"
147            "  info [-f fmt] filename\n"
148            "\n"
149            "Command parameters:\n"
150            "  'filename' is a disk image filename\n"
151            "  'base_image' is the read-only disk image which is used as base for a copy on\n"
152            "    write image; the copy on write image only stores the modified data\n"
153            "  'fmt' is the disk image format. It is guessed automatically in most cases\n"
154            "  'size' is the disk image size in kilobytes. Optional suffixes 'M' (megabyte)\n"
155            "    and 'G' (gigabyte) are supported\n"
156            "  'output_filename' is the destination disk image filename\n"
157            "  'output_fmt' is the destination format\n"
158            "  '-c' indicates that target image must be compressed (qcow format only)\n"
159            "  '-e' indicates that the target image must be encrypted (qcow format only)\n"
160            );
161     printf("\nSupported format:");
162     bdrv_iterate_format(format_print, NULL);
163     printf("\n");
164     exit(1);
165 }
166
167 #if defined(WIN32)
168 /* XXX: put correct support for win32 */
169 static int read_password(char *buf, int buf_size)
170 {
171     int c, i;
172     printf("Password: ");
173     fflush(stdout);
174     i = 0;
175     for(;;) {
176         c = getchar();
177         if (c == '\n')
178             break;
179         if (i < (buf_size - 1))
180             buf[i++] = c;
181     }
182     buf[i] = '\0';
183     return 0;
184 }
185
186 #else
187
188 #include <termios.h>
189
190 static struct termios oldtty;
191
192 static void term_exit(void)
193 {
194     tcsetattr (0, TCSANOW, &oldtty);
195 }
196
197 static void term_init(void)
198 {
199     struct termios tty;
200
201     tcgetattr (0, &tty);
202     oldtty = tty;
203
204     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
205                           |INLCR|IGNCR|ICRNL|IXON);
206     tty.c_oflag |= OPOST;
207     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
208     tty.c_cflag &= ~(CSIZE|PARENB);
209     tty.c_cflag |= CS8;
210     tty.c_cc[VMIN] = 1;
211     tty.c_cc[VTIME] = 0;
212     
213     tcsetattr (0, TCSANOW, &tty);
214
215     atexit(term_exit);
216 }
217
218 int read_password(char *buf, int buf_size)
219 {
220     uint8_t ch;
221     int i, ret;
222
223     printf("password: ");
224     fflush(stdout);
225     term_init();
226     i = 0;
227     for(;;) {
228         ret = read(0, &ch, 1);
229         if (ret == -1) {
230             if (errno == EAGAIN || errno == EINTR) {
231                 continue;
232             } else {
233                 ret = -1;
234                 break;
235             }
236         } else if (ret == 0) {
237             ret = -1;
238             break;
239         } else {
240             if (ch == '\r') {
241                 ret = 0;
242                 break;
243             }
244             if (i < (buf_size - 1))
245                 buf[i++] = ch;
246         }
247     }
248     term_exit();
249     buf[i] = '\0';
250     printf("\n");
251     return ret;
252 }
253 #endif
254
255 static BlockDriverState *bdrv_new_open(const char *filename,
256                                        const char *fmt)
257 {
258     BlockDriverState *bs;
259     BlockDriver *drv;
260     char password[256];
261
262     bs = bdrv_new("");
263     if (!bs)
264         error("Not enough memory");
265     if (fmt) {
266         drv = bdrv_find_format(fmt);
267         if (!drv)
268             error("Unknown file format '%s'", fmt);
269     } else {
270         drv = NULL;
271     }
272     if (bdrv_open2(bs, filename, 0, drv) < 0) {
273         error("Could not open '%s'", filename);
274     }
275     if (bdrv_is_encrypted(bs)) {
276         printf("Disk image '%s' is encrypted.\n", filename);
277         if (read_password(password, sizeof(password)) < 0)
278             error("No password given");
279         if (bdrv_set_key(bs, password) < 0)
280             error("invalid password");
281     }
282     return bs;
283 }
284
285 static int img_create(int argc, char **argv)
286 {
287     int c, ret, encrypted;
288     const char *fmt = "raw";
289     const char *filename;
290     const char *base_filename = NULL;
291     int64_t size;
292     const char *p;
293     BlockDriver *drv;
294     
295     encrypted = 0;
296     for(;;) {
297         c = getopt(argc, argv, "b:f:he");
298         if (c == -1)
299             break;
300         switch(c) {
301         case 'h':
302             help();
303             break;
304         case 'b':
305             base_filename = optarg;
306             break;
307         case 'f':
308             fmt = optarg;
309             break;
310         case 'e':
311             encrypted = 1;
312             break;
313         }
314     }
315     if (optind >= argc) 
316         help();
317     filename = argv[optind++];
318     size = 0;
319     if (base_filename) {
320         BlockDriverState *bs;
321         bs = bdrv_new_open(base_filename, NULL);
322         bdrv_get_geometry(bs, &size);
323         size *= 512;
324         bdrv_delete(bs);
325     } else {
326         if (optind >= argc)
327             help();
328         p = argv[optind];
329         size = strtoul(p, (char **)&p, 0);
330         if (*p == 'M') {
331             size *= 1024 * 1024;
332         } else if (*p == 'G') {
333             size *= 1024 * 1024 * 1024;
334         } else if (*p == 'k' || *p == 'K' || *p == '\0') {
335             size *= 1024;
336         } else {
337             help();
338         }
339     }
340     drv = bdrv_find_format(fmt);
341     if (!drv)
342         error("Unknown file format '%s'", fmt);
343     printf("Formating '%s', fmt=%s",
344            filename, fmt);
345     if (encrypted)
346         printf(", encrypted");
347     if (base_filename) {
348         printf(", backing_file=%s",
349                base_filename);
350     }
351     printf(", size=%" PRId64 " kB\n", (int64_t) (size / 1024));
352     ret = bdrv_create(drv, filename, size / 512, base_filename, encrypted);
353     if (ret < 0) {
354         if (ret == -ENOTSUP) {
355             error("Formatting or formatting option not supported for file format '%s'", fmt);
356         } else {
357             error("Error while formatting");
358         }
359     }
360     return 0;
361 }
362
363 static int img_commit(int argc, char **argv)
364 {
365     int c, ret;
366     const char *filename, *fmt;
367     BlockDriver *drv;
368     BlockDriverState *bs;
369
370     fmt = NULL;
371     for(;;) {
372         c = getopt(argc, argv, "f:h");
373         if (c == -1)
374             break;
375         switch(c) {
376         case 'h':
377             help();
378             break;
379         case 'f':
380             fmt = optarg;
381             break;
382         }
383     }
384     if (optind >= argc) 
385         help();
386     filename = argv[optind++];
387
388     bs = bdrv_new("");
389     if (!bs)
390         error("Not enough memory");
391     if (fmt) {
392         drv = bdrv_find_format(fmt);
393         if (!drv)
394             error("Unknown file format '%s'", fmt);
395     } else {
396         drv = NULL;
397     }
398     if (bdrv_open2(bs, filename, 0, drv) < 0) {
399         error("Could not open '%s'", filename);
400     }
401     ret = bdrv_commit(bs);
402     switch(ret) {
403     case 0:
404         printf("Image committed.\n");
405         break;
406     case -ENOENT:
407         error("No disk inserted");
408         break;
409     case -EACCES:
410         error("Image is read-only");
411         break;
412     case -ENOTSUP:
413         error("Image is already committed");
414         break;
415     default:
416         error("Error while committing image");
417         break;
418     }
419
420     bdrv_delete(bs);
421     return 0;
422 }
423
424 static int is_not_zero(const uint8_t *sector, int len)
425 {
426     int i;
427     len >>= 2;
428     for(i = 0;i < len; i++) {
429         if (((uint32_t *)sector)[i] != 0)
430             return 1;
431     }
432     return 0;
433 }
434
435 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
436 {
437     int v, i;
438
439     if (n <= 0) {
440         *pnum = 0;
441         return 0;
442     }
443     v = is_not_zero(buf, 512);
444     for(i = 1; i < n; i++) {
445         buf += 512;
446         if (v != is_not_zero(buf, 512))
447             break;
448     }
449     *pnum = i;
450     return v;
451 }
452
453 #define IO_BUF_SIZE 65536
454
455 static int img_convert(int argc, char **argv)
456 {
457     int c, ret, n, n1, compress, cluster_size, cluster_sectors, encrypt;
458     const char *filename, *fmt, *out_fmt, *out_filename;
459     BlockDriver *drv;
460     BlockDriverState *bs, *out_bs;
461     int64_t total_sectors, nb_sectors, sector_num;
462     uint8_t buf[IO_BUF_SIZE];
463     const uint8_t *buf1;
464     BlockDriverInfo bdi;
465
466     fmt = NULL;
467     out_fmt = "raw";
468     compress = 0;
469     encrypt = 0;
470     for(;;) {
471         c = getopt(argc, argv, "f:O:hce");
472         if (c == -1)
473             break;
474         switch(c) {
475         case 'h':
476             help();
477             break;
478         case 'f':
479             fmt = optarg;
480             break;
481         case 'O':
482             out_fmt = optarg;
483             break;
484         case 'c':
485             compress = 1;
486             break;
487         case 'e':
488             encrypt = 1;
489             break;
490         }
491     }
492     if (optind >= argc) 
493         help();
494     filename = argv[optind++];
495     if (optind >= argc) 
496         help();
497     out_filename = argv[optind++];
498     
499     bs = bdrv_new_open(filename, fmt);
500
501     drv = bdrv_find_format(out_fmt);
502     if (!drv)
503         error("Unknown file format '%s'", fmt);
504     if (compress && drv != &bdrv_qcow && drv != &bdrv_qcow2)
505         error("Compression not supported for this file format");
506     if (encrypt && drv != &bdrv_qcow && drv != &bdrv_qcow2)
507         error("Encryption not supported for this file format");
508     if (compress && encrypt)
509         error("Compression and encryption not supported at the same time");
510     bdrv_get_geometry(bs, &total_sectors);
511     ret = bdrv_create(drv, out_filename, total_sectors, NULL, encrypt);
512     if (ret < 0) {
513         if (ret == -ENOTSUP) {
514             error("Formatting not supported for file format '%s'", fmt);
515         } else {
516             error("Error while formatting '%s'", out_filename);
517         }
518     }
519     
520     out_bs = bdrv_new_open(out_filename, out_fmt);
521
522     if (compress) {
523         if (bdrv_get_info(out_bs, &bdi) < 0)
524             error("could not get block driver info");
525         cluster_size = bdi.cluster_size;
526         if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE)
527             error("invalid cluster size");
528         cluster_sectors = cluster_size >> 9;
529         sector_num = 0;
530         for(;;) {
531             nb_sectors = total_sectors - sector_num;
532             if (nb_sectors <= 0)
533                 break;
534             if (nb_sectors >= cluster_sectors)
535                 n = cluster_sectors;
536             else
537                 n = nb_sectors;
538             if (bdrv_read(bs, sector_num, buf, n) < 0) 
539                 error("error while reading");
540             if (n < cluster_sectors)
541                 memset(buf + n * 512, 0, cluster_size - n * 512);
542             if (is_not_zero(buf, cluster_size)) {
543                 if (bdrv_write_compressed(out_bs, sector_num, buf, 
544                                           cluster_sectors) != 0)
545                     error("error while compressing sector %" PRId64,
546                           sector_num);
547             }
548             sector_num += n;
549         }
550         /* signal EOF to align */
551         bdrv_write_compressed(out_bs, 0, NULL, 0);
552     } else {
553         sector_num = 0;
554         for(;;) {
555             nb_sectors = total_sectors - sector_num;
556             if (nb_sectors <= 0)
557                 break;
558             if (nb_sectors >= (IO_BUF_SIZE / 512))
559                 n = (IO_BUF_SIZE / 512);
560             else
561                 n = nb_sectors;
562             if (bdrv_read(bs, sector_num, buf, n) < 0) 
563                 error("error while reading");
564             /* NOTE: at the same time we convert, we do not write zero
565                sectors to have a chance to compress the image. Ideally, we
566                should add a specific call to have the info to go faster */
567             buf1 = buf;
568             while (n > 0) {
569                 if (is_allocated_sectors(buf1, n, &n1)) {
570                     if (bdrv_write(out_bs, sector_num, buf1, n1) < 0) 
571                         error("error while writing");
572                 }
573                 sector_num += n1;
574                 n -= n1;
575                 buf1 += n1 * 512;
576             }
577         }
578     }
579     bdrv_delete(out_bs);
580     bdrv_delete(bs);
581     return 0;
582 }
583
584 #ifdef _WIN32
585 static int64_t get_allocated_file_size(const char *filename)
586 {
587     typedef DWORD (WINAPI * get_compressed_t)(const char *filename, DWORD *high);
588     get_compressed_t get_compressed;
589     struct _stati64 st;
590
591     /* WinNT support GetCompressedFileSize to determine allocate size */
592     get_compressed = (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"), "GetCompressedFileSizeA");
593     if (get_compressed) {
594         DWORD high, low;
595         low = get_compressed(filename, &high);
596         if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR)
597             return (((int64_t) high) << 32) + low;
598     }
599
600     if (_stati64(filename, &st) < 0) 
601         return -1;
602     return st.st_size;
603 }
604 #else
605 static int64_t get_allocated_file_size(const char *filename)
606 {
607     struct stat st;
608     if (stat(filename, &st) < 0) 
609         return -1;
610     return (int64_t)st.st_blocks * 512;
611 }
612 #endif
613
614 static void dump_snapshots(BlockDriverState *bs)
615 {
616     QEMUSnapshotInfo *sn_tab, *sn;
617     int nb_sns, i;
618     char buf[256];
619
620     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
621     if (nb_sns <= 0)
622         return;
623     printf("Snapshot list:\n");
624     printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
625     for(i = 0; i < nb_sns; i++) {
626         sn = &sn_tab[i];
627         printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
628     }
629     qemu_free(sn_tab);
630 }
631
632 static int img_info(int argc, char **argv)
633 {
634     int c;
635     const char *filename, *fmt;
636     BlockDriver *drv;
637     BlockDriverState *bs;
638     char fmt_name[128], size_buf[128], dsize_buf[128];
639     int64_t total_sectors, allocated_size;
640     char backing_filename[1024];
641     char backing_filename2[1024];
642     BlockDriverInfo bdi;
643
644     fmt = NULL;
645     for(;;) {
646         c = getopt(argc, argv, "f:h");
647         if (c == -1)
648             break;
649         switch(c) {
650         case 'h':
651             help();
652             break;
653         case 'f':
654             fmt = optarg;
655             break;
656         }
657     }
658     if (optind >= argc) 
659         help();
660     filename = argv[optind++];
661
662     bs = bdrv_new("");
663     if (!bs)
664         error("Not enough memory");
665     if (fmt) {
666         drv = bdrv_find_format(fmt);
667         if (!drv)
668             error("Unknown file format '%s'", fmt);
669     } else {
670         drv = NULL;
671     }
672     if (bdrv_open2(bs, filename, 0, drv) < 0) {
673         error("Could not open '%s'", filename);
674     }
675     bdrv_get_format(bs, fmt_name, sizeof(fmt_name));
676     bdrv_get_geometry(bs, &total_sectors);
677     get_human_readable_size(size_buf, sizeof(size_buf), total_sectors * 512);
678     allocated_size = get_allocated_file_size(filename);
679     if (allocated_size < 0)
680         sprintf(dsize_buf, "unavailable");
681     else
682         get_human_readable_size(dsize_buf, sizeof(dsize_buf), 
683                                 allocated_size);
684     printf("image: %s\n"
685            "file format: %s\n"
686            "virtual size: %s (%" PRId64 " bytes)\n"
687            "disk size: %s\n",
688            filename, fmt_name, size_buf, 
689            (total_sectors * 512),
690            dsize_buf);
691     if (bdrv_is_encrypted(bs))
692         printf("encrypted: yes\n");
693     if (bdrv_get_info(bs, &bdi) >= 0) {
694         if (bdi.cluster_size != 0) 
695             printf("cluster_size: %d\n", bdi.cluster_size);
696     }
697     bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
698     if (backing_filename[0] != '\0') {
699         path_combine(backing_filename2, sizeof(backing_filename2),
700                      filename, backing_filename);
701         printf("backing file: %s (actual path: %s)\n", 
702                backing_filename,
703                backing_filename2);
704     }
705     dump_snapshots(bs);
706     bdrv_delete(bs);
707     return 0;
708 }
709
710 int main(int argc, char **argv)
711 {
712     const char *cmd;
713
714     bdrv_init();
715     if (argc < 2)
716         help();
717     cmd = argv[1];
718     optind++;
719     if (!strcmp(cmd, "create")) {
720         img_create(argc, argv);
721     } else if (!strcmp(cmd, "commit")) {
722         img_commit(argc, argv);
723     } else if (!strcmp(cmd, "convert")) {
724         img_convert(argc, argv);
725     } else if (!strcmp(cmd, "info")) {
726         img_info(argc, argv);
727     } else {
728         help();
729     }
730     return 0;
731 }