d52ad2c71226933cf3757d8dada7b8208288a2a5
[libguestfs.git] / daemon / parted.c
1 /* libguestfs - the guestfsd daemon
2  * Copyright (C) 2009-2011 Red Hat Inc.
3  *
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.
8  *
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.
13  *
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.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <inttypes.h>
25 #include <string.h>
26 #include <unistd.h>
27
28 #include "daemon.h"
29 #include "actions.h"
30
31 /* Notes:
32  *
33  * Parted 1.9 sends error messages to stdout, hence use of the
34  * COMMAND_FLAG_FOLD_STDOUT_ON_STDERR flag.
35  *
36  * parted occasionally fails to do ioctl(BLKRRPART) on the device,
37  * apparently because of some internal race in the code.  We attempt
38  * to detect and recover from this error if we can.
39  */
40 static int
41 recover_blkrrpart (const char *device, const char *err)
42 {
43   int r;
44
45   if (!strstr (err,
46                "Error informing the kernel about modifications to partition"))
47     return -1;
48
49   r = command (NULL, NULL, "blockdev", "--rereadpt", device, NULL);
50   if (r == -1)
51     return -1;
52
53   udev_settle ();
54
55   return 0;
56 }
57
58 #define RUN_PARTED(error,device,...)                                    \
59   do {                                                                  \
60     int r;                                                              \
61     char *err;                                                          \
62                                                                         \
63     r = commandf (NULL, &err, COMMAND_FLAG_FOLD_STDOUT_ON_STDERR,       \
64                   "parted", "-s", "--", (device), __VA_ARGS__);   \
65     if (r == -1) {                                                      \
66       if (recover_blkrrpart ((device), err) == -1) {                    \
67         reply_with_error ("%s: parted: %s: %s", __func__, (device), err); \
68         free (err);                                                     \
69         error;                                                          \
70       }                                                                 \
71     }                                                                   \
72                                                                         \
73     free (err);                                                         \
74   } while (0)
75
76 static const char *
77 check_parttype (const char *parttype)
78 {
79   /* Check and translate parttype. */
80   if (STREQ (parttype, "aix") ||
81       STREQ (parttype, "amiga") ||
82       STREQ (parttype, "bsd") ||
83       STREQ (parttype, "dasd") ||
84       STREQ (parttype, "dvh") ||
85       STREQ (parttype, "gpt") ||
86       STREQ (parttype, "mac") ||
87       STREQ (parttype, "msdos") ||
88       STREQ (parttype, "pc98") ||
89       STREQ (parttype, "sun"))
90     return parttype;
91   else if (STREQ (parttype, "rdb"))
92     return "amiga";
93   else if (STREQ (parttype, "efi"))
94     return "gpt";
95   else if (STREQ (parttype, "mbr"))
96     return "msdos";
97   else
98     return NULL;
99 }
100
101 int
102 do_part_init (const char *device, const char *parttype)
103 {
104   parttype = check_parttype (parttype);
105   if (!parttype) {
106     reply_with_error ("unknown partition type: common choices are \"gpt\" and \"msdos\"");
107     return -1;
108   }
109
110   RUN_PARTED (return -1, device, "mklabel", parttype, NULL);
111
112   udev_settle ();
113
114   return 0;
115 }
116
117 int
118 do_part_add (const char *device, const char *prlogex,
119              int64_t startsect, int64_t endsect)
120 {
121   char startstr[32];
122   char endstr[32];
123
124   /* Check and translate prlogex. */
125   if (STREQ (prlogex, "primary") ||
126       STREQ (prlogex, "logical") ||
127       STREQ (prlogex, "extended"))
128     ;
129   else if (STREQ (prlogex, "p"))
130     prlogex = "primary";
131   else if (STREQ (prlogex, "l"))
132     prlogex = "logical";
133   else if (STREQ (prlogex, "e"))
134     prlogex = "extended";
135   else {
136     reply_with_error ("unknown partition type: %s: this should be \"primary\", \"logical\" or \"extended\"", prlogex);
137     return -1;
138   }
139
140   if (startsect < 0) {
141     reply_with_error ("startsect cannot be negative");
142     return -1;
143   }
144   /* but endsect can be negative */
145
146   snprintf (startstr, sizeof startstr, "%" PRIi64 "s", startsect);
147   snprintf (endstr, sizeof endstr, "%" PRIi64 "s", endsect);
148
149   /* XXX Bug: If the partition table type (which we don't know in this
150    * function) is GPT, then this parted command sets the _partition
151    * name_ to prlogex, eg. "primary".  I would essentially describe
152    * this as a bug in the parted mkpart command.
153    */
154   RUN_PARTED (return -1, device, "mkpart", prlogex, startstr, endstr, NULL);
155
156   udev_settle ();
157
158   return 0;
159 }
160
161 int
162 do_part_del (const char *device, int partnum)
163 {
164   if (partnum <= 0) {
165     reply_with_error ("partition number must be >= 1");
166     return -1;
167   }
168
169   char partnum_str[16];
170   snprintf (partnum_str, sizeof partnum_str, "%d", partnum);
171
172   RUN_PARTED (return -1, device, "rm", partnum_str, NULL);
173
174   udev_settle ();
175   return 0;
176 }
177
178 int
179 do_part_disk (const char *device, const char *parttype)
180 {
181   parttype = check_parttype (parttype);
182   if (!parttype) {
183     reply_with_error ("unknown partition type: common choices are \"gpt\" and \"msdos\"");
184     return -1;
185   }
186
187   /* Align all partitions created this way to 64 sectors, and leave
188    * the last 64 sectors at the end of the disk free.  This wastes
189    * 32K+32K = 64K on 512-byte sector disks.  The rationale is:
190    *
191    * - aligned operations are faster
192    * - GPT requires at least 34 sectors at the end of the disk.
193    */
194   const char *startstr = "64s";
195   const char *endstr = "-64s";
196
197   RUN_PARTED (return -1,
198               device,
199               "mklabel", parttype,
200               /* See comment about about the parted mkpart command. */
201               "mkpart", STREQ (parttype, "gpt") ? "p1" : "primary",
202               startstr, endstr, NULL);
203
204   udev_settle ();
205
206   return 0;
207 }
208
209 int
210 do_part_set_bootable (const char *device, int partnum, int bootable)
211 {
212   if (partnum <= 0) {
213     reply_with_error ("partition number must be >= 1");
214     return -1;
215   }
216
217   char partstr[16];
218
219   snprintf (partstr, sizeof partstr, "%d", partnum);
220
221   RUN_PARTED (return -1,
222               device, "set", partstr, "boot", bootable ? "on" : "off", NULL);
223
224   udev_settle ();
225
226   return 0;
227 }
228
229 int
230 do_part_set_name (const char *device, int partnum, const char *name)
231 {
232   if (partnum <= 0) {
233     reply_with_error ("partition number must be >= 1");
234     return -1;
235   }
236
237   char partstr[16];
238
239   snprintf (partstr, sizeof partstr, "%d", partnum);
240
241   RUN_PARTED (return -1, device, "name", partstr, name, NULL);
242
243   udev_settle ();
244
245   return 0;
246 }
247
248 /* Return the nth field from a string of ':'/';'-delimited strings.
249  * Useful for parsing the return value from 'parted -m'.
250  */
251 static char *
252 get_table_field (const char *line, int n)
253 {
254   const char *p = line;
255
256   while (*p && n > 0) {
257     p += strcspn (p, ":;") + 1;
258     n--;
259   }
260
261   if (n > 0) {
262     reply_with_error ("not enough fields in output of parted print command: %s",
263                       line);
264     return NULL;
265   }
266
267   size_t len = strcspn (p, ":;");
268   char *q = strndup (p, len);
269   if (q == NULL) {
270     reply_with_perror ("strndup");
271     return NULL;
272   }
273
274   return q;
275 }
276
277 /* RHEL 5 parted doesn't have the -m (machine readable) option so we
278  * must do a lot more work to parse the output in
279  * print_partition_table below.  Test for this option the first time
280  * this function is called.
281  */
282 static int
283 test_parted_m_opt (void)
284 {
285   static int result = -1;
286
287   if (result >= 0)
288     return result;
289
290   char *err = NULL;
291   int r = commandr (NULL, &err, "parted", "-s", "-m", "/dev/null", NULL);
292   if (r == -1) {
293     /* Test failed, eg. missing or completely unusable parted binary. */
294     reply_with_error ("could not run 'parted' command");
295     free (err);
296     return -1;
297   }
298
299   if (err && strstr (err, "invalid option -- m"))
300     result = 0;
301   else
302     result = 1;
303   free (err);
304   return result;
305 }
306
307 static char *
308 print_partition_table (const char *device, int parted_has_m_opt)
309 {
310   char *out, *err;
311   int r;
312
313   if (parted_has_m_opt)
314     r = command (&out, &err, "parted", "-m", "--", device,
315                  "unit", "b",
316                  "print", NULL);
317   else
318     r = command (&out, &err, "parted", "-s", "--", device,
319                  "unit", "b",
320                  "print", NULL);
321   if (r == -1) {
322     reply_with_error ("parted print: %s: %s", device,
323                       /* Hack for parted 1.x which sends errors to stdout. */
324                       *err ? err : out);
325     free (out);
326     free (err);
327     return NULL;
328   }
329   free (err);
330
331   return out;
332 }
333
334 char *
335 do_part_get_parttype (const char *device)
336 {
337   int parted_has_m_opt = test_parted_m_opt ();
338   if (parted_has_m_opt == -1)
339     return NULL;
340
341   char *out = print_partition_table (device, parted_has_m_opt);
342   if (!out)
343     return NULL;
344
345   if (parted_has_m_opt) {
346     /* New-style parsing using the "machine-readable" format from
347      * 'parted -m'.
348      */
349     char **lines = split_lines (out);
350     free (out);
351
352     if (!lines)
353       return NULL;
354
355     if (lines[0] == NULL || STRNEQ (lines[0], "BYT;")) {
356       reply_with_error ("unknown signature, expected \"BYT;\" as first line of the output: %s",
357                         lines[0] ? lines[0] : "(signature was null)");
358       free_strings (lines);
359       return NULL;
360     }
361
362     if (lines[1] == NULL) {
363       reply_with_error ("parted didn't return a line describing the device");
364       free_strings (lines);
365       return NULL;
366     }
367
368     /* lines[1] is something like:
369      * "/dev/sda:1953525168s:scsi:512:512:msdos:ATA Hitachi HDT72101;"
370      */
371     char *r = get_table_field (lines[1], 5);
372     if (r == NULL) {
373       free_strings (lines);
374       return NULL;
375     }
376
377     free_strings (lines);
378
379     /* If "loop" return an error (RHBZ#634246). */
380     if (STREQ (r, "loop")) {
381       free (r);
382       reply_with_error ("not a partitioned device");
383       return NULL;
384     }
385
386     return r;
387   }
388   else {
389     /* Old-style.  Look for "\nPartition Table: <str>\n". */
390     char *p = strstr (out, "\nPartition Table: ");
391     if (!p) {
392       reply_with_error ("parted didn't return Partition Table line");
393       free (out);
394       return NULL;
395     }
396
397     p += 18;
398     char *q = strchr (p, '\n');
399     if (!q) {
400       reply_with_error ("parted Partition Table has no end of line char");
401       free (out);
402       return NULL;
403     }
404
405     *q = '\0';
406
407     p = strdup (p);
408     free (out);
409     if (!p) {
410       reply_with_perror ("strdup");
411       return NULL;
412     }
413
414     /* If "loop" return an error (RHBZ#634246). */
415     if (STREQ (p, "loop")) {
416       free (p);
417       reply_with_error ("not a partitioned device");
418       return NULL;
419     }
420
421     return p;                   /* caller frees */
422   }
423 }
424
425 guestfs_int_partition_list *
426 do_part_list (const char *device)
427 {
428   int parted_has_m_opt = test_parted_m_opt ();
429   if (parted_has_m_opt == -1)
430     return NULL;
431
432   char *out = print_partition_table (device, parted_has_m_opt);
433   if (!out)
434     return NULL;
435
436   char **lines = split_lines (out);
437   free (out);
438
439   if (!lines)
440     return NULL;
441
442   guestfs_int_partition_list *r;
443
444   if (parted_has_m_opt) {
445     /* New-style parsing using the "machine-readable" format from
446      * 'parted -m'.
447      *
448      * lines[0] is "BYT;", lines[1] is the device line which we ignore,
449      * lines[2..] are the partitions themselves.  Count how many.
450      */
451     size_t nr_rows = 0, row;
452     for (row = 2; lines[row] != NULL; ++row)
453       ++nr_rows;
454
455     r = malloc (sizeof *r);
456     if (r == NULL) {
457       reply_with_perror ("malloc");
458       goto error1;
459     }
460     r->guestfs_int_partition_list_len = nr_rows;
461     r->guestfs_int_partition_list_val =
462       malloc (nr_rows * sizeof (guestfs_int_partition));
463     if (r->guestfs_int_partition_list_val == NULL) {
464       reply_with_perror ("malloc");
465       goto error2;
466     }
467
468     /* Now parse the lines. */
469     size_t i;
470     for (i = 0, row = 2; lines[row] != NULL; ++i, ++row) {
471       if (sscanf (lines[row], "%d:%" SCNi64 "B:%" SCNi64 "B:%" SCNi64 "B",
472                   &r->guestfs_int_partition_list_val[i].part_num,
473                   &r->guestfs_int_partition_list_val[i].part_start,
474                   &r->guestfs_int_partition_list_val[i].part_end,
475                   &r->guestfs_int_partition_list_val[i].part_size) != 4) {
476         reply_with_error ("could not parse row from output of parted print command: %s", lines[row]);
477         goto error3;
478       }
479     }
480   }
481   else {
482     /* Old-style.  Start at the line following "^Number", up to the
483      * next blank line.
484      */
485     size_t start = 0, end = 0, row;
486
487     for (row = 0; lines[row] != NULL; ++row)
488       if (STRPREFIX (lines[row], "Number")) {
489         start = row+1;
490         break;
491       }
492
493     if (start == 0) {
494       reply_with_error ("parted output has no \"Number\" line");
495       goto error1;
496     }
497
498     for (row = start; lines[row] != NULL; ++row)
499       if (STREQ (lines[row], "")) {
500         end = row;
501         break;
502       }
503
504     if (end == 0) {
505       reply_with_error ("parted output has no blank after end of table");
506       goto error1;
507     }
508
509     size_t nr_rows = end - start;
510
511     r = malloc (sizeof *r);
512     if (r == NULL) {
513       reply_with_perror ("malloc");
514       goto error1;
515     }
516     r->guestfs_int_partition_list_len = nr_rows;
517     r->guestfs_int_partition_list_val =
518       malloc (nr_rows * sizeof (guestfs_int_partition));
519     if (r->guestfs_int_partition_list_val == NULL) {
520       reply_with_perror ("malloc");
521       goto error2;
522     }
523
524     /* Now parse the lines. */
525     size_t i;
526     for (i = 0, row = start; row < end; ++i, ++row) {
527       if (sscanf (lines[row], " %d %" SCNi64 "B %" SCNi64 "B %" SCNi64 "B",
528                   &r->guestfs_int_partition_list_val[i].part_num,
529                   &r->guestfs_int_partition_list_val[i].part_start,
530                   &r->guestfs_int_partition_list_val[i].part_end,
531                   &r->guestfs_int_partition_list_val[i].part_size) != 4) {
532         reply_with_error ("could not parse row from output of parted print command: %s", lines[row]);
533         goto error3;
534       }
535     }
536   }
537
538   free_strings (lines);
539   return r;
540
541  error3:
542   free (r->guestfs_int_partition_list_val);
543  error2:
544   free (r);
545  error1:
546   free_strings (lines);
547   return NULL;
548 }
549
550 int
551 do_part_get_bootable (const char *device, int partnum)
552 {
553   if (partnum <= 0) {
554     reply_with_error ("partition number must be >= 1");
555     return -1;
556   }
557
558   int parted_has_m_opt = test_parted_m_opt ();
559   if (parted_has_m_opt == -1)
560     return -1;
561
562   char *out = print_partition_table (device, parted_has_m_opt);
563   if (!out)
564     return -1;
565
566   char **lines = split_lines (out);
567   free (out);
568
569   if (!lines)
570     return -1;
571
572   if (parted_has_m_opt) {
573     /* New-style parsing using the "machine-readable" format from
574      * 'parted -m'.
575      *
576      * We want lines[1+partnum].
577      */
578     if (count_strings (lines) < (size_t) 1+partnum) {
579       reply_with_error ("partition number out of range: %d", partnum);
580       free_strings (lines);
581       return -1;
582     }
583
584     char *boot = get_table_field (lines[1+partnum], 6);
585     if (boot == NULL) {
586       free_strings (lines);
587       return -1;
588     }
589
590     int r = STREQ (boot, "boot");
591
592     free (boot);
593     free_strings (lines);
594
595     return r;
596   }
597   else {
598     /* Old-style: First look for the line matching "^Number". */
599     size_t start = 0, header, row;
600
601     for (row = 0; lines[row] != NULL; ++row)
602       if (STRPREFIX (lines[row], "Number")) {
603         start = row+1;
604         header = row;
605         break;
606       }
607
608     if (start == 0) {
609       reply_with_error ("parted output has no \"Number\" line");
610       free_strings (lines);
611       return -1;
612     }
613
614     /* Now we have to look at the column number of the "Flags" field.
615      * This is because parted's output has no way to represent a
616      * missing field except as whitespace, so we cannot just count
617      * fields from the left.  eg. The "File system" field is often
618      * missing in the output.
619      */
620     char *p = strstr (lines[header], "Flags");
621     if (!p) {
622       reply_with_error ("parted output has no \"Flags\" field");
623       free_strings (lines);
624       return -1;
625     }
626     size_t col = p - lines[header];
627
628     /* Look for the line corresponding to this partition number. */
629     row = start + partnum - 1;
630     if (row >= count_strings (lines) || !STRPREFIX (lines[row], " ")) {
631       reply_with_error ("partition number out of range: %d", partnum);
632       free_strings (lines);
633       return -1;
634     }
635
636     int r = STRPREFIX (&lines[row][col], "boot");
637     free_strings (lines);
638     return r;
639   }
640 }
641
642 /* Currently we use sfdisk for getting and setting the ID byte.  In
643  * future, extend parted to provide this functionality.  As a result
644  * of using sfdisk, this won't work for non-MBR-style partitions, but
645  * that limitation is noted in the documentation and we can extend it
646  * later without breaking the ABI.
647  */
648 int
649 do_part_get_mbr_id (const char *device, int partnum)
650 {
651   if (partnum <= 0) {
652     reply_with_error ("partition number must be >= 1");
653     return -1;
654   }
655
656   char partnum_str[16];
657   snprintf (partnum_str, sizeof partnum_str, "%d", partnum);
658
659   char *out, *err;
660   int r;
661
662   r = command (&out, &err, "sfdisk", "--print-id", device, partnum_str, NULL);
663   if (r == -1) {
664     reply_with_error ("sfdisk --print-id: %s", err);
665     free (out);
666     free (err);
667     return -1;
668   }
669
670   free (err);
671
672   /* It's printed in hex ... */
673   int id;
674   if (sscanf (out, "%x", &id) != 1) {
675     reply_with_error ("sfdisk --print-id: cannot parse output: %s", out);
676     free (out);
677     return -1;
678   }
679
680   free (out);
681   return id;
682 }
683
684 int
685 do_part_set_mbr_id (const char *device, int partnum, int idbyte)
686 {
687   if (partnum <= 0) {
688     reply_with_error ("partition number must be >= 1");
689     return -1;
690   }
691
692   char partnum_str[16];
693   snprintf (partnum_str, sizeof partnum_str, "%d", partnum);
694
695   char idbyte_str[16];
696   snprintf (idbyte_str, sizeof partnum_str, "%x", idbyte); /* NB: hex */
697
698   char *err;
699   int r;
700
701   r = command (NULL, &err, "sfdisk",
702                "--change-id", device, partnum_str, idbyte_str, NULL);
703   if (r == -1) {
704     reply_with_error ("sfdisk --change-id: %s", err);
705     free (err);
706     return -1;
707   }
708
709   free (err);
710   return 0;
711 }