fe68d1d982d0573c0ec051612214ef93e431ae40
[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   char partnum_str[16];
165   snprintf (partnum_str, sizeof partnum_str, "%d", partnum);
166
167   RUN_PARTED (return -1, device, "rm", partnum_str, NULL);
168
169   udev_settle ();
170   return 0;
171 }
172
173 int
174 do_part_disk (const char *device, const char *parttype)
175 {
176   const char *startstr;
177   const char *endstr;
178
179   parttype = check_parttype (parttype);
180   if (!parttype) {
181     reply_with_error ("unknown partition type: common choices are \"gpt\" and \"msdos\"");
182     return -1;
183   }
184
185   /* Voooooodooooooooo (thanks Jim Meyering for working this out). */
186   if (STREQ (parttype, "msdos")) {
187     startstr = "1s";
188     endstr = "-1s";
189   } else if (STREQ (parttype, "gpt")) {
190     startstr = "34s";
191     endstr = "-34s";
192   } else {
193     /* untested */
194     startstr = "1s";
195     endstr = "-1s";
196   }
197
198   RUN_PARTED (return -1,
199               device,
200               "mklabel", parttype,
201               /* See comment about about the parted mkpart command. */
202               "mkpart", STREQ (parttype, "gpt") ? "p1" : "primary",
203               startstr, endstr, NULL);
204
205   udev_settle ();
206
207   return 0;
208 }
209
210 int
211 do_part_set_bootable (const char *device, int partnum, int bootable)
212 {
213   char partstr[16];
214
215   snprintf (partstr, sizeof partstr, "%d", partnum);
216
217   RUN_PARTED (return -1,
218               device, "set", partstr, "boot", bootable ? "on" : "off", NULL);
219
220   udev_settle ();
221
222   return 0;
223 }
224
225 int
226 do_part_set_name (const char *device, int partnum, const char *name)
227 {
228   char partstr[16];
229
230   snprintf (partstr, sizeof partstr, "%d", partnum);
231
232   RUN_PARTED (return -1, device, "name", partstr, name, NULL);
233
234   udev_settle ();
235
236   return 0;
237 }
238
239 /* Return the nth field from a string of ':'/';'-delimited strings.
240  * Useful for parsing the return value from 'parted -m'.
241  */
242 static char *
243 get_table_field (const char *line, int n)
244 {
245   const char *p = line;
246
247   while (*p && n > 0) {
248     p += strcspn (p, ":;") + 1;
249     n--;
250   }
251
252   if (n > 0) {
253     reply_with_error ("not enough fields in output of parted print command: %s",
254                       line);
255     return NULL;
256   }
257
258   size_t len = strcspn (p, ":;");
259   char *q = strndup (p, len);
260   if (q == NULL) {
261     reply_with_perror ("strndup");
262     return NULL;
263   }
264
265   return q;
266 }
267
268 /* RHEL 5 parted doesn't have the -m (machine readable) option so we
269  * must do a lot more work to parse the output in
270  * print_partition_table below.  Test for this option the first time
271  * this function is called.
272  */
273 static int
274 test_parted_m_opt (void)
275 {
276   static int result = -1;
277
278   if (result >= 0)
279     return result;
280
281   if (verbose)
282     fprintf (stderr, "Testing if this parted supports '-m' option.\n");
283
284   char *err = NULL;
285   int r = commandr (NULL, &err, "parted", "-s", "-m", "/dev/null", NULL);
286   if (r == -1) {
287     /* Test failed, eg. missing or completely unusable parted binary. */
288     reply_with_error ("could not run 'parted' command");
289     return -1;
290   }
291
292   if (err && strstr (err, "invalid option -- m"))
293     return result = 0;
294
295   return result = 1;
296 }
297
298 static char *
299 print_partition_table (const char *device, int parted_has_m_opt)
300 {
301   char *out, *err;
302   int r;
303
304   if (parted_has_m_opt)
305     r = command (&out, &err, "parted", "-m", "--", device,
306                  "unit", "b",
307                  "print", NULL);
308   else
309     r = command (&out, &err, "parted", "-s", "--", device,
310                  "unit", "b",
311                  "print", NULL);
312   if (r == -1) {
313     reply_with_error ("parted print: %s: %s", device,
314                       /* Hack for parted 1.x which sends errors to stdout. */
315                       *err ? err : out);
316     free (out);
317     free (err);
318     return NULL;
319   }
320   free (err);
321
322   if (verbose)
323     fprintf (stderr, "parted output:\n%s<END>\n", out);
324
325   return out;
326 }
327
328 char *
329 do_part_get_parttype (const char *device)
330 {
331   int parted_has_m_opt = test_parted_m_opt ();
332   if (parted_has_m_opt == -1)
333     return NULL;
334
335   char *out = print_partition_table (device, parted_has_m_opt);
336   if (!out)
337     return NULL;
338
339   if (parted_has_m_opt) {
340     /* New-style parsing using the "machine-readable" format from
341      * 'parted -m'.
342      */
343     char **lines = split_lines (out);
344     free (out);
345
346     if (!lines)
347       return NULL;
348
349     if (lines[0] == NULL || STRNEQ (lines[0], "BYT;")) {
350       reply_with_error ("unknown signature, expected \"BYT;\" as first line of the output: %s",
351                         lines[0] ? lines[0] : "(signature was null)");
352       free_strings (lines);
353       return NULL;
354     }
355
356     if (lines[1] == NULL) {
357       reply_with_error ("parted didn't return a line describing the device");
358       free_strings (lines);
359       return NULL;
360     }
361
362     /* lines[1] is something like:
363      * "/dev/sda:1953525168s:scsi:512:512:msdos:ATA Hitachi HDT72101;"
364      */
365     char *r = get_table_field (lines[1], 5);
366     if (r == NULL) {
367       free_strings (lines);
368       return NULL;
369     }
370
371     free_strings (lines);
372     return r;
373   }
374   else {
375     /* Old-style.  Look for "\nPartition Table: <str>\n". */
376     char *p = strstr (out, "\nPartition Table: ");
377     if (!p) {
378       reply_with_error ("parted didn't return Partition Table line");
379       free (out);
380       return NULL;
381     }
382
383     p += 18;
384     char *q = strchr (p, '\n');
385     if (!q) {
386       reply_with_error ("parted Partition Table has no end of line char");
387       free (out);
388       return NULL;
389     }
390
391     *q = '\0';
392
393     p = strdup (p);
394     free (out);
395     if (!p) {
396       reply_with_perror ("strdup");
397       return NULL;
398     }
399
400     return p;                   /* caller frees */
401   }
402 }
403
404 guestfs_int_partition_list *
405 do_part_list (const char *device)
406 {
407   int parted_has_m_opt = test_parted_m_opt ();
408   if (parted_has_m_opt == -1)
409     return NULL;
410
411   char *out = print_partition_table (device, parted_has_m_opt);
412   if (!out)
413     return NULL;
414
415   char **lines = split_lines (out);
416   free (out);
417
418   if (!lines)
419     return NULL;
420
421   guestfs_int_partition_list *r;
422
423   if (parted_has_m_opt) {
424     /* New-style parsing using the "machine-readable" format from
425      * 'parted -m'.
426      *
427      * lines[0] is "BYT;", lines[1] is the device line which we ignore,
428      * lines[2..] are the partitions themselves.  Count how many.
429      */
430     size_t nr_rows = 0, row;
431     for (row = 2; lines[row] != NULL; ++row)
432       ++nr_rows;
433
434     r = malloc (sizeof *r);
435     if (r == NULL) {
436       reply_with_perror ("malloc");
437       goto error1;
438     }
439     r->guestfs_int_partition_list_len = nr_rows;
440     r->guestfs_int_partition_list_val =
441       malloc (nr_rows * sizeof (guestfs_int_partition));
442     if (r->guestfs_int_partition_list_val == NULL) {
443       reply_with_perror ("malloc");
444       goto error2;
445     }
446
447     /* Now parse the lines. */
448     size_t i;
449     for (i = 0, row = 2; lines[row] != NULL; ++i, ++row) {
450       if (sscanf (lines[row], "%d:%" SCNi64 "B:%" SCNi64 "B:%" SCNi64 "B",
451                   &r->guestfs_int_partition_list_val[i].part_num,
452                   &r->guestfs_int_partition_list_val[i].part_start,
453                   &r->guestfs_int_partition_list_val[i].part_end,
454                   &r->guestfs_int_partition_list_val[i].part_size) != 4) {
455         reply_with_error ("could not parse row from output of parted print command: %s", lines[row]);
456         goto error3;
457       }
458     }
459   }
460   else {
461     /* Old-style.  Start at the line following "^Number", up to the
462      * next blank line.
463      */
464     size_t start = 0, end = 0, row;
465
466     for (row = 0; lines[row] != NULL; ++row)
467       if (STRPREFIX (lines[row], "Number")) {
468         start = row+1;
469         break;
470       }
471
472     if (start == 0) {
473       reply_with_error ("parted output has no \"Number\" line");
474       goto error1;
475     }
476
477     for (row = start; lines[row] != NULL; ++row)
478       if (STREQ (lines[row], "")) {
479         end = row;
480         break;
481       }
482
483     if (end == 0) {
484       reply_with_error ("parted output has no blank after end of table");
485       goto error1;
486     }
487
488     size_t nr_rows = end - start;
489
490     r = malloc (sizeof *r);
491     if (r == NULL) {
492       reply_with_perror ("malloc");
493       goto error1;
494     }
495     r->guestfs_int_partition_list_len = nr_rows;
496     r->guestfs_int_partition_list_val =
497       malloc (nr_rows * sizeof (guestfs_int_partition));
498     if (r->guestfs_int_partition_list_val == NULL) {
499       reply_with_perror ("malloc");
500       goto error2;
501     }
502
503     /* Now parse the lines. */
504     size_t i;
505     for (i = 0, row = start; row < end; ++i, ++row) {
506       if (sscanf (lines[row], " %d %" SCNi64 "B %" SCNi64 "B %" SCNi64 "B",
507                   &r->guestfs_int_partition_list_val[i].part_num,
508                   &r->guestfs_int_partition_list_val[i].part_start,
509                   &r->guestfs_int_partition_list_val[i].part_end,
510                   &r->guestfs_int_partition_list_val[i].part_size) != 4) {
511         reply_with_error ("could not parse row from output of parted print command: %s", lines[row]);
512         goto error3;
513       }
514     }
515   }
516
517   free_strings (lines);
518   return r;
519
520  error3:
521   free (r->guestfs_int_partition_list_val);
522  error2:
523   free (r);
524  error1:
525   free_strings (lines);
526   return NULL;
527 }
528
529 int
530 do_part_get_bootable (const char *device, int partnum)
531 {
532   int parted_has_m_opt = test_parted_m_opt ();
533   if (parted_has_m_opt == -1)
534     return -1;
535
536   char *out = print_partition_table (device, parted_has_m_opt);
537   if (!out)
538     return -1;
539
540   char **lines = split_lines (out);
541   free (out);
542
543   if (!lines)
544     return -1;
545
546   if (parted_has_m_opt) {
547     /* New-style parsing using the "machine-readable" format from
548      * 'parted -m'.
549      *
550      * We want lines[1+partnum].
551      */
552     if (count_strings (lines) < (size_t) 1+partnum) {
553       reply_with_error ("partition number out of range: %d", partnum);
554       free_strings (lines);
555       return -1;
556     }
557
558     char *boot = get_table_field (lines[1+partnum], 6);
559     if (boot == NULL) {
560       free_strings (lines);
561       return -1;
562     }
563
564     int r = STREQ (boot, "boot");
565
566     free (boot);
567     free_strings (lines);
568
569     return r;
570   }
571   else {
572     /* Old-style: First look for the line matching "^Number". */
573     size_t start = 0, header, row;
574
575     for (row = 0; lines[row] != NULL; ++row)
576       if (STRPREFIX (lines[row], "Number")) {
577         start = row+1;
578         header = row;
579         break;
580       }
581
582     if (start == 0) {
583       reply_with_error ("parted output has no \"Number\" line");
584       free_strings (lines);
585       return -1;
586     }
587
588     /* Now we have to look at the column number of the "Flags" field.
589      * This is because parted's output has no way to represent a
590      * missing field except as whitespace, so we cannot just count
591      * fields from the left.  eg. The "File system" field is often
592      * missing in the output.
593      */
594     char *p = strstr (lines[header], "Flags");
595     if (!p) {
596       reply_with_error ("parted output has no \"Flags\" field");
597       free_strings (lines);
598       return -1;
599     }
600     size_t col = p - lines[header];
601
602     /* Look for the line corresponding to this partition number. */
603     row = start + partnum - 1;
604     if (row >= count_strings (lines) || !STRPREFIX (lines[row], " ")) {
605       reply_with_error ("partition number out of range: %d", partnum);
606       free_strings (lines);
607       return -1;
608     }
609
610     int r = STRPREFIX (&lines[row][col], "boot");
611     free_strings (lines);
612     return r;
613   }
614 }
615
616 /* Currently we use sfdisk for getting and setting the ID byte.  In
617  * future, extend parted to provide this functionality.  As a result
618  * of using sfdisk, this won't work for non-MBR-style partitions, but
619  * that limitation is noted in the documentation and we can extend it
620  * later without breaking the ABI.
621  */
622 int
623 do_part_get_mbr_id (const char *device, int partnum)
624 {
625   char partnum_str[16];
626   snprintf (partnum_str, sizeof partnum_str, "%d", partnum);
627
628   char *out, *err;
629   int r;
630
631   r = command (&out, &err, "sfdisk", "--print-id", device, partnum_str, NULL);
632   if (r == -1) {
633     reply_with_error ("sfdisk --print-id: %s", err);
634     free (out);
635     free (err);
636     return -1;
637   }
638
639   free (err);
640
641   /* It's printed in hex ... */
642   int id;
643   if (sscanf (out, "%x", &id) != 1) {
644     reply_with_error ("sfdisk --print-id: cannot parse output: %s", out);
645     free (out);
646     return -1;
647   }
648
649   free (out);
650   return id;
651 }
652
653 int
654 do_part_set_mbr_id (const char *device, int partnum, int idbyte)
655 {
656   char partnum_str[16];
657   snprintf (partnum_str, sizeof partnum_str, "%d", partnum);
658
659   char idbyte_str[16];
660   snprintf (idbyte_str, sizeof partnum_str, "%x", idbyte); /* NB: hex */
661
662   char *err;
663   int r;
664
665   r = command (NULL, &err, "sfdisk",
666                "--change-id", device, partnum_str, idbyte_str, NULL);
667   if (r == -1) {
668     reply_with_error ("sfdisk --change-id: %s", err);
669     free (err);
670     return -1;
671   }
672
673   free (err);
674   return 0;
675 }