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