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