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