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