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