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