]> git.ipfire.org Git - thirdparty/util-linux.git/blob - disk-utils/cfdisk.c
rfkill: merge rfkill.8 project to util-linux
[thirdparty/util-linux.git] / disk-utils / cfdisk.c
1 /*
2 * cfdisk.c - Display or manipulate a disk partition table.
3 *
4 * Copyright (C) 2014-2015 Karel Zak <kzak@redhat.com>
5 * Copyright (C) 1994 Kevin E. Martin (martin@cs.unc.edu)
6 *
7 * The original cfdisk was inspired by the fdisk program
8 * by A. V. Le Blanc (leblanc@mcc.ac.uk.
9 *
10 * cfdisk is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 */
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <errno.h>
18 #include <signal.h>
19 #include <ctype.h>
20 #include <getopt.h>
21 #include <assert.h>
22 #include <libsmartcols.h>
23 #include <sys/ioctl.h>
24 #include <libfdisk.h>
25
26 #ifdef HAVE_LIBMOUNT
27 # include <libmount.h> /* keep it optional for non-linux systems */
28 #endif
29
30 #ifdef HAVE_SLANG_H
31 # include <slang.h>
32 #elif defined(HAVE_SLANG_SLANG_H)
33 # include <slang/slang.h>
34 #endif
35
36 #ifdef HAVE_SLCURSES_H
37 # include <slcurses.h>
38 #elif defined(HAVE_SLANG_SLCURSES_H)
39 # include <slang/slcurses.h>
40 #elif defined(HAVE_NCURSESW_NCURSES_H) && defined(HAVE_WIDECHAR)
41 # include <ncursesw/ncurses.h>
42 #elif defined(HAVE_NCURSES_H)
43 # include <ncurses.h>
44 #elif defined(HAVE_NCURSES_NCURSES_H)
45 # include <ncurses/ncurses.h>
46 #endif
47
48 #ifdef HAVE_WIDECHAR
49 # include <wctype.h>
50 # include <wchar.h>
51 #endif
52
53 #include "c.h"
54 #include "closestream.h"
55 #include "nls.h"
56 #include "strutils.h"
57 #include "xalloc.h"
58 #include "mbsalign.h"
59 #include "mbsedit.h"
60 #include "colors.h"
61 #include "debug.h"
62 #include "list.h"
63
64 static const char *default_disks[] = {
65 #ifdef __GNU__
66 "/dev/hd0",
67 "/dev/sd0",
68 #elif defined(__FreeBSD__)
69 "/dev/ad0",
70 "/dev/da0",
71 #else
72 "/dev/sda",
73 "/dev/vda",
74 "/dev/hda",
75 #endif
76 };
77
78 #define ARROW_CURSOR_STRING ">> "
79 #define ARROW_CURSOR_DUMMY " "
80 #define ARROW_CURSOR_WIDTH (sizeof(ARROW_CURSOR_STRING) - 1)
81
82 /* vertical menu */
83 #define MENU_V_SPADDING 1 /* space around menu item string */
84
85 /* horizontal menu */
86 #define MENU_H_SPADDING 0 /* space around menu item string */
87 #define MENU_H_BETWEEN 2 /* space between menu items */
88 #define MENU_H_PRESTR "["
89 #define MENU_H_POSTSTR "]"
90
91 #define MENU_TITLE_PADDING 3
92
93 #define MENU_H_PRESTR_SZ (sizeof(MENU_H_PRESTR) - 1)
94 #define MENU_H_POSTSTR_SZ (sizeof(MENU_H_POSTSTR) - 1)
95
96 #define TABLE_START_LINE 4
97 #define MENU_START_LINE (ui_lines - 4) /* The menu maybe use two lines */
98 #define INFO_LINE (ui_lines - 2)
99 #define WARN_LINE INFO_LINE
100 #define HINT_LINE (ui_lines - 1)
101
102 #define CFDISK_ERR_ESC 5000
103
104 #ifndef KEY_ESC
105 # define KEY_ESC '\033'
106 #endif
107 #ifndef KEY_DELETE
108 # define KEY_DELETE '\177'
109 #endif
110 #ifndef KEY_DC
111 # define KEY_DC 0423
112 #endif
113
114
115 /* colors */
116 enum {
117 CFDISK_CL_NONE = 0,
118 CFDISK_CL_WARNING,
119 CFDISK_CL_FREESPACE,
120 CFDISK_CL_INFO
121 };
122 static const int color_pairs[][2] = {
123 /* color foreground, background */
124 [CFDISK_CL_WARNING] = { COLOR_RED, -1 },
125 [CFDISK_CL_FREESPACE] = { COLOR_GREEN, -1 },
126 [CFDISK_CL_INFO] = { COLOR_BLUE, -1 }
127 };
128
129 struct cfdisk;
130
131 static struct cfdisk_menuitem *menu_get_menuitem(struct cfdisk *cf, size_t idx);
132 static struct cfdisk_menuitem *menu_get_menuitem_by_key(struct cfdisk *cf, int key, size_t *idx);
133 static struct cfdisk_menu *menu_push(struct cfdisk *cf, struct cfdisk_menuitem *item);
134 static struct cfdisk_menu *menu_pop(struct cfdisk *cf);
135 static void menu_refresh_size(struct cfdisk *cf);
136
137 static int ui_refresh(struct cfdisk *cf);
138 static void ui_warnx(const char *fmt, ...);
139 static void ui_warn(const char *fmt, ...);
140 static void ui_info(const char *fmt, ...);
141 static void ui_draw_menu(struct cfdisk *cf);
142 static int ui_menu_move(struct cfdisk *cf, int key);
143 static void ui_menu_resize(struct cfdisk *cf);
144
145 static int ui_get_size(struct cfdisk *cf, const char *prompt, uintmax_t *res,
146 uintmax_t low, uintmax_t up, int *expsize);
147
148 static int ui_enabled;
149 static int ui_resize;
150
151 /* ncurses LINES and COLS may be actual variables or *macros*, but we need
152 * something portable and writable */
153 static size_t ui_lines;
154 static size_t ui_cols;
155
156 /* menu item */
157 struct cfdisk_menuitem {
158 int key; /* keyboard shortcut */
159 const char *name; /* item name */
160 const char *desc; /* item description (hint) */
161 void *userdata;
162 };
163
164 /* menu */
165 struct cfdisk_menu {
166 char *title; /* optional menu title */
167 struct cfdisk_menuitem *items; /* array with menu items */
168 char *ignore;/* string with keys to ignore */
169 size_t width; /* maximal width of the menu item */
170 size_t nitems; /* number of the active menu items */
171 size_t page_sz;/* when menu longer than screen */
172 size_t idx; /* the current menu item */
173 int prefkey;/* preferred menu item */
174 struct cfdisk_menu *prev;
175
176 /* @ignore keys generator */
177 int (*ignore_cb) (struct cfdisk *, char *, size_t);
178
179 unsigned int vertical : 1; /* enable vertical mode */
180 };
181
182 /* main menu */
183 static struct cfdisk_menuitem main_menuitems[] = {
184 { 'b', N_("Bootable"), N_("Toggle bootable flag of the current partition") },
185 { 'd', N_("Delete"), N_("Delete the current partition") },
186 { 'r', N_("Resize"), N_("Reduce or enlarge the current partition") },
187 { 'n', N_("New"), N_("Create new partition from free space") },
188 { 'q', N_("Quit"), N_("Quit program without writing changes") },
189 { 't', N_("Type"), N_("Change the partition type") },
190 { 'h', N_("Help"), N_("Print help screen") },
191 { 's', N_("Sort"), N_("Fix partitions order") },
192 { 'W', N_("Write"), N_("Write partition table to disk (this might destroy data)") },
193 { 'u', N_("Dump"), N_("Dump partition table to sfdisk compatible script file") },
194 { 0, NULL, NULL }
195 };
196
197 /* extra partinfo in name:value pairs */
198 struct cfdisk_extra {
199 char *name;
200 char *data;
201
202 struct list_head exs;
203 };
204
205 /* line and extra partinfo list_head */
206 struct cfdisk_line {
207 char *data; /* line data */
208 struct libscols_table *extra; /* extra info ('X') */
209 WINDOW *w; /* window with extra info */
210 };
211
212 /* top level control struct */
213 struct cfdisk {
214 struct fdisk_context *cxt; /* libfdisk context */
215 struct fdisk_table *table; /* partition table */
216 struct fdisk_table *original_layout; /* original on-disk PT */
217
218 struct cfdisk_menu *menu; /* the current menu */
219
220 int *fields; /* output columns IDs */
221 size_t nfields; /* number of columns IDs */
222
223 char *linesbuf; /* table as string */
224 size_t linesbufsz; /* size of the tb_buf */
225
226 struct cfdisk_line *lines; /* list of lines */
227
228 size_t nlines; /* number of lines */
229 size_t lines_idx; /* current line <0..N>, exclude header */
230 size_t page_sz;
231
232 unsigned int nwrites; /* fdisk_write_disklabel() counter */
233
234 WINDOW *act_win; /* the window currently on the screen */
235
236 #ifdef HAVE_LIBMOUNT
237 struct libmnt_table *mtab;
238 struct libmnt_table *fstab;
239 struct libmnt_cache *mntcache;
240 #endif
241 unsigned int wrong_order :1, /* PT not in right order */
242 zero_start :1, /* ignore existing partition table */
243 device_is_used : 1, /* don't use re-read ioctl */
244 show_extra :1; /* show extra partinfo */
245 };
246
247
248 /*
249 * let's use include/debug.h stuff for cfdisk too
250 */
251 static UL_DEBUG_DEFINE_MASK(cfdisk);
252 UL_DEBUG_DEFINE_MASKNAMES(cfdisk) = UL_DEBUG_EMPTY_MASKNAMES;
253
254 #define CFDISK_DEBUG_INIT (1 << 1)
255 #define CFDISK_DEBUG_UI (1 << 2)
256 #define CFDISK_DEBUG_MENU (1 << 3)
257 #define CFDISK_DEBUG_MISC (1 << 4)
258 #define CFDISK_DEBUG_TABLE (1 << 5)
259 #define CFDISK_DEBUG_ALL 0xFFFF
260
261 #define DBG(m, x) __UL_DBG(cfdisk, CFDISK_DEBUG_, m, x)
262
263 static void cfdisk_init_debug(void)
264 {
265 __UL_INIT_DEBUG(cfdisk, CFDISK_DEBUG_, 0, CFDISK_DEBUG);
266 }
267
268 /* Initialize output columns -- we follow libfdisk fields (usually specific
269 * to the label type.
270 */
271 static int cols_init(struct cfdisk *cf)
272 {
273 assert(cf);
274
275 free(cf->fields);
276 cf->fields = NULL;
277 cf->nfields = 0;
278
279 return fdisk_label_get_fields_ids(NULL, cf->cxt, &cf->fields, &cf->nfields);
280 }
281
282 static void resize(void)
283 {
284 struct winsize ws;
285
286 if (ioctl(fileno(stdout), TIOCGWINSZ, &ws) != -1
287 && ws.ws_row && ws.ws_col) {
288 ui_lines = ws.ws_row;
289 ui_cols = ws.ws_col;
290 #if HAVE_RESIZETERM
291 resizeterm(ws.ws_row, ws.ws_col);
292 #endif
293 clearok(stdscr, TRUE);
294 }
295 touchwin(stdscr);
296
297 DBG(UI, ul_debug("ui: resize refresh ui_cols=%zu, ui_lines=%zu",
298 ui_cols, ui_lines));
299 ui_resize = 0;
300 }
301
302 /* Reads partition in tree-like order from scols
303 */
304 static int partition_from_scols(struct fdisk_table *tb,
305 struct libscols_line *ln)
306 {
307 struct fdisk_partition *pa = scols_line_get_userdata(ln);
308
309 fdisk_table_add_partition(tb, pa);
310 fdisk_unref_partition(pa);
311
312 if (scols_line_has_children(ln)) {
313 struct libscols_line *chln;
314 struct libscols_iter *itr = scols_new_iter(SCOLS_ITER_FORWARD);
315
316 if (!itr)
317 return -EINVAL;
318 while (scols_line_next_child(ln, itr, &chln) == 0)
319 partition_from_scols(tb, chln);
320 scols_free_iter(itr);
321 }
322 return 0;
323 }
324
325 static char *table_to_string(struct cfdisk *cf, struct fdisk_table *tb)
326 {
327 struct fdisk_partition *pa;
328 struct fdisk_label *lb;
329 struct fdisk_iter *itr;
330 struct libscols_table *table = NULL;
331 struct libscols_iter *s_itr = NULL;
332 char *res = NULL;
333 size_t i;
334 int tree = 0;
335 struct libscols_line *ln, *ln_cont = NULL;
336
337 DBG(TABLE, ul_debug("convert to string"));
338
339 assert(cf);
340 assert(cf->cxt);
341 assert(cf->fields);
342 assert(tb);
343
344 lb = fdisk_get_label(cf->cxt, NULL);
345 assert(lb);
346
347 itr = fdisk_new_iter(FDISK_ITER_FORWARD);
348 if (!itr)
349 goto done;
350
351 /* get container (e.g. extended partition) */
352 while (fdisk_table_next_partition(tb, itr, &pa) == 0) {
353 if (fdisk_partition_is_nested(pa)) {
354 DBG(TABLE, ul_debug("nested detected, using tree"));
355 tree = SCOLS_FL_TREE;
356 break;
357 }
358 }
359
360 table = scols_new_table();
361 if (!table)
362 goto done;
363 scols_table_enable_maxout(table, 1);
364 scols_table_enable_nowrap(table, 1);
365
366 #if !defined(HAVE_LIBNCURSESW) || !defined(HAVE_WIDECHAR)
367 scols_table_enable_ascii(table, 1);
368 #endif
369
370 /* headers */
371 for (i = 0; i < cf->nfields; i++) {
372 int fl = 0;
373 const struct fdisk_field *field =
374 fdisk_label_get_field(lb, cf->fields[i]);
375 if (!field)
376 continue;
377
378 if (fdisk_field_is_number(field))
379 fl |= SCOLS_FL_RIGHT;
380 if (fdisk_field_get_id(field) == FDISK_FIELD_TYPE)
381 fl |= SCOLS_FL_TRUNC;
382 if (tree && fdisk_field_get_id(field) == FDISK_FIELD_DEVICE)
383 fl |= SCOLS_FL_TREE;
384
385 if (!scols_table_new_column(table,
386 _(fdisk_field_get_name(field)),
387 fdisk_field_get_width(field), fl))
388 goto done;
389 }
390
391 /* data */
392 fdisk_reset_iter(itr, FDISK_ITER_FORWARD);
393
394 while (fdisk_table_next_partition(tb, itr, &pa) == 0) {
395 struct libscols_line *parent = fdisk_partition_is_nested(pa) ? ln_cont : NULL;
396
397 ln = scols_table_new_line(table, parent);
398 if (!ln)
399 goto done;
400 for (i = 0; i < cf->nfields; i++) {
401 char *cdata = NULL;
402
403 if (fdisk_partition_to_string(pa, cf->cxt,
404 cf->fields[i], &cdata))
405 continue;
406 scols_line_refer_data(ln, i, cdata);
407 }
408 if (tree && fdisk_partition_is_container(pa))
409 ln_cont = ln;
410
411 scols_line_set_userdata(ln, (void *) pa);
412 fdisk_ref_partition(pa);
413 }
414
415 if (scols_table_is_empty(table))
416 goto done;
417
418 scols_table_reduce_termwidth(table, ARROW_CURSOR_WIDTH);
419 scols_print_table_to_string(table, &res);
420
421 /* scols_* code might reorder lines, let's reorder @tb according to the
422 * final output (it's no problem because partitions are addressed by
423 * parno stored within struct fdisk_partition) */
424
425 /* remove all */
426 fdisk_reset_iter(itr, FDISK_ITER_FORWARD);
427 while (fdisk_table_next_partition(tb, itr, &pa) == 0)
428 fdisk_table_remove_partition(tb, pa);
429
430 s_itr = scols_new_iter(SCOLS_ITER_FORWARD);
431 if (!s_itr)
432 goto done;
433
434 /* add all in the right order (don't forget the output is tree) */
435 while (scols_table_next_line(table, s_itr, &ln) == 0) {
436 if (scols_line_get_parent(ln))
437 continue;
438 if (partition_from_scols(tb, ln))
439 break;
440 }
441 done:
442 scols_unref_table(table);
443 scols_free_iter(s_itr);
444 fdisk_free_iter(itr);
445
446 return res;
447 }
448
449 static void cfdisk_free_lines(struct cfdisk *cf)
450 {
451 size_t i = 0;
452 while(i < cf->nlines) {
453 scols_unref_table(cf->lines[i].extra);
454
455 DBG(UI, ul_debug("delete window: %p",
456 cf->lines[i].w));
457
458 if (cf->lines[i].w)
459 delwin(cf->lines[i].w);
460 cf->lines[i].w = NULL;
461 ++i;
462 }
463 cf->act_win = NULL;
464 free(cf->lines);
465 cf->lines = NULL;
466 }
467 /*
468 * Read data about partitions from libfdisk and prepare output lines.
469 */
470 static int lines_refresh(struct cfdisk *cf)
471 {
472 int rc;
473 char *p;
474 size_t i;
475
476 assert(cf);
477
478 DBG(TABLE, ul_debug("refreshing buffer"));
479
480 free(cf->linesbuf);
481 cfdisk_free_lines(cf);
482 cf->linesbuf = NULL;
483 cf->linesbufsz = 0;
484 cf->lines = NULL;
485 cf->nlines = 0;
486
487 fdisk_unref_table(cf->table);
488 cf->table = NULL;
489
490 /* read partitions and free spaces into cf->table */
491 rc = fdisk_get_partitions(cf->cxt, &cf->table);
492 if (!rc)
493 rc = fdisk_get_freespaces(cf->cxt, &cf->table);
494 if (rc)
495 return rc;
496
497 cf->linesbuf = table_to_string(cf, cf->table);
498 if (!cf->linesbuf)
499 return -ENOMEM;
500
501 cf->linesbufsz = strlen(cf->linesbuf);
502 cf->nlines = fdisk_table_get_nents(cf->table) + 1; /* 1 for header line */
503 cf->page_sz = 0;
504 cf->wrong_order = fdisk_table_wrong_order(cf->table) ? 1 : 0;
505
506 if (MENU_START_LINE - TABLE_START_LINE < cf->nlines)
507 cf->page_sz = MENU_START_LINE - TABLE_START_LINE - 1;
508
509 cf->lines = xcalloc(cf->nlines, sizeof(struct cfdisk_line));
510
511 for (p = cf->linesbuf, i = 0; p && i < cf->nlines; i++) {
512 cf->lines[i].data = p;
513 p = strchr(p, '\n');
514 if (p) {
515 *p = '\0';
516 p++;
517 }
518 cf->lines[i].extra = scols_new_table();
519 scols_table_enable_noheadings(cf->lines[i].extra, 1);
520 scols_table_new_column(cf->lines[i].extra, NULL, 0, SCOLS_FL_RIGHT);
521 scols_table_new_column(cf->lines[i].extra, NULL, 0, SCOLS_FL_TRUNC);
522 }
523
524 return 0;
525 }
526
527 static struct fdisk_partition *get_current_partition(struct cfdisk *cf)
528 {
529 assert(cf);
530 assert(cf->table);
531
532 return fdisk_table_get_partition(cf->table, cf->lines_idx);
533 }
534
535 static int is_freespace(struct cfdisk *cf, size_t i)
536 {
537 struct fdisk_partition *pa;
538
539 assert(cf);
540 assert(cf->table);
541
542 pa = fdisk_table_get_partition(cf->table, i);
543 return fdisk_partition_is_freespace(pa);
544 }
545
546 /* converts libfdisk FDISK_ASKTYPE_MENU to cfdisk menu and returns user's
547 * response back to libfdisk
548 */
549 static int ask_menu(struct fdisk_ask *ask, struct cfdisk *cf)
550 {
551 struct cfdisk_menuitem *d, *cm;
552 int key;
553 size_t i = 0, nitems;
554 const char *name, *desc;
555
556 assert(ask);
557 assert(cf);
558
559 /* create cfdisk menu according to libfdisk ask-menu, note that the
560 * last cm[] item has to be empty -- so nitems + 1 */
561 nitems = fdisk_ask_menu_get_nitems(ask);
562 cm = xcalloc(nitems + 1, sizeof(struct cfdisk_menuitem));
563
564 for (i = 0; i < nitems; i++) {
565 if (fdisk_ask_menu_get_item(ask, i, &key, &name, &desc))
566 break;
567 cm[i].key = key;
568 cm[i].desc = desc;
569 cm[i].name = name;
570 }
571
572 /* make the new menu active */
573 menu_push(cf, cm);
574 ui_draw_menu(cf);
575 refresh();
576
577 /* wait for keys */
578 do {
579 key = getch();
580
581 if (ui_resize)
582 ui_menu_resize(cf);
583 if (ui_menu_move(cf, key) == 0)
584 continue;
585
586 switch (key) {
587 case KEY_ENTER:
588 case '\n':
589 case '\r':
590 d = menu_get_menuitem(cf, cf->menu->idx);
591 if (d)
592 fdisk_ask_menu_set_result(ask, d->key);
593 menu_pop(cf);
594 free(cm);
595 return 0;
596 }
597 } while (1);
598
599 menu_pop(cf);
600 free(cm);
601 return -1;
602 }
603
604 /* libfdisk callback
605 */
606 static int ask_callback(struct fdisk_context *cxt __attribute__((__unused__)),
607 struct fdisk_ask *ask,
608 void *data __attribute__((__unused__)))
609 {
610 int rc = 0;
611
612 assert(ask);
613
614 switch(fdisk_ask_get_type(ask)) {
615 case FDISK_ASKTYPE_INFO:
616 ui_info(fdisk_ask_print_get_mesg(ask));
617 break;
618 case FDISK_ASKTYPE_WARNX:
619 ui_warnx(fdisk_ask_print_get_mesg(ask));
620 break;
621 case FDISK_ASKTYPE_WARN:
622 ui_warn(fdisk_ask_print_get_mesg(ask));
623 break;
624 case FDISK_ASKTYPE_MENU:
625 ask_menu(ask, (struct cfdisk *) data);
626 break;
627 default:
628 ui_warnx(_("internal error: unsupported dialog type %d"),
629 fdisk_ask_get_type(ask));
630 return -EINVAL;
631 }
632 return rc;
633 }
634
635 static int ui_end(void)
636 {
637 if (!ui_enabled)
638 return -EINVAL;
639
640 #if defined(HAVE_SLCURSES_H) || defined(HAVE_SLANG_SLCURSES_H)
641 SLsmg_gotorc(ui_lines - 1, 0);
642 SLsmg_refresh();
643 #else
644 mvcur(0, ui_cols - 1, ui_lines-1, 0);
645 #endif
646 curs_set(1);
647 nl();
648 endwin();
649 printf("\n");
650 ui_enabled = 0;
651 return 0;
652 }
653
654 static void ui_vprint_center(size_t line, int attrs, const char *fmt, va_list ap)
655 {
656 size_t width;
657 char *buf = NULL;
658
659 move(line, 0);
660 clrtoeol();
661
662 xvasprintf(&buf, fmt, ap);
663
664 width = mbs_safe_width(buf);
665 if (width > (size_t) ui_cols) {
666 char *p = strrchr(buf + ui_cols, ' ');
667 if (!p)
668 p = buf + ui_cols;
669 *p = '\0';
670 if (line + 1 >= ui_lines)
671 line--;
672 attron(attrs);
673 mvaddstr(line, 0, buf);
674 mvaddstr(line + 1, 0, p+1);
675 attroff(attrs);
676 } else {
677 attron(attrs);
678 mvaddstr(line, (ui_cols - width) / 2, buf);
679 attroff(attrs);
680 }
681 free(buf);
682 }
683
684 static void ui_center(size_t line, const char *fmt, ...)
685 {
686 va_list ap;
687 va_start(ap, fmt);
688 ui_vprint_center(line, 0, fmt, ap);
689 va_end(ap);
690 }
691
692 static void ui_warnx(const char *fmt, ...)
693 {
694 va_list ap;
695 va_start(ap, fmt);
696 if (ui_enabled)
697 ui_vprint_center(WARN_LINE,
698 colors_wanted() ? COLOR_PAIR(CFDISK_CL_WARNING) : 0,
699 fmt, ap);
700 else {
701 vfprintf(stderr, fmt, ap);
702 fputc('\n', stderr);
703 }
704 va_end(ap);
705 }
706
707 static void ui_warn(const char *fmt, ...)
708 {
709 char *fmt_m;
710 va_list ap;
711
712 xasprintf(&fmt_m, "%s: %m", fmt);
713
714 va_start(ap, fmt);
715 if (ui_enabled)
716 ui_vprint_center(WARN_LINE,
717 colors_wanted() ? COLOR_PAIR(CFDISK_CL_WARNING) : 0,
718 fmt_m, ap);
719 else {
720 vfprintf(stderr, fmt_m, ap);
721 fputc('\n', stderr);
722 }
723 va_end(ap);
724 free(fmt_m);
725 }
726
727 static void ui_clean_warn(void)
728 {
729 move(WARN_LINE, 0);
730 clrtoeol();
731 }
732
733 static int __attribute__((__noreturn__)) ui_errx(int rc, const char *fmt, ...)
734 {
735 va_list ap;
736 ui_end();
737
738 va_start(ap, fmt);
739 fprintf(stderr, "%s: ", program_invocation_short_name);
740 vfprintf(stderr, fmt, ap);
741 fputc('\n', stderr);
742 va_end(ap);
743
744 exit(rc);
745 }
746
747 static void ui_info(const char *fmt, ...)
748 {
749 va_list ap;
750 va_start(ap, fmt);
751 if (ui_enabled)
752 ui_vprint_center(INFO_LINE,
753 colors_wanted() ? COLOR_PAIR(CFDISK_CL_INFO) : 0,
754 fmt, ap);
755 else {
756 vfprintf(stdout, fmt, ap);
757 fputc('\n', stdout);
758 }
759 va_end(ap);
760 }
761
762 static void ui_clean_info(void)
763 {
764 move(INFO_LINE, 0);
765 clrtoeol();
766 }
767
768 static void ui_hint(const char *fmt, ...)
769 {
770 va_list ap;
771 va_start(ap, fmt);
772 if (ui_enabled)
773 ui_vprint_center(HINT_LINE, A_BOLD, fmt, ap);
774 else {
775 vfprintf(stdout, fmt, ap);
776 fputc('\n', stdout);
777 }
778 va_end(ap);
779 }
780
781 static void ui_clean_hint(void)
782 {
783 move(HINT_LINE, 0);
784 clrtoeol();
785 }
786
787 static void die_on_signal(int dummy __attribute__((__unused__)))
788 {
789 DBG(MISC, ul_debug("die on signal."));
790 ui_end();
791 exit(EXIT_FAILURE);
792 }
793
794 static void resize_on_signal(int dummy __attribute__((__unused__)))
795 {
796 DBG(MISC, ul_debug("resize on signal."));
797 ui_resize = 1;
798 }
799
800 static void menu_refresh_size(struct cfdisk *cf)
801 {
802 if (cf->menu && cf->menu->nitems)
803 cf->menu->page_sz = (cf->menu->nitems / (ui_lines - 4)) ? ui_lines - 4 : 0;
804 }
805
806 static void menu_update_ignore(struct cfdisk *cf)
807 {
808 char ignore[128] = { 0 };
809 int i = 0;
810 struct cfdisk_menu *m;
811 struct cfdisk_menuitem *d, *org = NULL;
812 size_t idx;
813
814 assert(cf);
815 assert(cf->menu);
816 assert(cf->menu->ignore_cb);
817
818 m = cf->menu;
819 DBG(MENU, ul_debug("update menu ignored keys"));
820
821 i = m->ignore_cb(cf, ignore, sizeof(ignore));
822 ignore[i] = '\0';
823
824 /* return if no change */
825 if ((!m->ignore && !*ignore)
826 || (m->ignore && *ignore && strcmp(m->ignore, ignore) == 0)) {
827 return;
828 }
829
830 if (!m->prefkey)
831 org = menu_get_menuitem(cf, m->idx);
832
833 free(m->ignore);
834 m->ignore = xstrdup(ignore);
835 m->nitems = 0;
836
837 for (d = m->items; d->name; d++) {
838 if (m->ignore && strchr(m->ignore, d->key))
839 continue;
840 m->nitems++;
841 }
842
843 DBG(MENU, ul_debug("update menu preferred keys"));
844
845 /* refresh menu index to be at the same menuitem or go to the first */
846 if (org && menu_get_menuitem_by_key(cf, org->key, &idx))
847 m->idx = idx;
848 else if (m->prefkey && menu_get_menuitem_by_key(cf, m->prefkey, &idx))
849 m->idx = idx;
850 else
851 m->idx = 0;
852
853 menu_refresh_size(cf);
854 }
855
856 static struct cfdisk_menu *menu_push(
857 struct cfdisk *cf,
858 struct cfdisk_menuitem *items)
859 {
860 struct cfdisk_menu *m = xcalloc(1, sizeof(*m));
861 struct cfdisk_menuitem *d;
862
863 assert(cf);
864
865 DBG(MENU, ul_debug("new menu"));
866
867 m->prev = cf->menu;
868 m->items = items;
869
870 for (d = m->items; d->name; d++) {
871 const char *name = _(d->name);
872 size_t len = mbs_safe_width(name);
873 if (len > m->width)
874 m->width = len;
875 m->nitems++;
876 }
877
878 cf->menu = m;
879
880 menu_refresh_size(cf);
881 return m;
882 }
883
884 static struct cfdisk_menu *menu_pop(struct cfdisk *cf)
885 {
886 struct cfdisk_menu *m = NULL;
887
888 assert(cf);
889
890 DBG(MENU, ul_debug("pop menu"));
891
892 if (cf->menu) {
893 m = cf->menu->prev;
894 free(cf->menu->ignore);
895 free(cf->menu->title);
896 free(cf->menu);
897 }
898 cf->menu = m;
899 return cf->menu;
900 }
901
902 static void menu_set_title(struct cfdisk_menu *m, const char *title)
903 {
904 char *str = NULL;
905
906 if (title) {
907 size_t len = mbs_safe_width(title);
908 if (len + MENU_TITLE_PADDING > m->width)
909 m->width = len + MENU_TITLE_PADDING;
910 str = xstrdup(title);
911 }
912 m->title = str;
913 }
914
915
916 static int ui_init(struct cfdisk *cf __attribute__((__unused__)))
917 {
918 struct sigaction sa;
919
920 DBG(UI, ul_debug("init"));
921
922 /* setup SIGCHLD handler */
923 sigemptyset(&sa.sa_mask);
924 sa.sa_flags = 0;
925 sa.sa_handler = die_on_signal;
926 sigaction(SIGINT, &sa, NULL);
927 sigaction(SIGTERM, &sa, NULL);
928
929 sa.sa_handler = resize_on_signal;
930 sigaction(SIGWINCH, &sa, NULL);
931
932 ui_enabled = 1;
933 initscr();
934
935 #ifdef HAVE_USE_DEFAULT_COLORS
936 if (colors_wanted() && has_colors()) {
937 size_t i;
938
939 start_color();
940 use_default_colors();
941 for (i = 1; i < ARRAY_SIZE(color_pairs); i++) /* yeah, start from 1! */
942 init_pair(i, color_pairs[i][0], color_pairs[i][1]);
943 }
944 #else
945 colors_off();
946 #endif
947
948 cbreak();
949 noecho();
950 nonl();
951 curs_set(0);
952 keypad(stdscr, TRUE);
953
954 return 0;
955 }
956
957 /* "[ string ]" */
958 #define MENU_H_ITEMWIDTH(m) ( MENU_H_PRESTR_SZ \
959 + MENU_H_SPADDING \
960 + (m)->width \
961 + MENU_H_SPADDING \
962 + MENU_H_POSTSTR_SZ)
963
964 #define MENU_V_ITEMWIDTH(m) (MENU_V_SPADDING + (m)->width + MENU_V_SPADDING)
965
966
967 static size_t menuitem_get_line(struct cfdisk *cf, size_t idx)
968 {
969 struct cfdisk_menu *m = cf->menu;
970
971 if (m->vertical) {
972 if (!m->page_sz) /* small menu */
973 return (ui_lines - (cf->menu->nitems + 1)) / 2 + idx;
974 return (idx % m->page_sz) + 1;
975 } else {
976 size_t len = MENU_H_ITEMWIDTH(m) + MENU_H_BETWEEN; /** item width */
977 size_t items = ui_cols / len; /* items per line */
978
979 if (items == 0)
980 return 0;
981 return MENU_START_LINE + ((idx / items));
982 }
983 }
984
985 static int menuitem_get_column(struct cfdisk *cf, size_t idx)
986 {
987 if (cf->menu->vertical) {
988 size_t nc = MENU_V_ITEMWIDTH(cf->menu);
989 if ((size_t) ui_cols <= nc)
990 return 0;
991 return (ui_cols - nc) / 2;
992 } else {
993 size_t len = MENU_H_ITEMWIDTH(cf->menu) + MENU_H_BETWEEN; /* item width */
994 size_t items = ui_cols / len; /* items per line */
995 size_t extra = items < cf->menu->nitems ? /* extra space on line */
996 ui_cols % len : /* - multi-line menu */
997 ui_cols - (cf->menu->nitems * len); /* - one line menu */
998
999 if (items == 0)
1000 return 0; /* hmm... no space */
1001
1002 extra += MENU_H_BETWEEN; /* add padding after last item to extra */
1003
1004 if (idx < items)
1005 return (idx * len) + (extra / 2);
1006 return ((idx % items) * len) + (extra / 2);
1007 }
1008 }
1009
1010 static int menuitem_on_page(struct cfdisk *cf, size_t idx)
1011 {
1012 struct cfdisk_menu *m = cf->menu;
1013
1014 if (m->page_sz == 0 ||
1015 m->idx / m->page_sz == idx / m->page_sz)
1016 return 1;
1017 return 0;
1018 }
1019
1020 static struct cfdisk_menuitem *menu_get_menuitem(struct cfdisk *cf, size_t idx)
1021 {
1022 struct cfdisk_menuitem *d;
1023 size_t i;
1024
1025 for (i = 0, d = cf->menu->items; d->name; d++) {
1026 if (cf->menu->ignore && strchr(cf->menu->ignore, d->key))
1027 continue;
1028 if (i++ == idx)
1029 return d;
1030 }
1031
1032 return NULL;
1033 }
1034
1035 static struct cfdisk_menuitem *menu_get_menuitem_by_key(struct cfdisk *cf,
1036 int key, size_t *idx)
1037 {
1038 struct cfdisk_menuitem *d;
1039
1040 for (*idx = 0, d = cf->menu->items; d->name; d++) {
1041 if (cf->menu->ignore && strchr(cf->menu->ignore, d->key))
1042 continue;
1043 if (key == d->key)
1044 return d;
1045 (*idx)++;
1046 }
1047
1048 return NULL;
1049 }
1050
1051 static void ui_draw_menuitem(struct cfdisk *cf,
1052 struct cfdisk_menuitem *d,
1053 size_t idx)
1054 {
1055 char *buf, *ptr;
1056 const char *name;
1057 size_t width;
1058 const size_t buf_sz = 80 * MB_CUR_MAX;
1059 int ln, cl, vert = cf->menu->vertical;
1060
1061 if (!menuitem_on_page(cf, idx))
1062 return; /* no visible item */
1063 ln = menuitem_get_line(cf, idx);
1064 cl = menuitem_get_column(cf, idx);
1065
1066 ptr = buf = xmalloc(buf_sz);
1067 /* string width */
1068 if (vert) {
1069 width = cf->menu->width + MENU_V_SPADDING;
1070 memset(ptr, ' ', MENU_V_SPADDING);
1071 ptr += MENU_V_SPADDING;
1072 } else
1073 width = MENU_H_SPADDING + cf->menu->width + MENU_H_SPADDING;
1074
1075 name = _(d->name);
1076 mbsalign(name, ptr, buf_sz, &width,
1077 vert ? MBS_ALIGN_LEFT : MBS_ALIGN_CENTER,
1078 0);
1079
1080 DBG(MENU, ul_debug("menuitem: cl=%d, ln=%d, item='%s'",
1081 cl, ln, buf));
1082
1083 if (vert) {
1084 mvaddch(ln, cl - 1, ACS_VLINE);
1085 mvaddch(ln, cl + MENU_V_ITEMWIDTH(cf->menu), ACS_VLINE);
1086 }
1087
1088 if (cf->menu->idx == idx)
1089 standout();
1090
1091 if (vert)
1092 mvprintw(ln, cl, "%s", buf);
1093 else
1094 mvprintw(ln, cl, "%s%s%s", MENU_H_PRESTR, buf, MENU_H_POSTSTR);
1095 free(buf);
1096
1097 if (cf->menu->idx == idx) {
1098 standend();
1099 if (d->desc)
1100 ui_hint(_(d->desc));
1101 }
1102 }
1103
1104 static void ui_clean_menu(struct cfdisk *cf)
1105 {
1106 size_t i;
1107 size_t lastline;
1108 struct cfdisk_menu *m = cf->menu;
1109 size_t ln = menuitem_get_line(cf, 0);
1110
1111 if (m->vertical)
1112 lastline = ln + (m->page_sz ? m->page_sz : m->nitems);
1113 else
1114 lastline = menuitem_get_line(cf, m->nitems);
1115
1116 for (i = ln; i <= lastline; i++) {
1117 move(i, 0);
1118 clrtoeol();
1119 DBG(MENU, ul_debug("clean_menu: line %zu", i));
1120 }
1121 if (m->vertical) {
1122 move(ln - 1, 0);
1123 clrtoeol();
1124 }
1125 ui_clean_hint();
1126 }
1127
1128 static void ui_draw_menu(struct cfdisk *cf)
1129 {
1130 struct cfdisk_menuitem *d;
1131 struct cfdisk_menu *m;
1132 size_t i = 0;
1133 size_t ln = menuitem_get_line(cf, 0);
1134 size_t nlines;
1135
1136 assert(cf);
1137 assert(cf->menu);
1138
1139 DBG(MENU, ul_debug("draw start"));
1140
1141 ui_clean_menu(cf);
1142 m = cf->menu;
1143
1144 if (m->vertical)
1145 nlines = m->page_sz ? m->page_sz : m->nitems;
1146 else
1147 nlines = menuitem_get_line(cf, m->nitems);
1148
1149 if (m->ignore_cb)
1150 menu_update_ignore(cf);
1151 i = 0;
1152 while ((d = menu_get_menuitem(cf, i)))
1153 ui_draw_menuitem(cf, d, i++);
1154
1155 if (m->vertical) {
1156 size_t cl = menuitem_get_column(cf, 0);
1157 size_t curpg = m->page_sz ? m->idx / m->page_sz : 0;
1158
1159 /* corners and horizontal lines */
1160 mvaddch(ln - 1, cl - 1, ACS_ULCORNER);
1161 mvaddch(ln + nlines, cl - 1, ACS_LLCORNER);
1162
1163 for (i = 0; i < MENU_V_ITEMWIDTH(m); i++) {
1164 mvaddch(ln - 1, cl + i, ACS_HLINE);
1165 mvaddch(ln + nlines, cl + i, ACS_HLINE);
1166 }
1167
1168 mvaddch(ln - 1, cl + i, ACS_URCORNER);
1169 mvaddch(ln + nlines, cl + i, ACS_LRCORNER);
1170
1171 /* draw also lines around empty lines on last page */
1172 if (m->page_sz &&
1173 m->nitems / m->page_sz == m->idx / m->page_sz) {
1174 for (i = m->nitems % m->page_sz + 1; i <= m->page_sz; i++) {
1175 mvaddch(i, cl - 1, ACS_VLINE);
1176 mvaddch(i, cl + MENU_V_ITEMWIDTH(m), ACS_VLINE);
1177 }
1178 }
1179 if (m->title) {
1180 attron(A_BOLD);
1181 mvprintw(ln - 1, cl, " %s ", m->title);
1182 attroff(A_BOLD);
1183 }
1184 if (curpg != 0)
1185 mvaddch(ln - 1, cl + MENU_V_ITEMWIDTH(m) - 2, ACS_UARROW);
1186 if (m->page_sz && curpg < m->nitems / m->page_sz)
1187 mvaddch(ln + nlines, cl + MENU_V_ITEMWIDTH(m) - 2, ACS_DARROW);
1188 }
1189
1190 DBG(MENU, ul_debug("draw end."));
1191 }
1192
1193 inline static int extra_insert_pair(struct cfdisk_line *l, const char *name, const char *data)
1194 {
1195 struct libscols_line *lsl;
1196 int rc;
1197
1198 assert(l);
1199 assert(l->extra);
1200
1201 if (!data || !*data)
1202 return 0;
1203
1204 lsl = scols_table_new_line(l->extra, NULL);
1205 if (!lsl)
1206 return -ENOMEM;
1207
1208 rc = scols_line_set_data(lsl, 0, name);
1209 if (!rc)
1210 rc = scols_line_set_data(lsl, 1, data);
1211
1212 return rc;
1213 }
1214
1215 #ifndef HAVE_LIBMOUNT
1216 static char *get_mountpoint( struct cfdisk *cf __attribute__((unused)),
1217 const char *tagname __attribute__((unused)),
1218 const char *tagdata __attribute__((unused)))
1219 {
1220 return NULL;
1221 }
1222 #else
1223 static char *get_mountpoint(struct cfdisk *cf, const char *tagname, const char *tagdata)
1224 {
1225 struct libmnt_fs *fs = NULL;
1226 char *target = NULL;
1227 int mounted = 0;
1228
1229 assert(tagname);
1230 assert(tagdata);
1231
1232 DBG(UI, ul_debug("asking for mountpoint [%s=%s]", tagname, tagdata));
1233
1234 if (!cf->mntcache)
1235 cf->mntcache = mnt_new_cache();
1236
1237 /* 1st try between mounted filesystems */
1238 if (!cf->mtab) {
1239 cf->mtab = mnt_new_table();
1240 if (cf->mtab) {
1241 mnt_table_set_cache(cf->mtab, cf->mntcache);
1242 mnt_table_parse_mtab(cf->mtab, NULL);
1243 }
1244 }
1245
1246 if (cf->mtab)
1247 fs = mnt_table_find_tag(cf->mtab, tagname, tagdata, MNT_ITER_FORWARD);
1248
1249 /* 2nd try fstab */
1250 if (!fs) {
1251 if (!cf->fstab) {
1252 cf->fstab = mnt_new_table();
1253 if (cf->fstab) {
1254 mnt_table_set_cache(cf->fstab, cf->mntcache);
1255 mnt_table_parse_fstab(cf->fstab, NULL);
1256 }
1257 }
1258 if (cf->fstab)
1259 fs = mnt_table_find_tag(cf->fstab, tagname, tagdata, MNT_ITER_FORWARD);
1260 } else
1261 mounted = 1;
1262
1263 if (fs) {
1264 if (mounted)
1265 xasprintf(&target, _("%s (mounted)"), mnt_fs_get_target(fs));
1266 else
1267 target = xstrdup(mnt_fs_get_target(fs));
1268 }
1269
1270 return target;
1271 }
1272 #endif /* HAVE_LIBMOUNT */
1273
1274 static void extra_prepare_data(struct cfdisk *cf)
1275 {
1276 struct fdisk_partition *pa = get_current_partition(cf);
1277 struct cfdisk_line *l = &cf->lines[cf->lines_idx];
1278 char *data = NULL;
1279 char *mountpoint = NULL;
1280
1281 DBG(UI, ul_debug("preparing extra data"));
1282
1283 /* string data should not equal an empty string */
1284 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_NAME, &data) && data) {
1285 extra_insert_pair(l, _("Partition name:"), data);
1286 if (!mountpoint)
1287 mountpoint = get_mountpoint(cf, "PARTLABEL", data);
1288 free(data);
1289 }
1290
1291 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_UUID, &data) && data) {
1292 extra_insert_pair(l, _("Partition UUID:"), data);
1293 if (!mountpoint)
1294 mountpoint = get_mountpoint(cf, "PARTUUID", data);
1295 free(data);
1296 }
1297
1298 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_TYPE, &data) && data) {
1299 char *code = NULL, *type = NULL;
1300
1301 fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_TYPEID, &code);
1302 xasprintf(&type, "%s (%s)", data, code);
1303
1304 extra_insert_pair(l, _("Partition type:"), type);
1305 free(data);
1306 free(code);
1307 free(type);
1308 }
1309
1310 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_ATTR, &data) && data) {
1311 extra_insert_pair(l, _("Attributes:"), data);
1312 free(data);
1313 }
1314
1315 /* for numeric data, only show non-zero rows */
1316 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_BSIZE, &data) && data) {
1317 if (atoi(data))
1318 extra_insert_pair(l, "BSIZE:", data);
1319 free(data);
1320 }
1321
1322 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_CPG, &data) && data) {
1323 if (atoi(data))
1324 extra_insert_pair(l, "CPG:", data);
1325 free(data);
1326 }
1327
1328 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_FSIZE, &data) && data) {
1329 if (atoi(data))
1330 extra_insert_pair(l, "FSIZE:", data);
1331 free(data);
1332 }
1333
1334 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_FSUUID, &data) && data) {
1335 extra_insert_pair(l, _("Filesystem UUID:"), data);
1336 if (!mountpoint)
1337 mountpoint = get_mountpoint(cf, "UUID", data);
1338 free(data);
1339 }
1340
1341 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_FSLABEL, &data) && data) {
1342 extra_insert_pair(l, _("Filesystem LABEL:"), data);
1343 if (!mountpoint)
1344 mountpoint = get_mountpoint(cf, "LABEL", data);
1345 free(data);
1346 }
1347 if (!fdisk_partition_to_string(pa, cf->cxt, FDISK_FIELD_FSTYPE, &data) && data) {
1348 extra_insert_pair(l, _("Filesystem:"), data);
1349 free(data);
1350 }
1351
1352 if (mountpoint) {
1353 extra_insert_pair(l, _("Mountpoint:"), mountpoint);
1354 free(mountpoint);
1355 }
1356 }
1357
1358 static int ui_draw_extra(struct cfdisk *cf)
1359 {
1360 WINDOW *win_ex;
1361 int wline = 1;
1362 struct cfdisk_line *ln = &cf->lines[cf->lines_idx];
1363 char *tbstr = NULL, *end;
1364 int win_ex_start_line, win_height, tblen;
1365 int ndatalines;
1366
1367 if (!cf->show_extra)
1368 return 0;
1369
1370 DBG(UI, ul_debug("draw extra"));
1371
1372 assert(ln->extra);
1373
1374 if (cf->act_win) {
1375 wclear(cf->act_win);
1376 touchwin(stdscr);
1377 }
1378
1379 if (scols_table_is_empty(ln->extra)) {
1380 extra_prepare_data(cf);
1381 if (scols_table_is_empty(ln->extra))
1382 return 0;
1383 }
1384
1385 ndatalines = fdisk_table_get_nents(cf->table) + 1;
1386
1387 /* nents + header + one free line */
1388 win_ex_start_line = TABLE_START_LINE + ndatalines;
1389 win_height = MENU_START_LINE - win_ex_start_line;
1390 tblen = scols_table_get_nlines(ln->extra);
1391
1392 /* we can't get a single line of data under the partlist*/
1393 if (win_height < 3)
1394 return 1;
1395
1396 /* number of data lines + 2 for top/bottom lines */
1397 win_height = win_height < tblen + 2 ? win_height : tblen + 2;
1398
1399 if ((size_t) win_ex_start_line + win_height + 1 < MENU_START_LINE)
1400 win_ex_start_line = MENU_START_LINE - win_height;
1401
1402 win_ex = subwin(stdscr, win_height, ui_cols - 2, win_ex_start_line, 1);
1403
1404 scols_table_reduce_termwidth(ln->extra, 4);
1405 scols_print_table_to_string(ln->extra, &tbstr);
1406
1407 end = tbstr;
1408 while ((end = strchr(end, '\n')))
1409 *end++ = '\0';
1410
1411 box(win_ex, 0, 0);
1412
1413 end = tbstr;
1414 while (--win_height > 1) {
1415 mvwaddstr(win_ex, wline++, 1 /* window column*/, tbstr);
1416 tbstr += strlen(tbstr) + 1;
1417 }
1418 free(end);
1419
1420 if (ln->w)
1421 delwin(ln->w);
1422
1423 DBG(UI, ul_debug("draw window: %p", win_ex));
1424 touchwin(stdscr);
1425 wrefresh(win_ex);
1426
1427 cf->act_win = ln->w = win_ex;
1428 return 0;
1429 }
1430
1431 static void ui_menu_goto(struct cfdisk *cf, int where)
1432 {
1433 struct cfdisk_menuitem *d;
1434 size_t old;
1435
1436 /* stop and begin/end for vertical menus */
1437 if (cf->menu->vertical) {
1438 if (where < 0)
1439 where = 0;
1440 else if (where > (int) cf->menu->nitems - 1)
1441 where = cf->menu->nitems - 1;
1442 } else {
1443 /* continue from begin/end */
1444 if (where < 0)
1445 where = cf->menu->nitems - 1;
1446 else if ((size_t) where > cf->menu->nitems - 1)
1447 where = 0;
1448 }
1449 if ((size_t) where == cf->menu->idx)
1450 return;
1451
1452 ui_clean_info();
1453
1454 old = cf->menu->idx;
1455 cf->menu->idx = where;
1456
1457 if (!menuitem_on_page(cf, old)) {
1458 ui_draw_menu(cf);
1459 return;
1460 }
1461
1462 d = menu_get_menuitem(cf, old);
1463 ui_draw_menuitem(cf, d, old);
1464
1465 d = menu_get_menuitem(cf, where);
1466 ui_draw_menuitem(cf, d, where);
1467
1468 }
1469
1470 static int ui_menu_move(struct cfdisk *cf, int key)
1471 {
1472 struct cfdisk_menu *m;
1473
1474 assert(cf);
1475 assert(cf->menu);
1476
1477 if (key == (int) ERR)
1478 return 0; /* ignore errors */
1479
1480 m = cf->menu;
1481
1482 DBG(MENU, ul_debug("menu move key >%c<.", key));
1483
1484 if (m->vertical)
1485 {
1486 switch (key) {
1487 case KEY_DOWN:
1488 case '\016': /* ^N */
1489 case 'j': /* Vi-like alternative */
1490 ui_menu_goto(cf, m->idx + 1);
1491 return 0;
1492 case KEY_UP:
1493 case '\020': /* ^P */
1494 case 'k': /* Vi-like alternative */
1495 ui_menu_goto(cf, (int) m->idx - 1);
1496 return 0;
1497 case KEY_PPAGE:
1498 if (m->page_sz) {
1499 ui_menu_goto(cf, (int) m->idx - m->page_sz);
1500 return 0;
1501 }
1502 /* fallthrough */
1503 case KEY_HOME:
1504 ui_menu_goto(cf, 0);
1505 return 0;
1506 case KEY_NPAGE:
1507 if (m->page_sz) {
1508 ui_menu_goto(cf, m->idx + m->page_sz);
1509 return 0;
1510 }
1511 /* fallthrough */
1512 case KEY_END:
1513 ui_menu_goto(cf, m->nitems);
1514 return 0;
1515 }
1516 } else {
1517 switch (key) {
1518 case KEY_RIGHT:
1519 case '\t':
1520 ui_menu_goto(cf, m->idx + 1);
1521 return 0;
1522 case KEY_LEFT:
1523 #ifdef KEY_BTAB
1524 case KEY_BTAB:
1525 #endif
1526 ui_menu_goto(cf, (int) m->idx - 1);
1527 return 0;
1528 }
1529 }
1530
1531 if (key == '\014') { /* ^L refresh */
1532 ui_menu_resize(cf);
1533 return 0;
1534 }
1535
1536 DBG(MENU, ul_debug(" no menu move key"));
1537 return 1;
1538 }
1539
1540 /* but don't call me from ui_run(), this is for pop-up menus only */
1541 static void ui_menu_resize(struct cfdisk *cf)
1542 {
1543 DBG(MENU, ul_debug("menu resize/refresh"));
1544 resize();
1545 ui_clean_menu(cf);
1546 menu_refresh_size(cf);
1547 ui_draw_menu(cf);
1548 refresh();
1549 }
1550
1551 static int partition_on_page(struct cfdisk *cf, size_t i)
1552 {
1553 if (cf->page_sz == 0 ||
1554 cf->lines_idx / cf->page_sz == i / cf->page_sz)
1555 return 1;
1556 return 0;
1557 }
1558
1559 static void ui_draw_partition(struct cfdisk *cf, size_t i)
1560 {
1561 int ln = TABLE_START_LINE + 1 + i; /* skip table header */
1562 int cl = ARROW_CURSOR_WIDTH; /* we need extra space for cursor */
1563 int cur = cf->lines_idx == i;
1564 size_t curpg = 0;
1565
1566 if (cf->page_sz) {
1567 if (!partition_on_page(cf, i))
1568 return;
1569 ln = TABLE_START_LINE + (i % cf->page_sz) + 1;
1570 curpg = cf->lines_idx / cf->page_sz;
1571 }
1572
1573 DBG(UI, ul_debug(
1574 "draw partition %zu [page_sz=%zu, "
1575 "line=%d, idx=%zu]",
1576 i, cf->page_sz, ln, cf->lines_idx));
1577
1578 if (cur) {
1579 attron(A_REVERSE);
1580 mvaddstr(ln, 0, ARROW_CURSOR_STRING);
1581 mvaddstr(ln, cl, cf->lines[i + 1].data);
1582 attroff(A_REVERSE);
1583 } else {
1584 int at = 0;
1585
1586 if (colors_wanted() && is_freespace(cf, i)) {
1587 attron(COLOR_PAIR(CFDISK_CL_FREESPACE));
1588 at = 1;
1589 }
1590 mvaddstr(ln, 0, ARROW_CURSOR_DUMMY);
1591 mvaddstr(ln, cl, cf->lines[i + 1].data);
1592 if (at)
1593 attroff(COLOR_PAIR(CFDISK_CL_FREESPACE));
1594 }
1595
1596 if ((size_t) ln == MENU_START_LINE - 1 &&
1597 cf->page_sz && curpg < cf->nlines / cf->page_sz) {
1598 if (cur)
1599 attron(A_REVERSE);
1600 mvaddch(ln, ui_cols - 1, ACS_DARROW);
1601 mvaddch(ln, 0, ACS_DARROW);
1602 if (cur)
1603 attroff(A_REVERSE);
1604 }
1605
1606 }
1607
1608 static int ui_draw_table(struct cfdisk *cf)
1609 {
1610 int cl = ARROW_CURSOR_WIDTH;
1611 size_t i, nparts = fdisk_table_get_nents(cf->table);
1612 size_t curpg = cf->page_sz ? cf->lines_idx / cf->page_sz : 0;
1613
1614 DBG(UI, ul_debug("draw table"));
1615
1616 for (i = TABLE_START_LINE; i <= TABLE_START_LINE + cf->page_sz; i++) {
1617 move(i, 0);
1618 clrtoeol();
1619 }
1620
1621 if (nparts == 0 || (size_t) cf->lines_idx > nparts - 1)
1622 cf->lines_idx = nparts ? nparts - 1 : 0;
1623
1624 /* print header */
1625 attron(A_BOLD);
1626 mvaddstr(TABLE_START_LINE, cl, cf->lines[0].data);
1627 attroff(A_BOLD);
1628
1629 /* print partitions */
1630 for (i = 0; i < nparts; i++)
1631 ui_draw_partition(cf, i);
1632
1633 if (curpg != 0) {
1634 mvaddch(TABLE_START_LINE, ui_cols - 1, ACS_UARROW);
1635 mvaddch(TABLE_START_LINE, 0, ACS_UARROW);
1636 }
1637 if (cf->page_sz && curpg < cf->nlines / cf->page_sz) {
1638 mvaddch(MENU_START_LINE - 1, ui_cols - 1, ACS_DARROW);
1639 mvaddch(MENU_START_LINE - 1, 0, ACS_DARROW);
1640 }
1641 return 0;
1642 }
1643
1644 static int ui_table_goto(struct cfdisk *cf, int where)
1645 {
1646 size_t old;
1647 size_t nparts = fdisk_table_get_nents(cf->table);
1648
1649 DBG(UI, ul_debug("goto table %d", where));
1650
1651 if (where < 0)
1652 where = 0;
1653 else if ((size_t) where > nparts - 1)
1654 where = nparts - 1;
1655
1656 if ((size_t) where == cf->lines_idx)
1657 return 0;
1658
1659 old = cf->lines_idx;
1660 cf->lines_idx = where;
1661
1662 if (!partition_on_page(cf, old) ||!partition_on_page(cf, where))
1663 ui_draw_table(cf);
1664 else {
1665 ui_draw_partition(cf, old); /* cleanup old */
1666 ui_draw_partition(cf, where); /* draw new */
1667 }
1668 ui_clean_info();
1669 ui_draw_menu(cf);
1670 ui_draw_extra(cf);
1671 refresh();
1672
1673 return 0;
1674 }
1675
1676 static int ui_refresh(struct cfdisk *cf)
1677 {
1678 struct fdisk_label *lb;
1679 char *id = NULL;
1680 uint64_t bytes = fdisk_get_nsectors(cf->cxt) * fdisk_get_sector_size(cf->cxt);
1681 char *strsz;
1682
1683 if (!ui_enabled)
1684 return -EINVAL;
1685
1686 strsz = size_to_human_string(SIZE_SUFFIX_SPACE
1687 | SIZE_SUFFIX_3LETTER, bytes);
1688
1689 lb = fdisk_get_label(cf->cxt, NULL);
1690 assert(lb);
1691
1692 clear();
1693
1694 /* header */
1695 attron(A_BOLD);
1696 ui_center(0, _("Disk: %s"), fdisk_get_devname(cf->cxt));
1697 attroff(A_BOLD);
1698 ui_center(1, _("Size: %s, %ju bytes, %ju sectors"),
1699 strsz, bytes, (uintmax_t) fdisk_get_nsectors(cf->cxt));
1700 if (fdisk_get_disklabel_id(cf->cxt, &id) == 0 && id)
1701 ui_center(2, _("Label: %s, identifier: %s"),
1702 fdisk_label_get_name(lb), id);
1703 else
1704 ui_center(2, _("Label: %s"), fdisk_label_get_name(lb));
1705 free(strsz);
1706
1707 ui_draw_table(cf);
1708 ui_draw_menu(cf);
1709 refresh();
1710 return 0;
1711 }
1712
1713 static ssize_t ui_get_string(const char *prompt,
1714 const char *hint, char *buf, size_t len)
1715 {
1716 int ln = MENU_START_LINE, cl = 1;
1717 ssize_t rc = -1;
1718 struct mbs_editor *edit;
1719
1720 DBG(UI, ul_debug("ui get string"));
1721
1722 assert(buf);
1723 assert(len);
1724
1725 move(ln, 0);
1726 clrtoeol();
1727
1728 move(ln + 1, 0);
1729 clrtoeol();
1730
1731 if (prompt) {
1732 mvaddstr(ln, cl, (char *) prompt);
1733 cl += mbs_safe_width(prompt);
1734 }
1735
1736 edit = mbs_new_edit(buf, len, ui_cols - cl);
1737 if (!edit)
1738 goto done;
1739
1740 mbs_edit_goto(edit, MBS_EDIT_END);
1741
1742 if (hint)
1743 ui_hint(hint);
1744 else
1745 ui_clean_hint();
1746
1747 curs_set(1);
1748
1749 while (1) {
1750 wint_t c; /* we have fallback in widechar.h */
1751
1752 move(ln, cl);
1753 clrtoeol();
1754 mvaddstr(ln, cl, edit->buf);
1755 move(ln, cl + edit->cursor_cells);
1756 refresh();
1757
1758 #if !defined(HAVE_SLCURSES_H) && !defined(HAVE_SLANG_SLCURSES_H) && \
1759 defined(HAVE_LIBNCURSESW) && defined(HAVE_WIDECHAR)
1760 if (get_wch(&c) == ERR) {
1761 #else
1762 if ((c = getch()) == (wint_t) ERR) {
1763 #endif
1764 if (ui_resize) {
1765 resize();
1766 continue;
1767 }
1768 if (!isatty(STDIN_FILENO))
1769 exit(2);
1770 else
1771 goto done;
1772 }
1773
1774 DBG(UI, ul_debug("ui get string: key=%lc", c));
1775
1776 if (c == '\r' || c == '\n' || c == KEY_ENTER)
1777 break;
1778
1779 rc = 1;
1780
1781 switch (c) {
1782 case KEY_ESC:
1783 rc = -CFDISK_ERR_ESC;
1784 goto done;
1785 case KEY_LEFT:
1786 rc = mbs_edit_goto(edit, MBS_EDIT_LEFT);
1787 break;
1788 case KEY_RIGHT:
1789 rc = mbs_edit_goto(edit, MBS_EDIT_RIGHT);
1790 break;
1791 case KEY_END:
1792 rc = mbs_edit_goto(edit, MBS_EDIT_END);
1793 break;
1794 case KEY_HOME:
1795 rc = mbs_edit_goto(edit, MBS_EDIT_HOME);
1796 break;
1797 case KEY_UP:
1798 case KEY_DOWN:
1799 break;
1800 case KEY_DC:
1801 rc = mbs_edit_delete(edit);
1802 break;
1803 case '\b':
1804 case KEY_DELETE:
1805 case KEY_BACKSPACE:
1806 rc = mbs_edit_backspace(edit);
1807 break;
1808 default:
1809 rc = mbs_edit_insert(edit, c);
1810 break;
1811 }
1812 if (rc == 1)
1813 beep();
1814 }
1815
1816 rc = strlen(edit->buf); /* success */
1817 done:
1818 move(ln, 0);
1819 clrtoeol();
1820 curs_set(0);
1821 refresh();
1822 mbs_free_edit(edit);
1823
1824 return rc;
1825 }
1826
1827 static int ui_get_size(struct cfdisk *cf, /* context */
1828 const char *prompt, /* UI dialog string */
1829 uintmax_t *res, /* result in bytes */
1830 uintmax_t low, /* minimal size */
1831 uintmax_t up, /* maximal size */
1832 int *expsize) /* explicitly specified size */
1833 {
1834 char buf[128];
1835 uintmax_t user = 0;
1836 ssize_t rc;
1837 char *dflt = size_to_human_string(0, *res);
1838
1839 DBG(UI, ul_debug("get_size (default=%ju)", *res));
1840
1841 ui_clean_info();
1842
1843 snprintf(buf, sizeof(buf), "%s", dflt);
1844
1845 do {
1846 int pwr = 0, insec = 0;
1847
1848 rc = ui_get_string(prompt,
1849 _("May be followed by M for MiB, G for GiB, "
1850 "T for TiB, or S for sectors."),
1851 buf, sizeof(buf));
1852 ui_clean_warn();
1853
1854 if (rc == 0) {
1855 ui_warnx(_("Please, specify size."));
1856 continue; /* nothing specified */
1857 } else if (rc == -CFDISK_ERR_ESC)
1858 break; /* cancel dialog */
1859
1860 if (strcmp(buf, dflt) == 0)
1861 user = *res, rc = 0; /* no change, use default */
1862 else {
1863 size_t len = strlen(buf);
1864 if (buf[len - 1] == 'S' || buf[len - 1] == 's') {
1865 insec = 1;
1866 buf[len - 1] = '\0';
1867 }
1868 rc = parse_size(buf, &user, &pwr); /* parse */
1869 }
1870
1871 if (rc == 0) {
1872 DBG(UI, ul_debug("get_size user=%ju, power=%d, in-sectors=%s",
1873 user, pwr, insec ? "yes" : "no"));
1874 if (insec)
1875 user *= fdisk_get_sector_size(cf->cxt);
1876 if (user < low) {
1877 ui_warnx(_("Minimum size is %ju bytes."), low);
1878 rc = -ERANGE;
1879 }
1880 if (user > up && pwr && user < up + (1ULL << pwr * 10))
1881 /* ignore when the user specified size overflow
1882 * with in range specified by suffix (e.g. MiB) */
1883 user = up;
1884
1885 if (user > up) {
1886 ui_warnx(_("Maximum size is %ju bytes."), up);
1887 rc = -ERANGE;
1888 }
1889 if (rc == 0 && insec && expsize)
1890 *expsize = 1;
1891
1892 } else
1893 ui_warnx(_("Failed to parse size."));
1894 } while (rc != 0);
1895
1896 if (rc == 0)
1897 *res = user;
1898 free(dflt);
1899
1900 DBG(UI, ul_debug("get_size (result=%ju, rc=%zd)", *res, rc));
1901 return rc;
1902 }
1903
1904 static struct fdisk_parttype *ui_get_parttype(struct cfdisk *cf,
1905 struct fdisk_parttype *cur)
1906 {
1907 struct cfdisk_menuitem *d, *cm;
1908 size_t i = 0, nitems, idx = 0;
1909 struct fdisk_parttype *t = NULL;
1910 struct fdisk_label *lb;
1911 int codetypes = 0;
1912
1913 DBG(UI, ul_debug("asking for parttype."));
1914
1915 lb = fdisk_get_label(cf->cxt, NULL);
1916
1917 /* create cfdisk menu according to label types, note that the
1918 * last cm[] item has to be empty -- so nitems + 1 */
1919 nitems = fdisk_label_get_nparttypes(lb);
1920 if (!nitems)
1921 return NULL;
1922
1923 cm = xcalloc(nitems + 1, sizeof(struct cfdisk_menuitem));
1924 if (!cm)
1925 return NULL;
1926
1927 codetypes = fdisk_label_has_code_parttypes(lb);
1928
1929 for (i = 0; i < nitems; i++) {
1930 const struct fdisk_parttype *x = fdisk_label_get_parttype(lb, i);
1931 char *name;
1932
1933 cm[i].userdata = (void *) x;
1934 if (codetypes)
1935 xasprintf(&name, "%2x %s",
1936 fdisk_parttype_get_code(x),
1937 _(fdisk_parttype_get_name(x)));
1938 else {
1939 name = (char *) _(fdisk_parttype_get_name(x));
1940 cm[i].desc = fdisk_parttype_get_string(x);
1941 }
1942 cm[i].name = name;
1943 if (x == cur)
1944 idx = i;
1945 }
1946
1947 /* make the new menu active */
1948 menu_push(cf, cm);
1949 cf->menu->vertical = 1;
1950 cf->menu->idx = idx;
1951 menu_set_title(cf->menu, _("Select partition type"));
1952 ui_draw_menu(cf);
1953 refresh();
1954
1955 do {
1956 int key = getch();
1957
1958 if (ui_resize)
1959 ui_menu_resize(cf);
1960 if (ui_menu_move(cf, key) == 0)
1961 continue;
1962
1963 switch (key) {
1964 case KEY_ENTER:
1965 case '\n':
1966 case '\r':
1967 d = menu_get_menuitem(cf, cf->menu->idx);
1968 if (d)
1969 t = (struct fdisk_parttype *) d->userdata;
1970 goto done;
1971 case KEY_ESC:
1972 case 'q':
1973 case 'Q':
1974 goto done;
1975 }
1976 } while (1);
1977
1978 done:
1979 menu_pop(cf);
1980 if (codetypes) {
1981 for (i = 0; i < nitems; i++)
1982 free((char *) cm[i].name);
1983 }
1984 free(cm);
1985 DBG(UI, ul_debug("get parrtype done [type=%s] ", t ?
1986 fdisk_parttype_get_name(t) : NULL));
1987 return t;
1988 }
1989
1990 static int ui_script_read(struct cfdisk *cf)
1991 {
1992 struct fdisk_script *sc = NULL;
1993 char buf[PATH_MAX] = { 0 };
1994 int rc;
1995
1996 erase();
1997 rc = ui_get_string( _("Enter script file name: "),
1998 _("The script file will be applied to in-memory partition table."),
1999 buf, sizeof(buf));
2000 if (rc <= 0)
2001 return rc;
2002
2003 rc = -1;
2004 errno = 0;
2005 sc = fdisk_new_script_from_file(cf->cxt, buf);
2006 if (!sc && errno)
2007 ui_warn(_("Cannot open %s"), buf);
2008 else if (!sc)
2009 ui_warnx(_("Failed to parse script file %s"), buf);
2010 else if (fdisk_apply_script(cf->cxt, sc) != 0)
2011 ui_warnx(_("Failed to apply script %s"), buf);
2012 else
2013 rc = 0;
2014
2015 ui_clean_hint();
2016 fdisk_unref_script(sc);
2017 return rc;
2018 }
2019
2020 static int ui_script_write(struct cfdisk *cf)
2021 {
2022 struct fdisk_script *sc = NULL;
2023 char buf[PATH_MAX] = { 0 };
2024 FILE *f = NULL;
2025 int rc;
2026
2027 rc = ui_get_string( _("Enter script file name: "),
2028 _("The current in-memory partition table will be dumped to the file."),
2029 buf, sizeof(buf));
2030 if (rc <= 0)
2031 return rc;
2032
2033 rc = 0;
2034 sc = fdisk_new_script(cf->cxt);
2035 if (!sc) {
2036 ui_warn(_("Failed to allocate script handler"));
2037 goto done;
2038 }
2039
2040 rc = fdisk_script_read_context(sc, NULL);
2041 if (rc) {
2042 ui_warnx(_("Failed to read disk layout into script."));
2043 goto done;
2044 }
2045
2046 DBG(UI, ul_debug("writing dump into: '%s'", buf));
2047 f = fopen(buf, "w");
2048 if (!f) {
2049 ui_warn(_("Cannot open %s"), buf);
2050 rc = -errno;
2051 goto done;
2052 }
2053
2054 rc = fdisk_script_write_file(sc, f);
2055 if (!rc)
2056 ui_info(_("Disk layout successfully dumped."));
2057 done:
2058 if (rc)
2059 ui_warn(_("Failed to write script %s"), buf);
2060 if (f)
2061 fclose(f);
2062 fdisk_unref_script(sc);
2063 return rc;
2064 }
2065
2066 /* prints menu with libfdisk labels and waits for users response */
2067 static int ui_create_label(struct cfdisk *cf)
2068 {
2069 struct cfdisk_menuitem *d, *cm;
2070 int rc = 1, refresh_menu = 1;
2071 size_t i = 0, nitems;
2072 struct fdisk_label *lb = NULL;
2073
2074 assert(cf);
2075
2076 DBG(UI, ul_debug("asking for new disklabe."));
2077
2078 /* create cfdisk menu according to libfdisk labels, note that the
2079 * last cm[] item has to be empty -- so nitems + 1 */
2080 nitems = fdisk_get_nlabels(cf->cxt);
2081 cm = xcalloc(nitems + 1, sizeof(struct cfdisk_menuitem));
2082
2083 while (fdisk_next_label(cf->cxt, &lb) == 0) {
2084 if (fdisk_label_is_disabled(lb) ||
2085 fdisk_label_get_type(lb) == FDISK_DISKLABEL_BSD)
2086 continue;
2087 cm[i++].name = fdisk_label_get_name(lb);
2088 }
2089
2090 erase();
2091
2092 /* make the new menu active */
2093 menu_push(cf, cm);
2094 cf->menu->vertical = 1;
2095 menu_set_title(cf->menu, _("Select label type"));
2096
2097 if (!cf->zero_start)
2098 ui_info(_("Device does not contain a recognized partition table."));
2099
2100
2101 do {
2102 int key;
2103
2104 if (refresh_menu) {
2105 ui_draw_menu(cf);
2106 ui_hint(_("Select a type to create a new label or press 'L' to load script file."));
2107 refresh();
2108 refresh_menu = 0;
2109 }
2110
2111 key = getch();
2112
2113 if (ui_resize)
2114 ui_menu_resize(cf);
2115 if (ui_menu_move(cf, key) == 0)
2116 continue;
2117 switch (key) {
2118 case KEY_ENTER:
2119 case '\n':
2120 case '\r':
2121 d = menu_get_menuitem(cf, cf->menu->idx);
2122 if (d)
2123 rc = fdisk_create_disklabel(cf->cxt, d->name);
2124 goto done;
2125 case KEY_ESC:
2126 case 'q':
2127 case 'Q':
2128 goto done;
2129 case 'l':
2130 case 'L':
2131 rc = ui_script_read(cf);
2132 if (rc == 0)
2133 goto done;
2134 refresh_menu = 1;
2135 break;
2136 }
2137 } while (1);
2138
2139 done:
2140 menu_pop(cf);
2141 free(cm);
2142 DBG(UI, ul_debug("create label done [rc=%d] ", rc));
2143 return rc;
2144 }
2145
2146
2147 static int ui_help(void)
2148 {
2149 size_t i;
2150 static const char *help[] = {
2151 N_("This is cfdisk, a curses-based disk partitioning program."),
2152 N_("It lets you create, delete, and modify partitions on a block device."),
2153 " ",
2154 N_("Command Meaning"),
2155 N_("------- -------"),
2156 N_(" b Toggle bootable flag of the current partition"),
2157 N_(" d Delete the current partition"),
2158 N_(" h Print this screen"),
2159 N_(" n Create new partition from free space"),
2160 N_(" q Quit program without writing partition table"),
2161 N_(" s Fix partitions order (only when in disarray)"),
2162 N_(" t Change the partition type"),
2163 N_(" u Dump disk layout to sfdisk compatible script file"),
2164 N_(" W Write partition table to disk (you must enter uppercase W);"),
2165 N_(" since this might destroy data on the disk, you must either"),
2166 N_(" confirm or deny the write by entering 'yes' or 'no'"),
2167 N_(" x Display/hide extra information about a partition"),
2168 N_("Up Arrow Move cursor to the previous partition"),
2169 N_("Down Arrow Move cursor to the next partition"),
2170 N_("Left Arrow Move cursor to the previous menu item"),
2171 N_("Right Arrow Move cursor to the next menu item"),
2172 " ",
2173 N_("Note: All of the commands can be entered with either upper or lower"),
2174 N_("case letters (except for Write)."),
2175 " ",
2176 N_("Use lsblk(8) or partx(8) to see more details about the device."),
2177 " ",
2178 " ",
2179 "Copyright (C) 2014-2017 Karel Zak <kzak@redhat.com>"
2180 };
2181
2182 erase();
2183 for (i = 0; i < ARRAY_SIZE(help); i++)
2184 mvaddstr(i, 1, _(help[i]));
2185
2186 ui_info(_("Press a key to continue."));
2187
2188 getch();
2189 return 0;
2190 }
2191
2192 /* TODO: use @sz, now 128bytes */
2193 static int main_menu_ignore_keys(struct cfdisk *cf, char *ignore,
2194 size_t sz __attribute__((__unused__)))
2195 {
2196 struct fdisk_partition *pa = get_current_partition(cf);
2197 size_t i = 0;
2198
2199 if (!pa)
2200 return 0;
2201 if (fdisk_partition_is_freespace(pa)) {
2202 ignore[i++] = 'd'; /* delete */
2203 ignore[i++] = 't'; /* set type */
2204 ignore[i++] = 'b'; /* set bootable */
2205 ignore[i++] = 'r'; /* resize */
2206 cf->menu->prefkey = 'n';
2207 } else {
2208 cf->menu->prefkey = 'q';
2209 ignore[i++] = 'n';
2210 if (!fdisk_is_label(cf->cxt, DOS) &&
2211 !fdisk_is_label(cf->cxt, SGI))
2212 ignore[i++] = 'b';
2213 }
2214
2215 if (!cf->wrong_order)
2216 ignore[i++] = 's';
2217
2218 if (fdisk_is_readonly(cf->cxt))
2219 ignore[i++] = 'W';
2220
2221 return i;
2222 }
2223
2224
2225 /* returns: error: < 0, success: 0, quit: 1 */
2226 static int main_menu_action(struct cfdisk *cf, int key)
2227 {
2228 size_t n;
2229 int ref = 0, rc, org_order = cf->wrong_order;
2230 const char *info = NULL, *warn = NULL;
2231 struct fdisk_partition *pa;
2232
2233 assert(cf);
2234 assert(cf->cxt);
2235 assert(cf->menu);
2236
2237 if (key == 0) {
2238 struct cfdisk_menuitem *d = menu_get_menuitem(cf, cf->menu->idx);
2239 if (!d)
2240 return 0;
2241 key = d->key;
2242
2243 } else if (key != 'w' && key != 'W')
2244 key = tolower(key); /* case insensitive except 'W'rite */
2245
2246 DBG(MENU, ul_debug("main menu action: key=%c", key));
2247
2248 if (cf->menu->ignore && strchr(cf->menu->ignore, key)) {
2249 DBG(MENU, ul_debug(" ignore '%c'", key));
2250 return 0;
2251 }
2252
2253 pa = get_current_partition(cf);
2254 if (!pa)
2255 return -EINVAL;
2256 n = fdisk_partition_get_partno(pa);
2257
2258 DBG(MENU, ul_debug("menu action on %p", pa));
2259 ui_clean_hint();
2260 ui_clean_info();
2261
2262 switch (key) {
2263 case 'b': /* Bootable flag */
2264 {
2265 int fl = fdisk_is_label(cf->cxt, DOS) ? DOS_FLAG_ACTIVE :
2266 fdisk_is_label(cf->cxt, SGI) ? SGI_FLAG_BOOT : 0;
2267
2268 if (fl && fdisk_toggle_partition_flag(cf->cxt, n, fl))
2269 warn = _("Could not toggle the flag.");
2270 else if (fl)
2271 ref = 1;
2272 break;
2273 }
2274 #ifdef KEY_DC
2275 case KEY_DC:
2276 #endif
2277 case 'd': /* Delete */
2278 if (fdisk_delete_partition(cf->cxt, n) != 0)
2279 warn = _("Could not delete partition %zu.");
2280 else
2281 info = _("Partition %zu has been deleted.");
2282 ref = 1;
2283 break;
2284 case 'h': /* Help */
2285 case '?':
2286 ui_help();
2287 ref = 1;
2288 break;
2289 case 'n': /* New */
2290 {
2291 uint64_t start, size, dflt_size, secs, max_size;
2292 struct fdisk_partition *npa; /* the new partition */
2293 int expsize = 0; /* size specified explicitly in sectors */
2294
2295 if (!fdisk_partition_is_freespace(pa) || !fdisk_partition_has_start(pa))
2296 return -EINVAL;
2297
2298 /* free space range */
2299 start = fdisk_partition_get_start(pa);
2300 size = max_size = dflt_size = fdisk_partition_get_size(pa) * fdisk_get_sector_size(cf->cxt);
2301
2302 if (ui_get_size(cf, _("Partition size: "), &size,
2303 fdisk_get_sector_size(cf->cxt),
2304 max_size, &expsize) == -CFDISK_ERR_ESC)
2305 break;
2306
2307 secs = size / fdisk_get_sector_size(cf->cxt);
2308
2309 npa = fdisk_new_partition();
2310 if (!npa)
2311 return -ENOMEM;
2312
2313 if (dflt_size == size) /* default is to fillin all free space */
2314 fdisk_partition_end_follow_default(npa, 1);
2315 else
2316 fdisk_partition_set_size(npa, secs);
2317
2318 if (expsize)
2319 fdisk_partition_size_explicit(pa, 1);
2320
2321 fdisk_partition_set_start(npa, start);
2322 fdisk_partition_partno_follow_default(npa, 1);
2323 /* add to disk label -- libfdisk will ask for missing details */
2324 rc = fdisk_add_partition(cf->cxt, npa, NULL);
2325 fdisk_unref_partition(npa);
2326 if (rc == 0)
2327 ref = 1;
2328 break;
2329 }
2330 case 'q': /* Quit */
2331 return 1;
2332 case 't': /* Type */
2333 {
2334 struct fdisk_parttype *t;
2335
2336 if (fdisk_partition_is_freespace(pa))
2337 return -EINVAL;
2338 t = (struct fdisk_parttype *) fdisk_partition_get_type(pa);
2339 t = ui_get_parttype(cf, t);
2340 ref = 1;
2341
2342 if (t && fdisk_set_partition_type(cf->cxt, n, t) == 0)
2343 info = _("Changed type of partition %zu.");
2344 else
2345 info = _("The type of partition %zu is unchanged.");
2346 break;
2347 }
2348 case 'r': /* resize */
2349 {
2350 struct fdisk_partition *npa, *next;
2351 uint64_t size, max_size, secs;
2352
2353 if (fdisk_partition_is_freespace(pa) || !fdisk_partition_has_start(pa))
2354 return -EINVAL;
2355
2356 size = fdisk_partition_get_size(pa);
2357
2358 /* is the next freespace? */
2359 next = fdisk_table_get_partition(cf->table, cf->lines_idx + 1);
2360 if (next && fdisk_partition_is_freespace(next))
2361 size += fdisk_partition_get_size(next);
2362
2363 size *= fdisk_get_sector_size(cf->cxt);
2364 max_size = size;
2365
2366 if (ui_get_size(cf, _("New size: "), &size,
2367 fdisk_get_sector_size(cf->cxt),
2368 max_size, NULL) == -CFDISK_ERR_ESC)
2369 break;
2370 secs = size / fdisk_get_sector_size(cf->cxt);
2371 npa = fdisk_new_partition();
2372 if (!npa)
2373 return -ENOMEM;
2374
2375 fdisk_partition_set_size(npa, secs);
2376
2377 rc = fdisk_set_partition(cf->cxt, n, npa);
2378 fdisk_unref_partition(npa);
2379 if (rc == 0) {
2380 ref = 1;
2381 info = _("Partition %zu resized.");
2382 }
2383 break;
2384 }
2385 case 's': /* Sort */
2386 if (cf->wrong_order) {
2387 fdisk_reorder_partitions(cf->cxt);
2388 ref = 1;
2389 }
2390 break;
2391 case 'u': /* dUmp */
2392 ui_script_write(cf);
2393 break;
2394 case 'W': /* Write */
2395 {
2396 char buf[64] = { 0 };
2397
2398 if (fdisk_is_readonly(cf->cxt)) {
2399 warn = _("Device is open in read-only mode.");
2400 break;
2401 }
2402
2403 rc = ui_get_string(
2404 _("Are you sure you want to write the partition "
2405 "table to disk? "),
2406 _("Type \"yes\" or \"no\", or press ESC to leave this dialog."),
2407 buf, sizeof(buf));
2408
2409 ref = 1;
2410 if (rc <= 0 || (strcasecmp(buf, "yes") != 0 &&
2411 strcasecmp(buf, _("yes")) != 0)) {
2412 info = _("Did not write partition table to disk.");
2413 break;
2414 }
2415 rc = fdisk_write_disklabel(cf->cxt);
2416 if (rc)
2417 warn = _("Failed to write disklabel.");
2418 else {
2419 if (cf->device_is_used)
2420 fdisk_reread_changes(cf->cxt, cf->original_layout);
2421 else
2422 fdisk_reread_partition_table(cf->cxt);
2423 info = _("The partition table has been altered.");
2424 }
2425 cf->nwrites++;
2426 break;
2427 }
2428 default:
2429 break;
2430 }
2431
2432 if (ref) {
2433 lines_refresh(cf);
2434 ui_refresh(cf);
2435 ui_draw_extra(cf);
2436 } else
2437 ui_draw_menu(cf);
2438
2439 ui_clean_hint();
2440
2441 if (warn)
2442 ui_warnx(warn, n + 1);
2443 else if (info)
2444 ui_info(info, n + 1);
2445 else if (key == 'n' && cf->wrong_order && org_order == 0)
2446 ui_info(_("Note that partition table entries are not in disk order now."));
2447
2448 return 0;
2449 }
2450
2451 static void ui_resize_refresh(struct cfdisk *cf)
2452 {
2453 DBG(UI, ul_debug("ui resize/refresh"));
2454 resize();
2455 menu_refresh_size(cf);
2456 lines_refresh(cf);
2457 ui_refresh(cf);
2458 ui_draw_extra(cf);
2459 }
2460
2461 static void toggle_show_extra(struct cfdisk *cf)
2462 {
2463 if (cf->show_extra && cf->act_win) {
2464 wclear(cf->act_win);
2465 touchwin(stdscr);
2466 }
2467 cf->show_extra = cf->show_extra ? 0 : 1;
2468
2469 if (cf->show_extra)
2470 ui_draw_extra(cf);
2471 DBG(MENU, ul_debug("extra: %s", cf->show_extra ? "ENABLED" : "DISABLED" ));
2472 }
2473
2474 static int ui_run(struct cfdisk *cf)
2475 {
2476 int rc = 0;
2477
2478 ui_lines = LINES;
2479 ui_cols = COLS;
2480 DBG(UI, ul_debug("start cols=%zu, lines=%zu", ui_cols, ui_lines));
2481
2482 if (fdisk_get_collision(cf->cxt)) {
2483 ui_warnx(_("Device already contains a %s signature; it will be removed by a write command."),
2484 fdisk_get_collision(cf->cxt));
2485 fdisk_enable_wipe(cf->cxt, 1);
2486 ui_hint(_("Press a key to continue."));
2487 getch();
2488 }
2489
2490 if (!fdisk_has_label(cf->cxt) || cf->zero_start) {
2491 rc = ui_create_label(cf);
2492 if (rc < 0)
2493 ui_errx(EXIT_FAILURE,
2494 _("failed to create a new disklabel"));
2495 if (rc)
2496 return rc;
2497 }
2498
2499 cols_init(cf);
2500 rc = lines_refresh(cf);
2501 if (rc)
2502 ui_errx(EXIT_FAILURE, _("failed to read partitions"));
2503
2504 menu_push(cf, main_menuitems);
2505 cf->menu->ignore_cb = main_menu_ignore_keys;
2506
2507 rc = ui_refresh(cf);
2508 if (rc)
2509 return rc;
2510
2511 cf->show_extra = 1;
2512 ui_draw_extra(cf);
2513
2514 if (fdisk_is_readonly(cf->cxt))
2515 ui_warnx(_("Device is open in read-only mode."));
2516 else if (cf->wrong_order)
2517 ui_info(_("Note that partition table entries are not in disk order now."));
2518
2519 do {
2520 int key = getch();
2521
2522 rc = 0;
2523 if (ui_resize)
2524 /* Note that ncurses getch() returns ERR when interrupted
2525 * by signal, but SLang does not interrupt at all. */
2526 ui_resize_refresh(cf);
2527 if (key == ERR)
2528 continue;
2529 if (key == '\014') { /* ^L refresh */
2530 ui_resize_refresh(cf);
2531 continue;
2532 }
2533 if (ui_menu_move(cf, key) == 0)
2534 continue;
2535
2536 DBG(UI, ul_debug("main action key >%1$c< [\\0%1$o].", key));
2537
2538 switch (key) {
2539 case KEY_DOWN:
2540 case '\016': /* ^N */
2541 case 'j': /* Vi-like alternative */
2542 ui_table_goto(cf, cf->lines_idx + 1);
2543 break;
2544 case KEY_UP:
2545 case '\020': /* ^P */
2546 case 'k': /* Vi-like alternative */
2547 ui_table_goto(cf, (int) cf->lines_idx - 1);
2548 break;
2549 case KEY_PPAGE:
2550 if (cf->page_sz) {
2551 ui_table_goto(cf, (int) cf->lines_idx - cf->page_sz);
2552 break;
2553 }
2554 /* fallthrough */
2555 case KEY_HOME:
2556 ui_table_goto(cf, 0);
2557 break;
2558 case KEY_NPAGE:
2559 if (cf->page_sz) {
2560 ui_table_goto(cf, cf->lines_idx + cf->page_sz);
2561 break;
2562 }
2563 /* fallthrough */
2564 case KEY_END:
2565 ui_table_goto(cf, (int) cf->nlines - 1);
2566 break;
2567 case KEY_ENTER:
2568 case '\n':
2569 case '\r':
2570 rc = main_menu_action(cf, 0);
2571 break;
2572 case 'X':
2573 case 'x': /* Extra */
2574 toggle_show_extra(cf);
2575 break;
2576 default:
2577 rc = main_menu_action(cf, key);
2578 if (rc < 0)
2579 beep();
2580 break;
2581 }
2582
2583 if (rc == 1)
2584 break; /* quit */
2585 } while (1);
2586
2587 menu_pop(cf);
2588
2589 DBG(UI, ul_debug("end"));
2590 return 0;
2591 }
2592
2593 static void __attribute__((__noreturn__)) usage(void)
2594 {
2595 FILE *out = stdout;
2596 fputs(USAGE_HEADER, out);
2597 fprintf(out,
2598 _(" %1$s [options] <disk>\n"), program_invocation_short_name);
2599
2600 fputs(USAGE_SEPARATOR, out);
2601 fputs(_("Display or manipulate a disk partition table.\n"), out);
2602
2603 fputs(USAGE_OPTIONS, out);
2604 fputs(_(" -L, --color[=<when>] colorize output (auto, always or never)\n"), out);
2605 fprintf(out,
2606 " %s\n", USAGE_COLORS_DEFAULT);
2607 fputs(_(" -z, --zero start with zeroed partition table\n"), out);
2608
2609 fputs(USAGE_SEPARATOR, out);
2610 printf(USAGE_HELP_OPTIONS(26));
2611
2612 printf(USAGE_MAN_TAIL("cfdisk(8)"));
2613 exit(EXIT_SUCCESS);
2614 }
2615
2616 int main(int argc, char *argv[])
2617 {
2618 const char *diskpath = NULL;
2619 int rc, c, colormode = UL_COLORMODE_UNDEF;
2620 struct cfdisk _cf = { .lines_idx = 0 },
2621 *cf = &_cf;
2622
2623 static const struct option longopts[] = {
2624 { "color", optional_argument, NULL, 'L' },
2625 { "help", no_argument, NULL, 'h' },
2626 { "version", no_argument, NULL, 'V' },
2627 { "zero", no_argument, NULL, 'z' },
2628 { NULL, 0, NULL, 0 },
2629 };
2630
2631 setlocale(LC_ALL, "");
2632 bindtextdomain(PACKAGE, LOCALEDIR);
2633 textdomain(PACKAGE);
2634 atexit(close_stdout);
2635
2636 while((c = getopt_long(argc, argv, "L::hVz", longopts, NULL)) != -1) {
2637 switch(c) {
2638 case 'h':
2639 usage();
2640 break;
2641 case 'L':
2642 colormode = UL_COLORMODE_AUTO;
2643 if (optarg)
2644 colormode = colormode_or_err(optarg,
2645 _("unsupported color mode"));
2646 break;
2647 case 'V':
2648 printf(UTIL_LINUX_VERSION);
2649 return EXIT_SUCCESS;
2650 case 'z':
2651 cf->zero_start = 1;
2652 break;
2653 default:
2654 errtryhelp(EXIT_FAILURE);
2655 }
2656 }
2657
2658 colors_init(colormode, "cfdisk");
2659
2660 fdisk_init_debug(0);
2661 scols_init_debug(0);
2662 cfdisk_init_debug();
2663 cf->cxt = fdisk_new_context();
2664 if (!cf->cxt)
2665 err(EXIT_FAILURE, _("failed to allocate libfdisk context"));
2666
2667 fdisk_set_ask(cf->cxt, ask_callback, (void *) cf);
2668
2669 if (optind == argc) {
2670 size_t i;
2671
2672 for (i = 0; i < ARRAY_SIZE(default_disks); i++) {
2673 if (access(default_disks[i], F_OK) == 0) {
2674 diskpath = default_disks[i];
2675 break;
2676 }
2677 }
2678 if (!diskpath)
2679 diskpath = default_disks[0]; /* default, used for "cannot open" */
2680 } else
2681 diskpath = argv[optind];
2682
2683 rc = fdisk_assign_device(cf->cxt, diskpath, 0);
2684 if (rc == -EACCES)
2685 rc = fdisk_assign_device(cf->cxt, diskpath, 1);
2686 if (rc != 0)
2687 err(EXIT_FAILURE, _("cannot open %s"), diskpath);
2688
2689 if (!fdisk_is_readonly(cf->cxt)) {
2690 cf->device_is_used = fdisk_device_is_used(cf->cxt);
2691 fdisk_get_partitions(cf->cxt, &cf->original_layout);
2692 }
2693
2694 /* Don't use err(), warn() from this point */
2695 ui_init(cf);
2696 ui_run(cf);
2697 ui_end();
2698
2699 cfdisk_free_lines(cf);
2700 free(cf->linesbuf);
2701
2702 fdisk_unref_table(cf->table);
2703 #ifdef HAVE_LIBMOUNT
2704 mnt_unref_table(cf->fstab);
2705 mnt_unref_table(cf->mtab);
2706 mnt_unref_cache(cf->mntcache);
2707 #endif
2708 rc = fdisk_deassign_device(cf->cxt, cf->nwrites == 0);
2709 fdisk_unref_context(cf->cxt);
2710 DBG(MISC, ul_debug("bye! [rc=%d]", rc));
2711 return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
2712 }