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