]> git.ozlabs.org Git - petitboot/blob - ui/ncurses/nc-cui.c
ui/ncurses: Update cui_run_cmd() to pass display to command
[petitboot] / ui / ncurses / nc-cui.c
1 /*
2  *  Copyright (C) 2009 Sony Computer Entertainment Inc.
3  *  Copyright 2009 Sony Corp.
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; version 2 of the License.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, write to the Free Software
16  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19 #if defined(HAVE_CONFIG_H)
20 #include "config.h"
21 #endif
22
23 #include <assert.h>
24 #include <errno.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/ioctl.h>
28 #include <sys/reboot.h>
29
30 #include "log/log.h"
31 #include "pb-protocol/pb-protocol.h"
32 #include "talloc/talloc.h"
33 #include "waiter/waiter.h"
34 #include "process/process.h"
35 #include "i18n/i18n.h"
36 #include "ui/common/discover-client.h"
37 #include "ui/common/ui-system.h"
38 #include "nc-cui.h"
39 #include "nc-boot-editor.h"
40 #include "nc-config.h"
41 #include "nc-add-url.h"
42 #include "nc-sysinfo.h"
43 #include "nc-lang.h"
44 #include "nc-helpscreen.h"
45 #include "nc-statuslog.h"
46 #include "nc-subset.h"
47
48 extern const struct help_text main_menu_help_text;
49
50 static bool cui_detached = false;
51
52 static struct pmenu *main_menu_init(struct cui *cui);
53
54 static bool lockdown_active(void)
55 {
56         bool lockdown = false;
57         if (access(LOCKDOWN_FILE, F_OK) != -1)
58                 lockdown = true;
59         return lockdown;
60 }
61
62 static void cui_start(void)
63 {
64         initscr();                      /* Initialize ncurses. */
65         cbreak();                       /* Disable line buffering. */
66         noecho();                       /* Disable getch() echo. */
67         keypad(stdscr, TRUE);           /* Enable num keypad keys. */
68         nonl();                         /* Disable new-line translation. */
69         intrflush(stdscr, FALSE);       /* Disable interrupt flush. */
70         curs_set(0);                    /* Make cursor invisible */
71         nodelay(stdscr, TRUE);          /* Enable non-blocking getch() */
72
73         /* We may be operating with an incorrect $TERM type; in this case
74          * the keymappings will be slightly broken. We want at least
75          * backspace to work though, so we'll define both DEL and ^H to
76          * map to backspace */
77         define_key("\x7f", KEY_BACKSPACE);
78         define_key("\x08", KEY_BACKSPACE);
79
80         /* we need backtab too, for form navigation. vt220 doesn't include
81          * this (kcbt), but we don't want to require a full linux/xterm termcap
82          */
83         define_key("\x1b[Z", KEY_BTAB);
84
85         /* We'll define a few other keys too since they're commonly
86          * used for navigation but the escape character will cause
87          * Petitboot to exit if they're left undefined */
88         define_key("\x1b\x5b\x35\x7e", KEY_PPAGE);
89         define_key("\x1b\x5b\x36\x7e", KEY_NPAGE);
90         define_key("\x1b\x5b\x31\x7e", KEY_HOME);
91         define_key("\x1b\x5b\x34\x7e", KEY_END);
92         define_key("\x1b\x4f\x48", KEY_HOME);
93         define_key("\x1b\x4f\x46", KEY_END);
94         define_key("OH", KEY_HOME);
95         define_key("OF", KEY_END);
96         define_key("\x1b\x5b\x41", KEY_UP);
97         define_key("\x1b\x5b\x42", KEY_DOWN);
98         define_key("\x1b\x5b\x33\x7e", KEY_DC);
99
100         while (getch() != ERR)          /* flush stdin */
101                 (void)0;
102 }
103
104 static void cui_atexit(void)
105 {
106         if (cui_detached)
107                 return;
108
109         clear();
110         refresh();
111         endwin();
112
113         bool lockdown = lockdown_active();
114
115         while (lockdown) {
116                 sync();
117                 reboot(RB_AUTOBOOT);
118         }
119 }
120
121 /**
122  * cui_abort - Signal the main cui program loop to exit.
123  *
124  * Sets cui.abort, which causes the cui_run() routine to return.
125  */
126
127 void cui_abort(struct cui *cui)
128 {
129         pb_log("%s: exiting\n", __func__);
130         cui->abort = 1;
131 }
132
133 /**
134  * cui_resize - Signal the main cui program loop to resize
135  *
136  * Called at SIGWINCH.
137  */
138
139 void cui_resize(struct cui *cui)
140 {
141         pb_debug("%s: resizing\n", __func__);
142         cui->resize = 1;
143 }
144
145 /**
146  * cui_on_exit - A generic main menu exit callback.
147  */
148
149 void cui_on_exit(struct pmenu *menu)
150 {
151         cui_abort(cui_from_pmenu(menu));
152 }
153
154 /**
155  * cui_run_cmd - A generic cb to run the supplied command.
156  */
157
158 int cui_run_cmd(struct cui *cui, const char **cmd_argv)
159 {
160         struct process *process;
161         int result;
162
163         process = process_create(cui);
164         if (!process)
165                 return -1;
166
167         process->path = cmd_argv[0];
168         process->argv = cmd_argv;
169         process->raw_stdout = true;
170
171         nc_scr_status_printf(cui->current, _("Running %s..."), cmd_argv[0]);
172
173         def_prog_mode();
174         endwin();
175
176         result = process_run_sync(process);
177
178         reset_prog_mode();
179         refresh();
180
181         redrawwin(cui->current->main_ncw);
182
183         if (result) {
184                 pb_log("%s: failed: '%s'\n", __func__, cmd_argv[0]);
185                 nc_scr_status_printf(cui->current, _("Failed: %s"),
186                                 cmd_argv[0]);
187         }
188
189         process_release(process);
190
191         return result;
192 }
193
194 int cui_run_cmd_from_item(struct pmenu_item *item)
195 {
196         struct cui *cui = cui_from_item(item);
197         const char **cmd_argv = item->data;
198
199         return cui_run_cmd(cui, cmd_argv);
200 }
201
202 /**
203  * cui_boot - A generic cb to run kexec.
204  */
205
206 static int cui_boot(struct pmenu_item *item)
207 {
208         int result;
209         struct cui *cui = cui_from_item(item);
210         struct cui_opt_data *cod = cod_from_item(item);
211
212         assert(cui->current == &cui->main->scr);
213
214         pb_debug("%s: %s\n", __func__, cod->name);
215
216         nc_scr_status_printf(cui->current, _("Booting %s..."), cod->name);
217
218         result = discover_client_boot(cui->client, NULL, cod->opt, cod->bd);
219
220         if (result) {
221                 nc_scr_status_printf(cui->current,
222                                 _("Failed: boot %s"), cod->bd->image);
223         }
224
225         return 0;
226 }
227
228 static void cui_boot_editor_on_exit(struct cui *cui,
229                 struct pmenu_item *item,
230                 struct pb_boot_data *bd)
231 {
232         struct pmenu *menu = cui->main;
233         struct cui_opt_data *cod;
234         int idx, top, rows, cols;
235         static int user_idx = 0;
236
237         /* Was the edit cancelled? */
238         if (!bd) {
239                 cui_set_current(cui, &cui->main->scr);
240                 talloc_free(cui->boot_editor);
241                 cui->boot_editor = NULL;
242                 return;
243         }
244
245         /* Is this was a new item, we'll need to update the menu */
246         if (!item) {
247                 int insert_pt;
248
249                 cod = talloc_zero(NULL, struct cui_opt_data);
250                 cod->name = talloc_asprintf(cod, _("User item %u"), ++user_idx);
251
252                 item = pmenu_item_create(menu, cod->name);
253                 if (!item) {
254                         talloc_free(cod);
255                         goto out;
256                 }
257
258                 item->on_edit = cui_item_edit;
259                 item->on_execute = cui_boot;
260                 item->data = cod;
261
262                 talloc_steal(item, cod);
263
264                 /* Detach the items array. */
265                 set_menu_items(menu->ncm, NULL);
266
267                 /* Insert new item at insert_pt. */
268                 insert_pt = pmenu_grow(menu, 1);
269                 pmenu_item_insert(menu, item, insert_pt);
270
271                 /* Re-attach the items array. */
272                 set_menu_items(menu->ncm, menu->items);
273
274                 /* If our index is above the current top row, align
275                  * us to the new top. Otherwise, align us to the new
276                  * bottom */
277                 menu_format(cui->main->ncm, &rows, &cols);
278                 top = top_row(cui->main->ncm);
279                 idx = item_index(item->nci);
280
281                 if (top >= idx)
282                         top = idx;
283                 else
284                         top = idx < rows ? 0 : idx - rows + 1;
285
286                 set_top_row(cui->main->ncm, top);
287                 set_current_item(item->pmenu->ncm, item->nci);
288
289                 nc_scr_post(&menu->scr);
290         } else {
291                 cod = item->data;
292         }
293
294         cod->bd = talloc_steal(cod, bd);
295
296 out:
297         cui_set_current(cui, &cui->main->scr);
298         talloc_free(cui->boot_editor);
299         cui->boot_editor = NULL;
300 }
301
302 void cui_item_edit(struct pmenu_item *item)
303 {
304         struct cui *cui = cui_from_item(item);
305         cui->boot_editor = boot_editor_init(cui, item, cui->sysinfo,
306                                         cui_boot_editor_on_exit);
307         cui_set_current(cui, boot_editor_scr(cui->boot_editor));
308 }
309
310 void cui_item_new(struct pmenu *menu)
311 {
312         struct cui *cui = cui_from_pmenu(menu);
313         cui->boot_editor = boot_editor_init(cui, NULL, cui->sysinfo,
314                                         cui_boot_editor_on_exit);
315         cui_set_current(cui, boot_editor_scr(cui->boot_editor));
316 }
317
318 static void cui_sysinfo_exit(struct cui *cui)
319 {
320         cui_set_current(cui, &cui->main->scr);
321         talloc_free(cui->sysinfo_screen);
322         cui->sysinfo_screen = NULL;
323 }
324
325 void cui_show_sysinfo(struct cui *cui)
326 {
327         cui->sysinfo_screen = sysinfo_screen_init(cui, cui->sysinfo,
328                         cui_sysinfo_exit);
329         cui_set_current(cui, sysinfo_screen_scr(cui->sysinfo_screen));
330 }
331
332 static void cui_config_exit(struct cui *cui)
333 {
334         cui_set_current(cui, &cui->main->scr);
335         talloc_free(cui->config_screen);
336         cui->config_screen = NULL;
337 }
338
339 void cui_show_config(struct cui *cui)
340 {
341         cui->config_screen = config_screen_init(cui, cui->config,
342                         cui->sysinfo, cui_config_exit);
343         cui_set_current(cui, config_screen_scr(cui->config_screen));
344 }
345
346 static void cui_lang_exit(struct cui *cui)
347 {
348         cui_set_current(cui, &cui->main->scr);
349         talloc_free(cui->lang_screen);
350         cui->lang_screen = NULL;
351 }
352
353 void cui_show_lang(struct cui *cui)
354 {
355         cui->lang_screen = lang_screen_init(cui, cui->config, cui_lang_exit);
356         cui_set_current(cui, lang_screen_scr(cui->lang_screen));
357 }
358
359 static void cui_statuslog_exit(struct cui *cui)
360 {
361         cui_set_current(cui, &cui->main->scr);
362         talloc_free(cui->statuslog_screen);
363         cui->statuslog_screen = NULL;
364 }
365
366 void cui_show_statuslog(struct cui *cui)
367 {
368         cui->statuslog_screen = statuslog_screen_init(cui, cui_statuslog_exit);
369         cui_set_current(cui, statuslog_screen_scr(cui->statuslog_screen));
370 }
371
372 static void cui_add_url_exit(struct cui *cui)
373 {
374         cui_set_current(cui, &cui->main->scr);
375         talloc_free(cui->add_url_screen);
376         cui->add_url_screen = NULL;
377 }
378
379 void cui_show_add_url(struct cui *cui)
380 {
381         cui->add_url_screen = add_url_screen_init(cui, cui_add_url_exit);
382         cui_set_current(cui, add_url_screen_scr(cui->add_url_screen));
383 }
384
385 static void cui_help_exit(struct cui *cui)
386 {
387         cui_set_current(cui, help_screen_return_scr(cui->help_screen));
388         talloc_free(cui->help_screen);
389         cui->help_screen = NULL;
390 }
391
392 void cui_show_help(struct cui *cui, const char *title,
393                 const struct help_text *text)
394 {
395         if (!cui->current)
396                 return;
397
398         if (cui->help_screen)
399                 return;
400
401         cui->help_screen = help_screen_init(cui, cui->current,
402                         title, text, cui_help_exit);
403
404         if (cui->help_screen)
405                 cui_set_current(cui, help_screen_scr(cui->help_screen));
406 }
407
408 static void cui_subset_exit(struct cui *cui)
409 {
410         cui_set_current(cui, subset_screen_return_scr(cui->subset_screen));
411         talloc_free(cui->subset_screen);
412         cui->subset_screen = NULL;
413 }
414
415 void cui_show_subset(struct cui *cui, const char *title,
416                      void *arg)
417 {
418         if (!cui->current)
419                 return;
420
421         if (cui->subset_screen)
422                 return;
423
424         cui->subset_screen = subset_screen_init(cui, cui->current,
425                         title, arg, cui_subset_exit);
426
427         if (cui->subset_screen)
428                 cui_set_current(cui, subset_screen_scr(cui->subset_screen));
429 }
430
431 /**
432  * cui_set_current - Set the currently active screen and redraw it.
433  */
434
435 struct nc_scr *cui_set_current(struct cui *cui, struct nc_scr *scr)
436 {
437         struct nc_scr *old;
438
439         DBGS("%p -> %p\n", cui->current, scr);
440
441         assert(cui->current != scr);
442
443         old = cui->current;
444         nc_scr_unpost(old);
445
446         cui->current = scr;
447
448         nc_scr_post(cui->current);
449
450         return old;
451 }
452
453 static bool process_global_keys(struct cui *cui, int key)
454 {
455         switch (key) {
456         case 0xc:
457                 if (cui->current && cui->current->main_ncw)
458                         wrefresh(curscr);
459                 return true;
460         }
461         return false;
462 }
463
464 /**
465  * cui_process_key - Process input on stdin.
466  */
467
468 static int cui_process_key(void *arg)
469 {
470         struct cui *cui = cui_from_arg(arg);
471
472         assert(cui->current);
473
474         for (;;) {
475                 int c = getch();
476
477                 pb_debug("%s: got key %d\n", __func__, c);
478
479                 if (c == ERR)
480                         break;
481
482                 if (!cui->has_input) {
483                         cui->has_input = true;
484                         if (cui->client) {
485                                 pb_log("UI input received (key = %d), aborting "
486                                         "default boot\n", c);
487                                 discover_client_cancel_default(cui->client);
488                         } else {
489                                 pb_log("UI input received (key = %d), aborting "
490                                         "once server connects\n", c);
491                         }
492                 }
493
494                 if (process_global_keys(cui, c))
495                         continue;
496
497                 cui->current->process_key(cui->current, c);
498         }
499
500         return 0;
501 }
502
503 /**
504  * cui_process_js - Process joystick events.
505  */
506
507 static int cui_process_js(void *arg)
508 {
509         struct cui *cui = cui_from_arg(arg);
510         int c;
511
512         c = pjs_process_event(cui->pjs);
513
514         if (c) {
515                 ungetch(c);
516                 cui_process_key(arg);
517         }
518
519         return 0;
520 }
521
522 /**
523  * cui_handle_resize - Handle the term resize.
524  */
525
526 static void cui_handle_resize(struct cui *cui)
527 {
528         struct winsize ws;
529
530         if (ioctl(1, TIOCGWINSZ, &ws) == -1) {
531                 pb_log("%s: ioctl failed: %s\n", __func__, strerror(errno));
532                 return;
533         }
534
535         pb_debug("%s: {%u,%u}\n", __func__, ws.ws_row, ws.ws_col);
536
537         wclear(cui->current->main_ncw);
538         resize_term(ws.ws_row, ws.ws_col);
539         cui->current->resize(cui->current);
540
541         /* For some reason this makes ncurses redraw the screen */
542         getch();
543         redrawwin(cui->current->main_ncw);
544         wrefresh(cui->current->main_ncw);
545 }
546
547 /**
548  * cui_device_add - Client device_add callback.
549  *
550  * Creates menu_items for all the device boot_options and inserts those
551  * menu_items into the main menu.  Redraws the main menu if it is active.
552  */
553
554 static int cui_boot_option_add(struct device *dev, struct boot_option *opt,
555                 void *arg)
556 {
557         struct pmenu_item *i, *dev_hdr = NULL;
558         struct cui *cui = cui_from_arg(arg);
559         struct cui_opt_data *cod;
560         const char *tab = "  ";
561         unsigned int insert_pt;
562         int result, rows, cols;
563         ITEM *selected;
564         char *name;
565
566         pb_debug("%s: %p %s\n", __func__, opt, opt->id);
567
568         selected = current_item(cui->main->ncm);
569         menu_format(cui->main->ncm, &rows, &cols);
570
571         if (cui->current == &cui->main->scr)
572                 nc_scr_unpost(cui->current);
573
574         /* Check if the boot device is new */
575         dev_hdr = pmenu_find_device(cui->main, dev, opt);
576
577         /* All actual boot entries are 'tabbed' across */
578         name = talloc_asprintf(cui->main, "%s%s",
579                         tab, opt->name ? : "Unknown Name");
580
581         /* Save the item in opt->ui_info for cui_device_remove() */
582         opt->ui_info = i = pmenu_item_create(cui->main, name);
583         talloc_free(name);
584         if (!i)
585                 return -1;
586
587         i->on_edit = cui_item_edit;
588         i->on_execute = cui_boot;
589         i->data = cod = talloc(i, struct cui_opt_data);
590
591         cod->opt = opt;
592         cod->dev = dev;
593         cod->opt_hash = pb_opt_hash(dev, opt);
594         cod->name = opt->name;
595         cod->bd = talloc(i, struct pb_boot_data);
596
597         cod->bd->image = talloc_strdup(cod->bd, opt->boot_image_file);
598         cod->bd->initrd = talloc_strdup(cod->bd, opt->initrd_file);
599         cod->bd->dtb = talloc_strdup(cod->bd, opt->dtb_file);
600         cod->bd->args = talloc_strdup(cod->bd, opt->boot_args);
601         cod->bd->args_sig_file = talloc_strdup(cod->bd, opt->args_sig_file);
602
603         /* This disconnects items array from menu. */
604         result = set_menu_items(cui->main->ncm, NULL);
605
606         if (result)
607                 pb_log("%s: set_menu_items failed: %d\n", __func__, result);
608
609         /* Insert new items at insert_pt. */
610         if (dev_hdr) {
611                 insert_pt = pmenu_grow(cui->main, 2);
612                 pmenu_item_insert(cui->main, dev_hdr, insert_pt);
613                 pb_log("%s: adding new device hierarchy %s\n",
614                         __func__,opt->device_id);
615                 pmenu_item_insert(cui->main, i, insert_pt+1);
616         } else {
617                 insert_pt = pmenu_grow(cui->main, 1);
618                 pmenu_item_add(cui->main, i, insert_pt);
619         }
620
621         pb_log("%s: adding opt '%s'\n", __func__, cod->name);
622         pb_log("   image  '%s'\n", cod->bd->image);
623         pb_log("   initrd '%s'\n", cod->bd->initrd);
624         pb_log("   args   '%s'\n", cod->bd->args);
625         pb_log("   argsig '%s'\n", cod->bd->args_sig_file);
626
627         /* Re-attach the items array. */
628         result = set_menu_items(cui->main->ncm, cui->main->items);
629
630         if (result)
631                 pb_log("%s: set_menu_items failed: %d\n", __func__, result);
632
633         if (0) {
634                 pb_log("%s\n", __func__);
635                 pmenu_dump_items(cui->main->items,
636                         item_count(cui->main->ncm) + 1);
637         }
638
639         if (!item_visible(selected)) {
640                 int idx, top;
641
642                 top = top_row(cui->main->ncm);
643                 idx = item_index(selected);
644
645                 /* If our index is above the current top row, align
646                  * us to the new top. Otherwise, align us to the new
647                  * bottom */
648                 top = top < idx ? idx - rows + 1 : idx;
649
650                 set_top_row(cui->main->ncm, top);
651                 set_current_item(cui->main->ncm, selected);
652         }
653
654         if (cui->current == &cui->main->scr)
655                 nc_scr_post(cui->current);
656
657         return 0;
658 }
659
660 /**
661  * cui_device_remove - Client device remove callback.
662  *
663  * Removes all the menu_items for the device from the main menu and redraws the
664  * main menu if it is active.
665  */
666
667 static void cui_device_remove(struct device *dev, void *arg)
668 {
669         struct cui *cui = cui_from_arg(arg);
670         struct boot_option *opt;
671         unsigned int i;
672         int rows, cols, top, last;
673         int result;
674
675         pb_log("%s: %p %s\n", __func__, dev, dev->id);
676
677         if (cui->current == &cui->main->scr)
678                 nc_scr_unpost(cui->current);
679
680         /* This disconnects items array from menu. */
681
682         result = set_menu_items(cui->main->ncm, NULL);
683
684         if (result)
685                 pb_log("%s: set_menu_items failed: %d\n", __func__, result);
686
687         list_for_each_entry(&dev->boot_options, opt, list) {
688                 struct pmenu_item *item = pmenu_item_from_arg(opt->ui_info);
689
690                 assert(pb_protocol_device_cmp(dev, cod_from_item(item)->dev));
691                 pmenu_remove(cui->main, item);
692         }
693
694         /* Manually remove remaining device hierarchy item */
695         for (i=0; i < cui->main->item_count; i++) {
696                 struct pmenu_item *item = item_userptr(cui->main->items[i]);
697                 if (!item || !item->data )
698                         continue;
699
700                 struct cui_opt_data *data = item->data;
701                 if (data && data->dev && data->dev == dev)
702                         pmenu_remove(cui->main,item);
703         }
704
705         /* Re-attach the items array. */
706
707         result = set_menu_items(cui->main->ncm, cui->main->items);
708
709         /* Move cursor to 'Exit' menu entry */
710         menu_format(cui->main->ncm, &rows, &cols);
711         last = cui->main->item_count - 1;
712         set_current_item(cui->main->ncm, cui->main->items[last]);
713         if (!item_visible(cui->main->items[last])) {
714                 top = last < rows ? 0 : last - rows + 1;
715                 set_top_row(cui->main->ncm, top);
716         }
717
718         if (result)
719                 pb_log("%s: set_menu_items failed: %d\n", __func__, result);
720
721         if (0) {
722                 pb_log("%s\n", __func__);
723                 pmenu_dump_items(cui->main->items,
724                         item_count(cui->main->ncm) + 1);
725         }
726
727         if (cui->current == &cui->main->scr)
728                 nc_scr_post(cui->current);
729 }
730
731 static void cui_update_status(struct status *status, void *arg)
732 {
733         struct cui *cui = cui_from_arg(arg);
734
735         statuslog_append_steal(cui, cui->statuslog, status);
736
737         /* Ignore status messages from the backlog */
738         if (!status->backlog)
739                 nc_scr_status_printf(cui->current, "%s", status->message);
740 }
741
742 static void cui_update_mm_title(struct cui *cui)
743 {
744         struct nc_frame *frame = &cui->main->scr.frame;
745
746         talloc_free(frame->rtitle);
747
748         frame->rtitle = talloc_strdup(cui->main, cui->sysinfo->type);
749         if (cui->sysinfo->identifier)
750                 frame->rtitle = talloc_asprintf_append(frame->rtitle,
751                                 " %s", cui->sysinfo->identifier);
752
753         if (cui->current == &cui->main->scr)
754                 nc_scr_post(cui->current);
755 }
756
757 static void cui_update_sysinfo(struct system_info *sysinfo, void *arg)
758 {
759         struct cui *cui = cui_from_arg(arg);
760         cui->sysinfo = talloc_steal(cui, sysinfo);
761
762         /* if we're currently displaying the system info screen, inform it
763          * of the updated information. */
764         if (cui->sysinfo_screen)
765                 sysinfo_screen_update(cui->sysinfo_screen, sysinfo);
766
767         if (cui->subset_screen)
768                 subset_screen_update(cui->subset_screen);
769
770         /* ... and do the same with the config screen... */
771         if (cui->config_screen)
772                 config_screen_update(cui->config_screen, cui->config, sysinfo);
773
774         /* ... and the boot editor. */
775         if (cui->boot_editor)
776                 boot_editor_update(cui->boot_editor, sysinfo);
777
778         cui_update_mm_title(cui);
779 }
780
781 static void cui_update_language(struct cui *cui, char *lang)
782 {
783         bool repost_menu;
784         char *cur_lang;
785
786         cur_lang = setlocale(LC_ALL, NULL);
787         if (cur_lang && !strcmp(cur_lang, lang))
788                 return;
789
790         setlocale(LC_ALL, lang);
791
792         /* we'll need to update the menu: drop all items and repopulate */
793         repost_menu = cui->current == &cui->main->scr;
794         if (repost_menu)
795                 nc_scr_unpost(cui->current);
796
797         talloc_free(cui->main);
798         cui->main = main_menu_init(cui);
799
800         if (repost_menu) {
801                 cui->current = &cui->main->scr;
802                 nc_scr_post(cui->current);
803         }
804
805         discover_client_enumerate(cui->client);
806 }
807
808 static void cui_update_config(struct config *config, void *arg)
809 {
810         struct cui *cui = cui_from_arg(arg);
811         cui->config = talloc_steal(cui, config);
812
813         if (config->lang)
814                 cui_update_language(cui, config->lang);
815
816         if (cui->subset_screen)
817                 subset_screen_update(cui->subset_screen);
818
819         if (cui->config_screen)
820                 config_screen_update(cui->config_screen, config, cui->sysinfo);
821
822         if (config->safe_mode)
823                 nc_scr_status_printf(cui->current,
824                                 _("SAFE MODE: select '%s' to continue"),
825                                 _("Rescan devices"));
826 }
827
828 int cui_send_config(struct cui *cui, struct config *config)
829 {
830         return discover_client_send_config(cui->client, config);
831 }
832
833 int cui_send_url(struct cui *cui, char * url)
834 {
835         return discover_client_send_url(cui->client, url);
836 }
837
838 void cui_send_reinit(struct cui *cui)
839 {
840         discover_client_send_reinit(cui->client);
841 }
842
843 static int menu_sysinfo_execute(struct pmenu_item *item)
844 {
845         cui_show_sysinfo(cui_from_item(item));
846         return 0;
847 }
848
849 static int menu_config_execute(struct pmenu_item *item)
850 {
851         cui_show_config(cui_from_item(item));
852         return 0;
853 }
854
855 static int menu_lang_execute(struct pmenu_item *item)
856 {
857         cui_show_lang(cui_from_item(item));
858         return 0;
859 }
860
861 static int menu_statuslog_execute(struct pmenu_item *item)
862 {
863         cui_show_statuslog(cui_from_item(item));
864         return 0;
865 }
866
867 static int menu_reinit_execute(struct pmenu_item *item)
868 {
869         if (cui_from_item(item)->client)
870                 cui_send_reinit(cui_from_item(item));
871         return 0;
872 }
873
874 static int menu_add_url_execute(struct pmenu_item *item)
875 {
876         if (cui_from_item(item)->client)
877                 cui_show_add_url(cui_from_item(item));
878         return 0;
879 }
880
881 /**
882  * pb_mm_init - Setup the main menu instance.
883  */
884 static struct pmenu *main_menu_init(struct cui *cui)
885 {
886         struct pmenu_item *i;
887         struct pmenu *m;
888         int result;
889         bool lockdown = lockdown_active();
890
891         m = pmenu_init(cui, 8, cui_on_exit);
892         if (!m) {
893                 pb_log("%s: failed\n", __func__);
894                 return NULL;
895         }
896
897         m->on_new = cui_item_new;
898
899         m->scr.frame.ltitle = talloc_asprintf(m,
900                 "Petitboot (" PACKAGE_VERSION ")");
901         m->scr.frame.rtitle = NULL;
902         m->scr.frame.help = talloc_strdup(m,
903                 _("Enter=accept, e=edit, n=new, x=exit, l=language, g=log, h=help"));
904         m->scr.frame.status = talloc_strdup(m, _("Welcome to Petitboot"));
905
906         /* add a separator */
907         i = pmenu_item_create(m, " ");
908         item_opts_off(i->nci, O_SELECTABLE);
909         pmenu_item_insert(m, i, 0);
910
911         /* add system items */
912         i = pmenu_item_create(m, _("System information"));
913         i->on_execute = menu_sysinfo_execute;
914         pmenu_item_insert(m, i, 1);
915
916         i = pmenu_item_create(m, _("System configuration"));
917         i->on_execute = menu_config_execute;
918         pmenu_item_insert(m, i, 2);
919
920         i = pmenu_item_create(m, _("System status log"));
921         i->on_execute = menu_statuslog_execute;
922         pmenu_item_insert(m, i, 3);
923
924         /* this label isn't translated, so we don't want a gettext() here */
925         i = pmenu_item_create(m, "Language");
926         i->on_execute = menu_lang_execute;
927         pmenu_item_insert(m, i, 4);
928
929         i = pmenu_item_create(m, _("Rescan devices"));
930         i->on_execute = menu_reinit_execute;
931         pmenu_item_insert(m, i, 5);
932
933         i = pmenu_item_create(m, _("Retrieve config from URL"));
934         i->on_execute = menu_add_url_execute;
935         pmenu_item_insert(m, i, 6);
936
937         if (lockdown)
938                 i = pmenu_item_create(m, _("Reboot"));
939         else
940                 i = pmenu_item_create(m, _("Exit to shell"));
941         i->on_execute = pmenu_exit_cb;
942         pmenu_item_insert(m, i, 7);
943
944         result = pmenu_setup(m);
945
946         if (result) {
947                 pb_log("%s:%d: pmenu_setup failed: %s\n", __func__, __LINE__,
948                         strerror(errno));
949                 goto fail_setup;
950         }
951
952         m->help_title = _("main menu");
953         m->help_text = &main_menu_help_text;
954
955         menu_opts_off(m->ncm, O_SHOWDESC);
956         set_menu_mark(m->ncm, " *");
957         set_current_item(m->ncm, i->nci);
958
959         return m;
960
961 fail_setup:
962         talloc_free(m);
963         return NULL;
964 }
965
966 static struct discover_client_ops cui_client_ops = {
967         .device_add = NULL,
968         .boot_option_add = cui_boot_option_add,
969         .device_remove = cui_device_remove,
970         .update_status = cui_update_status,
971         .update_sysinfo = cui_update_sysinfo,
972         .update_config = cui_update_config,
973 };
974
975 /* cui_server_wait_on_exit - On exit spin until the server is available.
976  *
977  * If the program exits before connecting to the server autoboot won't be
978  * cancelled even though there has been keyboard activity. This function is
979  * called by a child process which will spin until the server is connected and
980  * told to cancel autoboot.
981  *
982  * Processes exiting from this function will not carry out the cui_atexit()
983  * steps.
984  */
985 static void cui_server_wait_on_exit(struct cui *cui)
986 {
987         cui_detached = true;
988
989         while (!cui->client) {
990                 cui->client = discover_client_init(cui->waitset,
991                                 &cui_client_ops, cui);
992                 if (!cui->client)
993                         sleep(1);
994         }
995
996         talloc_steal(cui, cui->client);
997         discover_client_cancel_default(cui->client);
998 }
999
1000 /* cui_server_wait - Connect to the discover server.
1001  * @arg: Pointer to the cui instance.
1002  *
1003  * A timeout callback that attempts to connect to the discover server; on
1004  * failure it registers itself with a one second timeout to try again.
1005  * On success the cui->client struct will be set.
1006  *
1007  * Since this updates the status line when called it must not be called
1008  * before the UI is ready.
1009  */
1010 static int cui_server_wait(void *arg)
1011 {
1012         struct cui *cui = cui_from_arg(arg);
1013
1014         if (cui->client) {
1015                 pb_debug("We already have a server!\n");
1016                 return 0;
1017         }
1018
1019         /* We haven't yet connected to the server */
1020         pb_log("Trying to connect...\n");
1021         cui->client = discover_client_init(cui->waitset,
1022                         &cui_client_ops, cui);
1023
1024         if (!cui->client) {
1025                 waiter_register_timeout(cui->waitset, 1000, cui_server_wait,
1026                                         cui);
1027                 nc_scr_status_printf(cui->current,
1028                                      "Info: Waiting for device discovery");
1029         } else {
1030                 nc_scr_status_free(cui->current);
1031                 talloc_steal(cui, cui->client);
1032
1033                 if (cui->has_input) {
1034                         pb_log("Aborting default boot on pb-discover connect\n");
1035                         discover_client_cancel_default(cui->client);
1036                 }
1037         }
1038
1039         return 0;
1040 }
1041
1042 /**
1043  * cui_init - Setup the cui instance.
1044  * @platform_info: A value for the struct cui platform_info member.
1045  *
1046  * Returns a pointer to a struct cui on success, or NULL on error.
1047  *
1048  * Allocates the cui instance, sets up the client and stdin waiters, and
1049  * sets up the ncurses menu screen.
1050  */
1051
1052 struct cui *cui_init(void* platform_info,
1053         int (*js_map)(const struct js_event *e), int start_daemon, int timeout)
1054 {
1055         struct cui *cui;
1056         unsigned int i;
1057
1058         cui = talloc_zero(NULL, struct cui);
1059         if (!cui) {
1060                 pb_log("%s: alloc cui failed.\n", __func__);
1061                 fprintf(stderr, _("%s: alloc cui failed.\n"), __func__);
1062                 goto fail_alloc;
1063         }
1064
1065         cui->c_sig = pb_cui_sig;
1066         cui->platform_info = platform_info;
1067         cui->waitset = waitset_create(cui);
1068         cui->statuslog = statuslog_init(cui);
1069
1070         process_init(cui, cui->waitset, false);
1071
1072         /* Loop here for scripts that just started the server. */
1073
1074 retry_start:
1075         for (i = start_daemon ? 2 : 15; i && timeout; i--) {
1076                 cui->client = discover_client_init(cui->waitset,
1077                                 &cui_client_ops, cui);
1078                 if (cui->client || !i)
1079                         break;
1080                 pb_log("%s: waiting for server %d\n", __func__, i);
1081                 sleep(1);
1082         }
1083
1084         if (!cui->client && start_daemon) {
1085                 int result;
1086
1087                 start_daemon = 0;
1088
1089                 result = pb_start_daemon(cui);
1090
1091                 if (!result)
1092                         goto retry_start;
1093
1094                 pb_log("%s: discover_client_init failed.\n", __func__);
1095                 fprintf(stderr, _("%s: error: discover_client_init failed.\n"),
1096                         __func__);
1097                 fprintf(stderr, _("could not start pb-discover, the petitboot "
1098                         "daemon.\n"));
1099                 goto fail_client_init;
1100         }
1101
1102         if (!cui->client && !timeout) {
1103                 /* Have the first timeout fire immediately so we can check
1104                  * for the server as soon as the UI is ready */
1105                 waiter_register_timeout(cui->waitset, 0,
1106                                         cui_server_wait, cui);
1107         } else if (!cui->client) {
1108                 pb_log("%s: discover_client_init failed.\n", __func__);
1109                 fprintf(stderr, _("%s: error: discover_client_init failed.\n"),
1110                         __func__);
1111                 fprintf(stderr, _("check that pb-discover, "
1112                         "the petitboot daemon is running.\n"));
1113                 goto fail_client_init;
1114         }
1115
1116         atexit(cui_atexit);
1117         talloc_steal(cui, cui->client);
1118         cui_start();
1119
1120         cui->main = main_menu_init(cui);
1121         if (!cui->main)
1122                 goto fail_client_init;
1123
1124         waiter_register_io(cui->waitset, STDIN_FILENO, WAIT_IN,
1125                         cui_process_key, cui);
1126
1127         if (js_map) {
1128
1129                 cui->pjs = pjs_init(cui, js_map);
1130
1131                 if (cui->pjs)
1132                         waiter_register_io(cui->waitset, pjs_get_fd(cui->pjs),
1133                                         WAIT_IN, cui_process_js, cui);
1134         }
1135
1136         return cui;
1137
1138 fail_client_init:
1139         talloc_free(cui);
1140 fail_alloc:
1141         return NULL;
1142 }
1143
1144 /**
1145  * cui_run - The main cui program loop.
1146  * @cui: The cui instance.
1147  * @main: The menu to use as the main menu.
1148  *
1149  * Runs the cui engine.  Does not return until indicated to do so by some
1150  * user action, or an error occurs.  Frees the cui object on return.
1151  * Returns 0 on success (return to shell), -1 on error (should restart).
1152  */
1153
1154 int cui_run(struct cui *cui)
1155 {
1156         pid_t pid;
1157
1158         assert(main);
1159
1160         cui->current = &cui->main->scr;
1161         cui->default_item = 0;
1162
1163         nc_scr_post(cui->current);
1164
1165         while (1) {
1166                 int result = waiter_poll(cui->waitset);
1167
1168                 if (result < 0) {
1169                         pb_log("%s: poll: %s\n", __func__, strerror(errno));
1170                         break;
1171                 }
1172
1173                 if (cui->abort)
1174                         break;
1175
1176                 while (cui->resize) {
1177                         cui->resize = 0;
1178                         cui_handle_resize(cui);
1179                 }
1180         }
1181
1182         cui_atexit();
1183
1184         if (!cui->client) {
1185                 /* Fork a child to tell the server to cancel autoboot */
1186                 pid = fork();
1187                 if (!pid) {
1188                         cui_server_wait_on_exit(cui);
1189                         exit(EXIT_SUCCESS);
1190                 }
1191                 if (pid < 0)
1192                         pb_log("Failed to fork child on exit: %m\n");
1193         }
1194
1195         return cui->abort ? 0 : -1;
1196 }