Update to latest gnulib for stable-1.8 branch.
[libguestfs.git] / daemon / parted.c
1 /* libguestfs - the guestfsd daemon
2  * Copyright (C) 2009 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   if (verbose)
291     fprintf (stderr, "Testing if this parted supports '-m' option.\n");
292
293   char *err = NULL;
294   int r = commandr (NULL, &err, "parted", "-s", "-m", "/dev/null", NULL);
295   if (r == -1) {
296     /* Test failed, eg. missing or completely unusable parted binary. */
297     reply_with_error ("could not run 'parted' command");
298     free (err);
299     return -1;
300   }
301
302   if (err && strstr (err, "invalid option -- m"))
303     result = 0;
304   else
305     result = 1;
306   free (err);
307   return result;
308 }
309
310 static char *
311 print_partition_table (const char *device, int parted_has_m_opt)
312 {
313   char *out, *err;
314   int r;
315
316   if (parted_has_m_opt)
317     r = command (&out, &err, "parted", "-m", "--", device,
318                  "unit", "b",
319                  "print", NULL);
320   else
321     r = command (&out, &err, "parted", "-s", "--", device,
322                  "unit", "b",
323                  "print", NULL);
324   if (r == -1) {
325     reply_with_error ("parted print: %s: %s", device,
326                       /* Hack for parted 1.x which sends errors to stdout. */
327                       *err ? err : out);
328     free (out);
329     free (err);
330     return NULL;
331   }
332   free (err);
333
334   if (verbose)
335     fprintf (stderr, "parted output:\n%s<END>\n", out);
336
337   return out;
338 }
339
340 char *
341 do_part_get_parttype (const char *device)
342 {
343   int parted_has_m_opt = test_parted_m_opt ();
344   if (parted_has_m_opt == -1)
345     return NULL;
346
347   char *out = print_partition_table (device, parted_has_m_opt);
348   if (!out)
349     return NULL;
350
351   if (parted_has_m_opt) {
352     /* New-style parsing using the "machine-readable" format from
353      * 'parted -m'.
354      */
355     char **lines = split_lines (out);
356     free (out);
357
358     if (!lines)
359       return NULL;
360
361     if (lines[0] == NULL || STRNEQ (lines[0], "BYT;")) {
362       reply_with_error ("unknown signature, expected \"BYT;\" as first line of the output: %s",
363                         lines[0] ? lines[0] : "(signature was null)");
364       free_strings (lines);
365       return NULL;
366     }
367
368     if (lines[1] == NULL) {
369       reply_with_error ("parted didn't return a line describing the device");
370       free_strings (lines);
371       return NULL;
372     }
373
374     /* lines[1] is something like:
375      * "/dev/sda:1953525168s:scsi:512:512:msdos:ATA Hitachi HDT72101;"
376      */
377     char *r = get_table_field (lines[1], 5);
378     if (r == NULL) {
379       free_strings (lines);
380       return NULL;
381     }
382
383     free_strings (lines);
384
385     /* If "loop" return an error (RHBZ#634246). */
386     if (STREQ (r, "loop")) {
387       free (r);
388       reply_with_error ("not a partitioned device");
389       return NULL;
390     }
391
392     return r;
393   }
394   else {
395     /* Old-style.  Look for "\nPartition Table: <str>\n". */
396     char *p = strstr (out, "\nPartition Table: ");
397     if (!p) {
398       reply_with_error ("parted didn't return Partition Table line");
399       free (out);
400       return NULL;
401     }
402
403     p += 18;
404     char *q = strchr (p, '\n');
405     if (!q) {
406       reply_with_error ("parted Partition Table has no end of line char");
407       free (out);
408       return NULL;
409     }
410
411     *q = '\0';
412
413     p = strdup (p);
414     free (out);
415     if (!p) {
416       reply_with_perror ("strdup");
417       return NULL;
418     }
419
420     /* If "loop" return an error (RHBZ#634246). */
421     if (STREQ (p, "loop")) {
422       free (p);
423       reply_with_error ("not a partitioned device");
424       return NULL;
425     }
426
427     return p;                   /* caller frees */
428   }
429 }
430
431 guestfs_int_partition_list *
432 do_part_list (const char *device)
433 {
434   int parted_has_m_opt = test_parted_m_opt ();
435   if (parted_has_m_opt == -1)
436     return NULL;
437
438   char *out = print_partition_table (device, parted_has_m_opt);
439   if (!out)
440     return NULL;
441
442   char **lines = split_lines (out);
443   free (out);
444
445   if (!lines)
446     return NULL;
447
448   guestfs_int_partition_list *r;
449
450   if (parted_has_m_opt) {
451     /* New-style parsing using the "machine-readable" format from
452      * 'parted -m'.
453      *
454      * lines[0] is "BYT;", lines[1] is the device line which we ignore,
455      * lines[2..] are the partitions themselves.  Count how many.
456      */
457     size_t nr_rows = 0, row;
458     for (row = 2; lines[row] != NULL; ++row)
459       ++nr_rows;
460
461     r = malloc (sizeof *r);
462     if (r == NULL) {
463       reply_with_perror ("malloc");
464       goto error1;
465     }
466     r->guestfs_int_partition_list_len = nr_rows;
467     r->guestfs_int_partition_list_val =
468       malloc (nr_rows * sizeof (guestfs_int_partition));
469     if (r->guestfs_int_partition_list_val == NULL) {
470       reply_with_perror ("malloc");
471       goto error2;
472     }
473
474     /* Now parse the lines. */
475     size_t i;
476     for (i = 0, row = 2; lines[row] != NULL; ++i, ++row) {
477       if (sscanf (lines[row], "%d:%" SCNi64 "B:%" SCNi64 "B:%" SCNi64 "B",
478                   &r->guestfs_int_partition_list_val[i].part_num,
479                   &r->guestfs_int_partition_list_val[i].part_start,
480                   &r->guestfs_int_partition_list_val[i].part_end,
481                   &r->guestfs_int_partition_list_val[i].part_size) != 4) {
482         reply_with_error ("could not parse row from output of parted print command: %s", lines[row]);
483         goto error3;
484       }
485     }
486   }
487   else {
488     /* Old-style.  Start at the line following "^Number", up to the
489      * next blank line.
490      */
491     size_t start = 0, end = 0, row;
492
493     for (row = 0; lines[row] != NULL; ++row)
494       if (STRPREFIX (lines[row], "Number")) {
495         start = row+1;
496         break;
497       }
498
499     if (start == 0) {
500       reply_with_error ("parted output has no \"Number\" line");
501       goto error1;
502     }
503
504     for (row = start; lines[row] != NULL; ++row)
505       if (STREQ (lines[row], "")) {
506         end = row;
507         break;
508       }
509
510     if (end == 0) {
511       reply_with_error ("parted output has no blank after end of table");
512       goto error1;
513     }
514
515     size_t nr_rows = end - start;
516
517     r = malloc (sizeof *r);
518     if (r == NULL) {
519       reply_with_perror ("malloc");
520       goto error1;
521     }
522     r->guestfs_int_partition_list_len = nr_rows;
523     r->guestfs_int_partition_list_val =
524       malloc (nr_rows * sizeof (guestfs_int_partition));
525     if (r->guestfs_int_partition_list_val == NULL) {
526       reply_with_perror ("malloc");
527       goto error2;
528     }
529
530     /* Now parse the lines. */
531     size_t i;
532     for (i = 0, row = start; row < end; ++i, ++row) {
533       if (sscanf (lines[row], " %d %" SCNi64 "B %" SCNi64 "B %" SCNi64 "B",
534                   &r->guestfs_int_partition_list_val[i].part_num,
535                   &r->guestfs_int_partition_list_val[i].part_start,
536                   &r->guestfs_int_partition_list_val[i].part_end,
537                   &r->guestfs_int_partition_list_val[i].part_size) != 4) {
538         reply_with_error ("could not parse row from output of parted print command: %s", lines[row]);
539         goto error3;
540       }
541     }
542   }
543
544   free_strings (lines);
545   return r;
546
547  error3:
548   free (r->guestfs_int_partition_list_val);
549  error2:
550   free (r);
551  error1:
552   free_strings (lines);
553   return NULL;
554 }
555
556 int
557 do_part_get_bootable (const char *device, int partnum)
558 {
559   if (partnum <= 0) {
560     reply_with_error ("partition number must be >= 1");
561     return -1;
562   }
563
564   int parted_has_m_opt = test_parted_m_opt ();
565   if (parted_has_m_opt == -1)
566     return -1;
567
568   char *out = print_partition_table (device, parted_has_m_opt);
569   if (!out)
570     return -1;
571
572   char **lines = split_lines (out);
573   free (out);
574
575   if (!lines)
576     return -1;
577
578   if (parted_has_m_opt) {
579     /* New-style parsing using the "machine-readable" format from
580      * 'parted -m'.
581      *
582      * Partitions may not be in any order, so we have to look for
583      * the matching partition number (RHBZ#602997).
584      */
585     if (lines[0] == NULL || STRNEQ (lines[0], "BYT;")) {
586       reply_with_error ("unknown signature, expected \"BYT;\" as first line of the output: %s",
587                         lines[0] ? lines[0] : "(signature was null)");
588       free_strings (lines);
589       return -1;
590     }
591
592     if (lines[1] == NULL) {
593       reply_with_error ("parted didn't return a line describing the device");
594       free_strings (lines);
595       return -1;
596     }
597
598     size_t row;
599     int pnum;
600     for (row = 2; lines[row] != NULL; ++row) {
601       if (sscanf (lines[row], "%d:", &pnum) != 1) {
602         reply_with_error ("could not parse row from output of parted print command: %s", lines[row]);
603         free_strings (lines);
604         return -1;
605       }
606       if (pnum == partnum)
607         break;
608     }
609
610     if (lines[row] == NULL) {
611       reply_with_error ("partition number %d not found", partnum);
612       free_strings (lines);
613       return -1;
614     }
615
616     char *boot = get_table_field (lines[row], 6);
617     if (boot == NULL) {
618       free_strings (lines);
619       return -1;
620     }
621
622     int r = STREQ (boot, "boot");
623
624     free (boot);
625     free_strings (lines);
626
627     return r;
628   }
629   else {
630     /* Old-style: First look for the line matching "^Number". */
631     size_t start = 0, header, row;
632
633     for (row = 0; lines[row] != NULL; ++row)
634       if (STRPREFIX (lines[row], "Number")) {
635         start = row+1;
636         header = row;
637         break;
638       }
639
640     if (start == 0) {
641       reply_with_error ("parted output has no \"Number\" line");
642       free_strings (lines);
643       return -1;
644     }
645
646     /* Now we have to look at the column number of the "Flags" field.
647      * This is because parted's output has no way to represent a
648      * missing field except as whitespace, so we cannot just count
649      * fields from the left.  eg. The "File system" field is often
650      * missing in the output.
651      */
652     char *p = strstr (lines[header], "Flags");
653     if (!p) {
654       reply_with_error ("parted output has no \"Flags\" field");
655       free_strings (lines);
656       return -1;
657     }
658     size_t col = p - lines[header];
659
660     /* Look for the line corresponding to this partition number. */
661     row = start + partnum - 1;
662     if (row >= count_strings (lines) || !STRPREFIX (lines[row], " ")) {
663       reply_with_error ("partition number out of range: %d", partnum);
664       free_strings (lines);
665       return -1;
666     }
667
668     int r = STRPREFIX (&lines[row][col], "boot");
669     free_strings (lines);
670     return r;
671   }
672 }
673
674 /* Currently we use sfdisk for getting and setting the ID byte.  In
675  * future, extend parted to provide this functionality.  As a result
676  * of using sfdisk, this won't work for non-MBR-style partitions, but
677  * that limitation is noted in the documentation and we can extend it
678  * later without breaking the ABI.
679  */
680 int
681 do_part_get_mbr_id (const char *device, int partnum)
682 {
683   if (partnum <= 0) {
684     reply_with_error ("partition number must be >= 1");
685     return -1;
686   }
687
688   char partnum_str[16];
689   snprintf (partnum_str, sizeof partnum_str, "%d", partnum);
690
691   char *out, *err;
692   int r;
693
694   r = command (&out, &err, "sfdisk", "--print-id", device, partnum_str, NULL);
695   if (r == -1) {
696     reply_with_error ("sfdisk --print-id: %s", err);
697     free (out);
698     free (err);
699     return -1;
700   }
701
702   free (err);
703
704   /* It's printed in hex ... */
705   int id;
706   if (sscanf (out, "%x", &id) != 1) {
707     reply_with_error ("sfdisk --print-id: cannot parse output: %s", out);
708     free (out);
709     return -1;
710   }
711
712   free (out);
713   return id;
714 }
715
716 int
717 do_part_set_mbr_id (const char *device, int partnum, int idbyte)
718 {
719   if (partnum <= 0) {
720     reply_with_error ("partition number must be >= 1");
721     return -1;
722   }
723
724   char partnum_str[16];
725   snprintf (partnum_str, sizeof partnum_str, "%d", partnum);
726
727   char idbyte_str[16];
728   snprintf (idbyte_str, sizeof partnum_str, "%x", idbyte); /* NB: hex */
729
730   char *err;
731   int r;
732
733   r = command (NULL, &err, "sfdisk",
734                "--change-id", device, partnum_str, idbyte_str, NULL);
735   if (r == -1) {
736     reply_with_error ("sfdisk --change-id: %s", err);
737     free (err);
738     return -1;
739   }
740
741   free (err);
742   return 0;
743 }