]> git.ipfire.org Git - thirdparty/util-linux.git/blob - disk-utils/fdisk.c
Use --help suggestion on invalid option
[thirdparty/util-linux.git] / disk-utils / fdisk.c
1 /*
2 * Copyright (C) 1992 A. V. Le Blanc (LeBlanc@mcc.ac.uk)
3 * Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
4 *
5 * Copyright (C) 2007-2013 Karel Zak <kzak@redhat.com>
6 *
7 * This program is free software. You can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation: either version 1 or
10 * (at your option) any later version.
11 */
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <fcntl.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <getopt.h>
20 #include <sys/stat.h>
21 #include <sys/time.h>
22 #include <time.h>
23 #include <limits.h>
24 #include <libsmartcols.h>
25 #ifdef HAVE_LIBREADLINE
26 # include <readline/readline.h>
27 #endif
28
29 #include "c.h"
30 #include "xalloc.h"
31 #include "all-io.h"
32 #include "nls.h"
33 #include "rpmatch.h"
34 #include "blkdev.h"
35 #include "mbsalign.h"
36 #include "pathnames.h"
37 #include "canonicalize.h"
38 #include "strutils.h"
39 #include "closestream.h"
40 #include "pager.h"
41
42 #include "fdisk.h"
43
44 #include "pt-sun.h" /* to toggle flags */
45
46 #ifdef HAVE_LINUX_COMPILER_H
47 # include <linux/compiler.h>
48 #endif
49 #ifdef HAVE_LINUX_BLKPG_H
50 # include <linux/blkpg.h>
51 #endif
52
53 int pwipemode = WIPEMODE_AUTO;
54
55 /*
56 * fdisk debug stuff (see fdisk.h and include/debug.h)
57 */
58 UL_DEBUG_DEFINE_MASK(fdisk);
59 UL_DEBUG_DEFINE_MASKNAMES(fdisk) = UL_DEBUG_EMPTY_MASKNAMES;
60
61 static void fdiskprog_init_debug(void)
62 {
63 __UL_INIT_DEBUG(fdisk, FDISKPROG_DEBUG_, 0, FDISK_DEBUG);
64 }
65
66 #ifdef HAVE_LIBREADLINE
67 static char *rl_fgets(char *s, int n, FILE *stream, const char *prompt)
68 {
69 char *p;
70
71 rl_outstream = stream;
72 p = readline(prompt);
73 if (!p)
74 return NULL;
75
76 strncpy(s, p, n);
77 s[n - 1] = '\0';
78 free(p);
79 return s;
80 }
81 #endif
82
83 int get_user_reply(struct fdisk_context *cxt, const char *prompt,
84 char *buf, size_t bufsz)
85 {
86 char *p;
87 size_t sz;
88
89 do {
90 #ifdef HAVE_LIBREADLINE
91 if (isatty(STDIN_FILENO)) {
92 if (!rl_fgets(buf, bufsz, stdout, prompt)) {
93 if (fdisk_label_is_changed(fdisk_get_label(cxt, NULL))) {
94 if (rl_fgets(buf, bufsz, stderr,
95 _("\nDo you really want to quit? "))
96 && !rpmatch(buf))
97 continue;
98 }
99 fdisk_unref_context(cxt);
100 exit(EXIT_FAILURE);
101 } else
102 break;
103 }
104 else
105 #endif
106 {
107 fputs(prompt, stdout);
108 fflush(stdout);
109 if (!fgets(buf, bufsz, stdin)) {
110 if (fdisk_label_is_changed(fdisk_get_label(cxt, NULL))) {
111 fprintf(stderr, _("\nDo you really want to quit? "));
112
113 if (fgets(buf, bufsz, stdin) && !rpmatch(buf))
114 continue;
115 }
116 fdisk_unref_context(cxt);
117 exit(EXIT_FAILURE);
118 } else
119 break;
120 }
121 } while (1);
122
123 for (p = buf; *p && !isgraph(*p); p++); /* get first non-blank */
124
125 if (p > buf)
126 memmove(buf, p, p - buf); /* remove blank space */
127 sz = strlen(buf);
128 if (sz && *(buf + sz - 1) == '\n')
129 *(buf + sz - 1) = '\0';
130
131 DBG(ASK, ul_debug("user's reply: >>>%s<<<", buf));
132 return 0;
133 }
134
135 static int ask_menu(struct fdisk_context *cxt, struct fdisk_ask *ask,
136 char *buf, size_t bufsz)
137
138 {
139 const char *q = fdisk_ask_get_query(ask);
140 int dft = fdisk_ask_menu_get_default(ask);
141
142 if (q) {
143 fputs(q, stdout); /* print header */
144 fputc('\n', stdout);
145 }
146
147 do {
148 char prompt[128];
149 int key, c, rc;
150 const char *name, *desc;
151 size_t i = 0;
152
153 /* print menu items */
154 while (fdisk_ask_menu_get_item(ask, i++, &key, &name, &desc) == 0)
155 fprintf(stdout, " %c %s (%s)\n", key, name, desc);
156
157 /* ask for key */
158 snprintf(prompt, sizeof(prompt), _("Select (default %c): "), dft);
159 rc = get_user_reply(cxt, prompt, buf, bufsz);
160 if (rc)
161 return rc;
162 if (!*buf) {
163 fdisk_info(cxt, _("Using default response %c."), dft);
164 c = dft;
165 } else
166 c = tolower(buf[0]);
167
168 /* check result */
169 i = 0;
170 while (fdisk_ask_menu_get_item(ask, i++, &key, NULL, NULL) == 0) {
171 if (c == key) {
172 fdisk_ask_menu_set_result(ask, c);
173 return 0; /* success */
174 }
175 }
176 fdisk_warnx(cxt, _("Value out of range."));
177 } while (1);
178
179 return -EINVAL;
180 }
181
182
183 #define tochar(num) ((int) ('a' + num - 1))
184 static int ask_number(struct fdisk_context *cxt,
185 struct fdisk_ask *ask,
186 char *buf, size_t bufsz)
187 {
188 char prompt[128] = { '\0' };
189 const char *q = fdisk_ask_get_query(ask);
190 const char *range = fdisk_ask_number_get_range(ask);
191
192 uint64_t dflt = fdisk_ask_number_get_default(ask),
193 low = fdisk_ask_number_get_low(ask),
194 high = fdisk_ask_number_get_high(ask);
195 int inchar = fdisk_ask_number_inchars(ask);
196
197 assert(q);
198
199 DBG(ASK, ul_debug("asking for number "
200 "['%s', <%"PRIu64",%"PRIu64">, default=%"PRIu64", range: %s]",
201 q, low, high, dflt, range));
202
203 if (range && dflt >= low && dflt <= high) {
204 if (inchar)
205 snprintf(prompt, sizeof(prompt), _("%s (%s, default %c): "),
206 q, range, tochar(dflt));
207 else
208 snprintf(prompt, sizeof(prompt), _("%s (%s, default %"PRIu64"): "),
209 q, range, dflt);
210
211 } else if (dflt >= low && dflt <= high) {
212 if (inchar)
213 snprintf(prompt, sizeof(prompt), _("%s (%c-%c, default %c): "),
214 q, tochar(low), tochar(high), tochar(dflt));
215 else
216 snprintf(prompt, sizeof(prompt),
217 _("%s (%"PRIu64"-%"PRIu64", default %"PRIu64"): "),
218 q, low, high, dflt);
219 } else if (inchar)
220 snprintf(prompt, sizeof(prompt), _("%s (%c-%c): "),
221 q, tochar(low), tochar(high));
222 else
223 snprintf(prompt, sizeof(prompt), _("%s (%"PRIu64"-%"PRIu64"): "),
224 q, low, high);
225
226 do {
227 int rc = get_user_reply(cxt, prompt, buf, bufsz);
228 uint64_t num;
229
230 if (rc)
231 return rc;
232 if (!*buf && dflt >= low && dflt <= high)
233 return fdisk_ask_number_set_result(ask, dflt);
234
235 if (isdigit_string(buf)) {
236 char *end;
237
238 errno = 0;
239 num = strtoumax(buf, &end, 10);
240 if (errno || buf == end || (end && *end))
241 continue;
242 } else if (inchar && isalpha(*buf)) {
243 num = tolower(*buf) - 'a' + 1;
244 } else
245 rc = -EINVAL;
246
247 if (rc == 0 && num >= low && num <= high)
248 return fdisk_ask_number_set_result(ask, num);
249
250 fdisk_warnx(cxt, _("Value out of range."));
251 } while (1);
252
253 return -1;
254 }
255
256 static int ask_offset(struct fdisk_context *cxt,
257 struct fdisk_ask *ask,
258 char *buf, size_t bufsz)
259 {
260 char prompt[128] = { '\0' };
261 const char *q = fdisk_ask_get_query(ask);
262 const char *range = fdisk_ask_number_get_range(ask);
263
264 uint64_t dflt = fdisk_ask_number_get_default(ask),
265 low = fdisk_ask_number_get_low(ask),
266 high = fdisk_ask_number_get_high(ask),
267 base = fdisk_ask_number_get_base(ask);
268
269 assert(q);
270
271 DBG(ASK, ul_debug("asking for offset ['%s', <%"PRIu64",%"PRIu64">, base=%"PRIu64", default=%"PRIu64", range: %s]",
272 q, low, high, base, dflt, range));
273
274 if (range && dflt >= low && dflt <= high)
275 snprintf(prompt, sizeof(prompt), _("%s (%s, default %"PRIu64"): "),
276 q, range, dflt);
277 else if (dflt >= low && dflt <= high)
278 snprintf(prompt, sizeof(prompt),
279 _("%s (%"PRIu64"-%"PRIu64", default %"PRIu64"): "),
280 q, low, high, dflt);
281 else
282 snprintf(prompt, sizeof(prompt), _("%s (%"PRIu64"-%"PRIu64"): "),
283 q, low, high);
284
285 do {
286 uintmax_t num = 0;
287 char sig = 0, *p;
288 int pwr = 0;
289
290 int rc = get_user_reply(cxt, prompt, buf, bufsz);
291 if (rc)
292 return rc;
293 if (!*buf && dflt >= low && dflt <= high)
294 return fdisk_ask_number_set_result(ask, dflt);
295
296 p = buf;
297 if (*p == '+' || *p == '-') {
298 sig = *buf;
299 p++;
300 }
301
302 rc = parse_size(p, &num, &pwr);
303 if (rc)
304 continue;
305 DBG(ASK, ul_debug("parsed size: %ju", num));
306 if (sig && pwr) {
307 /* +{size}{K,M,...} specified, the "num" is in bytes */
308 uint64_t unit = fdisk_ask_number_get_unit(ask);
309 num += unit/2; /* round */
310 num /= unit;
311 }
312 if (sig == '+')
313 num += base;
314 else if (sig == '-')
315 num = base - num;
316
317 DBG(ASK, ul_debug("final offset: %ju [sig: %c, power: %d, %s]",
318 num, sig, pwr,
319 sig ? "relative" : "absolute"));
320 if (num >= low && num <= high) {
321 if (sig && pwr)
322 fdisk_ask_number_set_relative(ask, 1);
323 return fdisk_ask_number_set_result(ask, (uint64_t)num);
324 }
325 fdisk_warnx(cxt, _("Value out of range."));
326 } while (1);
327
328 return -1;
329 }
330
331 static unsigned int info_count;
332
333 static void fputs_info(struct fdisk_ask *ask, FILE *out)
334 {
335 const char *msg;
336 assert(ask);
337
338 msg = fdisk_ask_print_get_mesg(ask);
339 if (!msg)
340 return;
341 if (info_count == 1)
342 fputc('\n', out);
343
344 fputs(msg, out);
345 fputc('\n', out);
346 }
347
348 int ask_callback(struct fdisk_context *cxt, struct fdisk_ask *ask,
349 void *data __attribute__((__unused__)))
350 {
351 int rc = 0;
352 char buf[BUFSIZ];
353
354 assert(cxt);
355 assert(ask);
356
357 if (fdisk_ask_get_type(ask) != FDISK_ASKTYPE_INFO)
358 info_count = 0;
359
360 switch(fdisk_ask_get_type(ask)) {
361 case FDISK_ASKTYPE_MENU:
362 return ask_menu(cxt, ask, buf, sizeof(buf));
363 case FDISK_ASKTYPE_NUMBER:
364 return ask_number(cxt, ask, buf, sizeof(buf));
365 case FDISK_ASKTYPE_OFFSET:
366 return ask_offset(cxt, ask, buf, sizeof(buf));
367 case FDISK_ASKTYPE_INFO:
368 if (!fdisk_is_listonly(cxt))
369 info_count++;
370 fputs_info(ask, stdout);
371 break;
372 case FDISK_ASKTYPE_WARNX:
373 fflush(stdout);
374 color_scheme_fenable("warn", UL_COLOR_RED, stderr);
375 fputs(fdisk_ask_print_get_mesg(ask), stderr);
376 color_fdisable(stderr);
377 fputc('\n', stderr);
378 break;
379 case FDISK_ASKTYPE_WARN:
380 fflush(stdout);
381 color_scheme_fenable("warn", UL_COLOR_RED, stderr);
382 fputs(fdisk_ask_print_get_mesg(ask), stderr);
383 errno = fdisk_ask_print_get_errno(ask);
384 fprintf(stderr, ": %m\n");
385 color_fdisable(stderr);
386 break;
387 case FDISK_ASKTYPE_YESNO:
388 fputc('\n', stdout);
389 do {
390 int x;
391 fputs(fdisk_ask_get_query(ask), stdout);
392 rc = get_user_reply(cxt, _(" [Y]es/[N]o: "), buf, sizeof(buf));
393 if (rc)
394 break;
395 x = rpmatch(buf);
396 if (x == RPMATCH_YES || x == RPMATCH_NO) {
397 fdisk_ask_yesno_set_result(ask, x);
398 break;
399 }
400 } while(1);
401 DBG(ASK, ul_debug("yes-no ask: reply '%s' [rc=%d]", buf, rc));
402 break;
403 case FDISK_ASKTYPE_STRING:
404 {
405 char prmt[BUFSIZ];
406 snprintf(prmt, sizeof(prmt), "%s: ", fdisk_ask_get_query(ask));
407 fputc('\n', stdout);
408 rc = get_user_reply(cxt, prmt, buf, sizeof(buf));
409 if (rc == 0)
410 fdisk_ask_string_set_result(ask, xstrdup(buf));
411 DBG(ASK, ul_debug("string ask: reply '%s' [rc=%d]", buf, rc));
412 break;
413 }
414 default:
415 warnx(_("internal error: unsupported dialog type %d"), fdisk_ask_get_type(ask));
416 return -EINVAL;
417 }
418 return rc;
419 }
420
421 static struct fdisk_parttype *ask_partition_type(struct fdisk_context *cxt)
422 {
423 const char *q;
424 struct fdisk_label *lb;
425
426 assert(cxt);
427 lb = fdisk_get_label(cxt, NULL);
428
429 if (!lb)
430 return NULL;
431
432 q = fdisk_label_has_code_parttypes(lb) ?
433 _("Partition type (type L to list all types): ") :
434 _("Hex code (type L to list all codes): ");
435 do {
436 char buf[256];
437 int rc = get_user_reply(cxt, q, buf, sizeof(buf));
438
439 if (rc)
440 break;
441
442 if (buf[1] == '\0' && toupper(*buf) == 'L')
443 list_partition_types(cxt);
444 else if (*buf)
445 return fdisk_label_parse_parttype(lb, buf);
446 } while (1);
447
448 return NULL;
449 }
450
451
452 void list_partition_types(struct fdisk_context *cxt)
453 {
454 size_t ntypes = 0;
455 struct fdisk_label *lb;
456
457 assert(cxt);
458 lb = fdisk_get_label(cxt, NULL);
459 if (!lb)
460 return;
461 ntypes = fdisk_label_get_nparttypes(lb);
462 if (!ntypes)
463 return;
464
465 if (fdisk_label_has_code_parttypes(lb)) {
466 /*
467 * Prints in 4 columns in format <hex> <name>
468 */
469 size_t last[4], done = 0, next = 0, size;
470 int i;
471
472 size = ntypes;
473
474 for (i = 3; i >= 0; i--)
475 last[3 - i] = done += (size + i - done) / (i + 1);
476 i = done = 0;
477
478 do {
479 #define NAME_WIDTH 15
480 char name[NAME_WIDTH * MB_LEN_MAX];
481 size_t width = NAME_WIDTH;
482 const struct fdisk_parttype *t = fdisk_label_get_parttype(lb, next);
483 size_t ret;
484
485 if (fdisk_parttype_get_name(t)) {
486 printf("%c%2x ", i ? ' ' : '\n',
487 fdisk_parttype_get_code(t));
488 ret = mbsalign(_(fdisk_parttype_get_name(t)),
489 name, sizeof(name),
490 &width, MBS_ALIGN_LEFT, 0);
491
492 if (ret == (size_t)-1 || ret >= sizeof(name))
493 printf("%-15.15s",
494 _(fdisk_parttype_get_name(t)));
495 else
496 fputs(name, stdout);
497 }
498
499 next = last[i++] + done;
500 if (i > 3 || next >= last[i]) {
501 i = 0;
502 next = ++done;
503 }
504 } while (done < last[0]);
505
506 } else {
507 /*
508 * Prints 1 column in format <idx> <name> <typestr>
509 */
510 size_t i;
511
512 pager_open();
513
514 for (i = 0; i < ntypes; i++) {
515 const struct fdisk_parttype *t = fdisk_label_get_parttype(lb, i);
516 printf("%3zu %-30s %s\n", i + 1,
517 fdisk_parttype_get_name(t),
518 fdisk_parttype_get_string(t));
519 }
520
521 pager_close();
522 }
523 putchar('\n');
524 }
525
526 void toggle_dos_compatibility_flag(struct fdisk_context *cxt)
527 {
528 struct fdisk_label *lb = fdisk_get_label(cxt, "dos");
529 int flag;
530
531 if (!lb)
532 return;
533
534 flag = !fdisk_dos_is_compatible(lb);
535 fdisk_info(cxt, flag ?
536 _("DOS Compatibility flag is set (DEPRECATED!)") :
537 _("DOS Compatibility flag is not set"));
538
539 fdisk_dos_enable_compatible(lb, flag);
540
541 if (fdisk_is_label(cxt, DOS))
542 fdisk_reset_alignment(cxt); /* reset the current label */
543 }
544
545 void change_partition_type(struct fdisk_context *cxt)
546 {
547 size_t i;
548 struct fdisk_parttype *t = NULL;
549 struct fdisk_partition *pa = NULL;
550 const char *old = NULL;
551
552 assert(cxt);
553
554 if (fdisk_ask_partnum(cxt, &i, FALSE))
555 return;
556
557 if (fdisk_get_partition(cxt, i, &pa)) {
558 fdisk_warnx(cxt, _("Partition %zu does not exist yet!"), i + 1);
559 return;
560 }
561
562 t = (struct fdisk_parttype *) fdisk_partition_get_type(pa);
563 old = t ? fdisk_parttype_get_name(t) : _("Unknown");
564
565 do {
566 t = ask_partition_type(cxt);
567 } while (!t);
568
569 if (fdisk_set_partition_type(cxt, i, t) == 0)
570 fdisk_info(cxt,
571 _("Changed type of partition '%s' to '%s'."),
572 old, t ? fdisk_parttype_get_name(t) : _("Unknown"));
573 else
574 fdisk_info(cxt,
575 _("Type of partition %zu is unchanged: %s."),
576 i + 1, old);
577
578 fdisk_unref_partition(pa);
579 fdisk_unref_parttype(t);
580 }
581
582 int print_partition_info(struct fdisk_context *cxt)
583 {
584 struct fdisk_partition *pa = NULL;
585 int rc = 0;
586 size_t i, nfields;
587 int *fields = NULL;
588 struct fdisk_label *lb = fdisk_get_label(cxt, NULL);
589
590 if ((rc = fdisk_ask_partnum(cxt, &i, FALSE)))
591 return rc;
592
593 if ((rc = fdisk_get_partition(cxt, i, &pa))) {
594 fdisk_warnx(cxt, _("Partition %zu does not exist yet!"), i + 1);
595 return rc;
596 }
597
598 if ((rc = fdisk_label_get_fields_ids_all(lb, cxt, &fields, &nfields)))
599 goto clean_data;
600
601 for (i = 0; i < nfields; ++i) {
602 int id = fields[i];
603 char *data = NULL;
604 const struct fdisk_field *fd = fdisk_label_get_field(lb, id);
605
606 if (!fd)
607 continue;
608
609 rc = fdisk_partition_to_string(pa, cxt, id, &data);
610 if (rc < 0)
611 goto clean_data;
612 if (!data || !*data)
613 continue;
614 fdisk_info(cxt, _("%15s: %s"), fdisk_field_get_name(fd), data);
615 free(data);
616 }
617
618 clean_data:
619 fdisk_unref_partition(pa);
620 free(fields);
621 return rc;
622 }
623
624 static size_t skip_empty(const unsigned char *buf, size_t i, size_t sz)
625 {
626 size_t next;
627 const unsigned char *p0 = buf + i;
628
629 for (next = i + 16; next < sz; next += 16) {
630 if (memcmp(p0, buf + next, 16) != 0)
631 break;
632 }
633
634 return next == i + 16 ? i : next;
635 }
636
637 static void dump_buffer(off_t base, unsigned char *buf, size_t sz, int all)
638 {
639 size_t i, l, next = 0;
640
641 if (!buf)
642 return;
643 for (i = 0, l = 0; i < sz; i++, l++) {
644 if (l == 0) {
645 if (all == 0 && !next)
646 next = skip_empty(buf, i, sz);
647 printf("%08jx ", (intmax_t)base + i);
648 }
649 printf(" %02x", buf[i]);
650 if (l == 7) /* words separator */
651 fputs(" ", stdout);
652 else if (l == 15) {
653 fputc('\n', stdout); /* next line */
654 l = -1;
655 if (next > i) {
656 printf("*\n");
657 i = next - 1;
658 }
659 next = 0;
660 }
661 }
662 if (l > 0)
663 printf("\n");
664 }
665
666 static void dump_blkdev(struct fdisk_context *cxt, const char *name,
667 uint64_t offset, size_t size, int all)
668 {
669 int fd = fdisk_get_devfd(cxt);
670
671 fdisk_info(cxt, _("\n%s: offset = %"PRIu64", size = %zu bytes."),
672 name, offset, size);
673
674 assert(fd >= 0);
675
676 if (lseek(fd, (off_t) offset, SEEK_SET) == (off_t) -1)
677 fdisk_warn(cxt, _("cannot seek"));
678 else {
679 unsigned char *buf = xmalloc(size);
680
681 if (read_all(fd, (char *) buf, size) != (ssize_t) size)
682 fdisk_warn(cxt, _("cannot read"));
683 else
684 dump_buffer(offset, buf, size, all);
685 free(buf);
686 }
687 }
688
689 void dump_firstsector(struct fdisk_context *cxt)
690 {
691 int all = !isatty(STDOUT_FILENO);
692
693 assert(cxt);
694
695 dump_blkdev(cxt, _("First sector"), 0, fdisk_get_sector_size(cxt), all);
696 }
697
698 void dump_disklabel(struct fdisk_context *cxt)
699 {
700 int all = !isatty(STDOUT_FILENO);
701 int i = 0;
702 const char *name = NULL;
703 uint64_t offset = 0;
704 size_t size = 0;
705
706 assert(cxt);
707
708 while (fdisk_locate_disklabel(cxt, i++, &name, &offset, &size) == 0 && size)
709 dump_blkdev(cxt, name, offset, size, all);
710 }
711
712 static fdisk_sector_t get_dev_blocks(char *dev)
713 {
714 int fd, ret;
715 fdisk_sector_t size;
716
717 if ((fd = open(dev, O_RDONLY)) < 0)
718 err(EXIT_FAILURE, _("cannot open %s"), dev);
719 ret = blkdev_get_sectors(fd, (unsigned long long *) &size);
720 close(fd);
721 if (ret < 0)
722 err(EXIT_FAILURE, _("BLKGETSIZE ioctl failed on %s"), dev);
723 return size/2;
724 }
725
726 static void __attribute__ ((__noreturn__)) usage(FILE *out)
727 {
728 fputs(USAGE_HEADER, out);
729
730 fprintf(out,
731 _(" %1$s [options] <disk> change partition table\n"
732 " %1$s [options] -l [<disk>] list partition table(s)\n"),
733 program_invocation_short_name);
734
735 fputs(USAGE_SEPARATOR, out);
736 fputs(_("Display or manipulate a disk partition table.\n"), out);
737
738 fputs(USAGE_OPTIONS, out);
739 fputs(_(" -b, --sector-size <size> physical and logical sector size\n"), out);
740 fputs(_(" -B, --protect-boot don't erase bootbits when creating a new label\n"), out);
741 fputs(_(" -c, --compatibility[=<mode>] mode is 'dos' or 'nondos' (default)\n"), out);
742 fputs(_(" -L, --color[=<when>] colorize output (auto, always or never)\n"), out);
743 fprintf(out,
744 " %s\n", USAGE_COLORS_DEFAULT);
745 fputs(_(" -l, --list display partitions and exit\n"), out);
746 fputs(_(" -o, --output <list> output columns\n"), out);
747 fputs(_(" -t, --type <type> recognize specified partition table type only\n"), out);
748 fputs(_(" -u, --units[=<unit>] display units: 'cylinders' or 'sectors' (default)\n"), out);
749 fputs(_(" -s, --getsz display device size in 512-byte sectors [DEPRECATED]\n"), out);
750 fputs(_(" --bytes print SIZE in bytes rather than in human readable format\n"), out);
751 fputs(_(" -w, --wipe <mode> wipe signatures (auto, always or never)\n"), out);
752 fputs(_(" -W, --wipe-partitions <mode> wipe signatures from new partitions (auto, always or never)\n"), out);
753
754 fputs(USAGE_SEPARATOR, out);
755 fputs(_(" -C, --cylinders <number> specify the number of cylinders\n"), out);
756 fputs(_(" -H, --heads <number> specify the number of heads\n"), out);
757 fputs(_(" -S, --sectors <number> specify the number of sectors per track\n"), out);
758
759 fputs(USAGE_SEPARATOR, out);
760 fputs(USAGE_HELP, out);
761 fputs(USAGE_VERSION, out);
762
763 list_available_columns(out);
764
765 fprintf(out, USAGE_MAN_TAIL("fdisk(8)"));
766 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
767 }
768
769
770 enum {
771 ACT_FDISK = 0, /* default */
772 ACT_LIST,
773 ACT_SHOWSIZE
774 };
775
776 int main(int argc, char **argv)
777 {
778 int rc, i, c, act = ACT_FDISK;
779 int colormode = UL_COLORMODE_UNDEF;
780 int wipemode = WIPEMODE_AUTO;
781 struct fdisk_context *cxt;
782 char *outarg = NULL;
783 enum {
784 OPT_BYTES = CHAR_MAX + 1
785 };
786 static const struct option longopts[] = {
787 { "bytes", no_argument, NULL, OPT_BYTES },
788 { "color", optional_argument, NULL, 'L' },
789 { "compatibility", optional_argument, NULL, 'c' },
790 { "cylinders", required_argument, NULL, 'C' },
791 { "heads", required_argument, NULL, 'H' },
792 { "sectors", required_argument, NULL, 'S' },
793 { "getsz", no_argument, NULL, 's' },
794 { "help", no_argument, NULL, 'h' },
795 { "list", no_argument, NULL, 'l' },
796 { "sector-size", required_argument, NULL, 'b' },
797 { "type", required_argument, NULL, 't' },
798 { "units", optional_argument, NULL, 'u' },
799 { "version", no_argument, NULL, 'V' },
800 { "output", no_argument, NULL, 'o' },
801 { "protect-boot", no_argument, NULL, 'B' },
802 { "wipe", required_argument, NULL, 'w' },
803 { "wipe-partitions",required_argument, NULL, 'W' },
804 { NULL, 0, NULL, 0 }
805 };
806
807 setlocale(LC_ALL, "");
808 bindtextdomain(PACKAGE, LOCALEDIR);
809 textdomain(PACKAGE);
810 atexit(close_stdout);
811
812 fdisk_init_debug(0);
813 scols_init_debug(0);
814 fdiskprog_init_debug();
815
816 cxt = fdisk_new_context();
817 if (!cxt)
818 err(EXIT_FAILURE, _("failed to allocate libfdisk context"));
819
820 fdisk_set_ask(cxt, ask_callback, NULL);
821
822 while ((c = getopt_long(argc, argv, "b:Bc::C:hH:lL::o:sS:t:u::vVw:W:",
823 longopts, NULL)) != -1) {
824 switch (c) {
825 case 'b':
826 {
827 size_t sz = strtou32_or_err(optarg,
828 _("invalid sector size argument"));
829 if (sz != 512 && sz != 1024 && sz != 2048 && sz != 4096)
830 usage(stderr);
831 fdisk_save_user_sector_size(cxt, sz, sz);
832 break;
833 }
834 case 'B':
835 fdisk_enable_bootbits_protection(cxt, 1);
836 break;
837 case 'C':
838 fdisk_save_user_geometry(cxt,
839 strtou32_or_err(optarg,
840 _("invalid cylinders argument")),
841 0, 0);
842 break;
843 case 'c':
844 if (optarg) {
845 /* this setting is independent on the current
846 * actively used label
847 */
848 char *p = *optarg == '=' ? optarg + 1 : optarg;
849 struct fdisk_label *lb = fdisk_get_label(cxt, "dos");
850
851 if (!lb)
852 err(EXIT_FAILURE, _("not found DOS label driver"));
853 if (strcmp(p, "dos") == 0)
854 fdisk_dos_enable_compatible(lb, TRUE);
855 else if (strcmp(p, "nondos") == 0)
856 fdisk_dos_enable_compatible(lb, FALSE);
857 else {
858 warnx(_("unknown compatibility mode '%s'"), p);
859 usage(stderr);
860 }
861 }
862 /* use default if no optarg specified */
863 break;
864 case 'H':
865 fdisk_save_user_geometry(cxt, 0,
866 strtou32_or_err(optarg,
867 _("invalid heads argument")),
868 0);
869 break;
870 case 'S':
871 fdisk_save_user_geometry(cxt, 0, 0,
872 strtou32_or_err(optarg,
873 _("invalid sectors argument")));
874 break;
875 case 'l':
876 act = ACT_LIST;
877 break;
878 case 'L':
879 colormode = UL_COLORMODE_AUTO;
880 if (optarg)
881 colormode = colormode_or_err(optarg,
882 _("unsupported color mode"));
883 break;
884 case 'o':
885 outarg = optarg;
886 break;
887 case 's':
888 act = ACT_SHOWSIZE;
889 break;
890 case 't':
891 {
892 struct fdisk_label *lb = NULL;
893
894 while (fdisk_next_label(cxt, &lb) == 0)
895 fdisk_label_set_disabled(lb, 1);
896
897 lb = fdisk_get_label(cxt, optarg);
898 if (!lb)
899 errx(EXIT_FAILURE, _("unsupported disklabel: %s"), optarg);
900 fdisk_label_set_disabled(lb, 0);
901 break;
902 }
903 case 'u':
904 if (optarg && *optarg == '=')
905 optarg++;
906 if (fdisk_set_unit(cxt, optarg) != 0)
907 usage(stderr);
908 break;
909 case 'V': /* preferred for util-linux */
910 case 'v': /* for backward compatibility only */
911 printf(UTIL_LINUX_VERSION);
912 return EXIT_SUCCESS;
913 case 'w':
914 wipemode = wipemode_from_string(optarg);
915 if (wipemode < 0)
916 errx(EXIT_FAILURE, _("unsupported wipe mode"));
917 break;
918 case 'W':
919 pwipemode = wipemode_from_string(optarg);
920 if (pwipemode < 0)
921 errx(EXIT_FAILURE, _("unsupported wipe mode"));
922 break;
923 case 'h':
924 usage(stdout);
925 case OPT_BYTES:
926 fdisk_set_size_unit(cxt, FDISK_SIZEUNIT_BYTES);
927 break;
928 default:
929 errtryhelp(EXIT_FAILURE);
930 }
931 }
932
933 if (argc-optind != 1 && fdisk_has_user_device_properties(cxt))
934 warnx(_("The device properties (sector size and geometry) should"
935 " be used with one specified device only."));
936
937 colors_init(colormode, "fdisk");
938
939 switch (act) {
940 case ACT_LIST:
941 fdisk_enable_listonly(cxt, 1);
942 init_fields(cxt, outarg, NULL);
943
944 if (argc > optind) {
945 int k;
946 int ct = 0;
947
948 for (rc = 0, k = optind; k < argc; k++) {
949 if (ct)
950 fputs("\n\n", stdout);
951
952 rc += print_device_pt(cxt, argv[k], 1, 0);
953 ct++;
954 }
955 if (rc)
956 return EXIT_FAILURE;
957 } else
958 print_all_devices_pt(cxt, 0);
959 break;
960
961 case ACT_SHOWSIZE:
962 /* deprecated */
963 if (argc - optind <= 0)
964 usage(stderr);
965
966 for (i = optind; i < argc; i++) {
967 uintmax_t blks = get_dev_blocks(argv[i]);
968
969 if (argc - optind == 1)
970 printf("%ju\n", blks);
971 else
972 printf("%s: %ju\n", argv[i], blks);
973 }
974 break;
975
976 case ACT_FDISK:
977 if (argc-optind != 1)
978 usage(stderr);
979
980 /* Here starts interactive mode, use fdisk_{warn,info,..} functions */
981 color_scheme_enable("welcome", UL_COLOR_GREEN);
982 fdisk_info(cxt, _("Welcome to fdisk (%s)."), PACKAGE_STRING);
983 color_disable();
984 fdisk_info(cxt, _("Changes will remain in memory only, until you decide to write them.\n"
985 "Be careful before using the write command.\n"));
986
987 rc = fdisk_assign_device(cxt, argv[optind], 0);
988 if (rc == -EACCES) {
989 rc = fdisk_assign_device(cxt, argv[optind], 1);
990 if (rc == 0)
991 fdisk_warnx(cxt, _("Device is open in read-only mode."));
992 }
993 if (rc)
994 err(EXIT_FAILURE, _("cannot open %s"), argv[optind]);
995
996 fflush(stdout);
997
998 if (fdisk_get_collision(cxt)) {
999 int dowipe = wipemode == WIPEMODE_ALWAYS ? 1 : 0;
1000
1001 fdisk_warnx(cxt, _("Device %s already contains a %s signature."),
1002 argv[optind], fdisk_get_collision(cxt));
1003
1004 if (isatty(STDIN_FILENO) && wipemode == WIPEMODE_AUTO)
1005 dowipe = 1; /* do it in interactive mode */
1006
1007 fdisk_enable_wipe(cxt, dowipe);
1008 if (dowipe)
1009 fdisk_warnx(cxt, _(
1010 "The signature will be removed by a write command."));
1011 else
1012 fdisk_warnx(cxt, _(
1013 "It is strongly recommended to wipe the device with "
1014 "wipefs(8), in order to avoid possible collisions."));
1015 }
1016 if (!fdisk_has_label(cxt)) {
1017 fdisk_info(cxt, _("Device does not contain a recognized partition table."));
1018 fdisk_create_disklabel(cxt, NULL);
1019
1020 } else if (fdisk_is_label(cxt, GPT) && fdisk_gpt_is_hybrid(cxt))
1021 fdisk_warnx(cxt, _(
1022 "A hybrid GPT was detected. You have to sync "
1023 "the hybrid MBR manually (expert command 'M')."));
1024
1025 init_fields(cxt, outarg, NULL); /* -o <columns> */
1026
1027 while (1)
1028 process_fdisk_menu(&cxt);
1029 }
1030
1031 fdisk_unref_context(cxt);
1032 return EXIT_SUCCESS;
1033 }