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