Rename "secchan" to "ofproto" (library) and "ovs-openflowd" (program).
[sliver-openvswitch.git] / extras / ezio / ovs-switchui.c
1 /* Copyright (c) 2008, 2009 Nicira Networks, Inc.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17 #include <arpa/inet.h>
18 #include <assert.h>
19 #include <ctype.h>
20 #include <curses.h>
21 #include <errno.h>
22 #include <getopt.h>
23 #include <inttypes.h>
24 #include <math.h>
25 #include <pcre.h>
26 #include <signal.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/stat.h>
30 #include <term.h>
31 #include <unistd.h>
32 #include "command-line.h"
33 #include "daemon.h"
34 #include "dynamic-string.h"
35 #include "ezio.h"
36 #include "fatal-signal.h"
37 #include "netdev.h"
38 #include "ofpbuf.h"
39 #include "openflow/nicira-ext.h"
40 #include "openflow/openflow.h"
41 #include "packets.h"
42 #include "poll-loop.h"
43 #include "process.h"
44 #include "random.h"
45 #include "rconn.h"
46 #include "socket-util.h"
47 #include "svec.h"
48 #include "timeval.h"
49 #include "util.h"
50 #include "vconn.h"
51 #include "xtoxll.h"
52
53 #define THIS_MODULE VLM_switchui
54 #include "vlog.h"
55
56 static void parse_options(int argc, char *argv[]);
57 static void usage(void);
58
59 static void initialize_terminal(void);
60 static void restore_terminal(void *aux);
61
62 enum priority {
63     P_STATUS = 5,
64     P_PROGRESS = 10,
65     P_WARNING = 15,
66     P_ERROR = 20,
67     P_FATAL = 25
68 };
69
70 struct message;
71 static void emit(struct message **, enum priority, const char *, ...)
72     PRINTF_FORMAT(3, 4);
73 static void emit_function(struct message **, enum priority,
74                           void (*function)(void *aux), void *aux);
75 static int shown(struct message **);
76 static void clear_messages(void);
77 static bool empty_message(const struct message *);
78 static struct message *best_message(void);
79 static struct message *next_message(struct message *);
80 static struct message *prev_message(struct message *);
81 static void put_message(const struct message *);
82 static void message_shown(struct message *);
83 static void age_messages(void);
84
85 struct pair {
86     char *name;
87     char *value;
88 };
89
90 struct dict {
91     struct pair *pairs;
92     size_t n, max;
93 };
94
95 static void dict_init(struct dict *);
96 static void dict_add(struct dict *, const char *name, const char *value);
97 static void dict_add_nocopy(struct dict *, char *name, char *value);
98 static void dict_delete(struct dict *, const char *name);
99 static void dict_parse(struct dict *, const char *data, size_t nbytes);
100 static void dict_free(struct dict *);
101 static bool dict_lookup(const struct dict *,
102                         const char *name, const char **value);
103 static int dict_get_int(const struct dict *, const char *name, int def);
104 static bool dict_get_bool(const struct dict *, const char *name, bool def);
105 static const char *dict_get_string(const struct dict *,
106                                    const char *name, const char *def);
107 static uint32_t dict_get_ip(const struct dict *, const char *name);
108
109 static void addf(const char *format, ...) PRINTF_FORMAT(1, 2);
110
111 static void fetch_status(struct rconn *, struct dict *, long long int timeout);
112 static bool parse_reply(void *, struct dict *, uint32_t xid);
113 static void compose_messages(const struct dict *, struct rconn *rconn);
114
115 static void show_flows(struct rconn *);
116 static void show_dpid_ip(struct rconn *, const struct dict *);
117 static void show_ofproto_state(const struct dict *);
118 static void show_fail_open_state(const struct dict *);
119 static void show_discovery_state(const struct dict *);
120 static void show_remote_state(const struct dict *);
121 static void show_data_rates(struct rconn *, const struct dict *);
122
123 static void init_reboot_notifier(void);
124 static bool show_reboot_state(void);
125
126 static void show_string(const char *string);
127 static void block_until(long long timeout);
128 static void menu(const struct dict *);
129 static void drain_keyboard_buffer(void);
130
131 static const char *progress(void);
132
133 int
134 main(int argc, char *argv[])
135 {
136     struct rconn *rconn;
137     struct message *msg;
138     int countdown = 5;
139     bool user_selected;
140     bool debug_mode;
141
142     /* Tracking keystroke repeat counts. */
143     int last_key = 0;
144     long long int last_key_time = 0;
145     int repeat_count = 0;
146
147     set_program_name(argv[0]);
148     time_init();
149     vlog_init();
150     parse_options(argc, argv);
151     signal(SIGPIPE, SIG_IGN);
152     vlog_set_levels(VLM_ANY_MODULE, VLF_CONSOLE, VLL_EMER);
153     init_reboot_notifier();
154
155     argc -= optind;
156     argv += optind;
157     if (argc != 1) {
158         ovs_fatal(0, "exactly one non-option argument required; "
159                   "use --help for help");
160     }
161
162     rconn = rconn_new(argv[0], 5, 5);
163
164     die_if_already_running();
165     daemonize();
166
167     initialize_terminal();
168     fatal_signal_add_hook(restore_terminal, NULL, true);
169
170     msg = NULL;
171     countdown = 0;
172     user_selected = false;
173     debug_mode = false;
174     for (;;) {
175         struct dict dict;
176         long long timeout = time_msec() + 1000;
177
178         clear_messages();
179
180         dict_init(&dict);
181         fetch_status(rconn, &dict, timeout);
182         dict_add(&dict, "debug", debug_mode ? "true" : "false");
183         compose_messages(&dict, rconn);
184
185         if (countdown) {
186             if (!empty_message(msg)) {
187                 countdown--;
188             } else {
189                 msg = user_selected ? next_message(msg) : best_message();
190                 countdown = 5;
191             }
192         } else {
193             msg = best_message();
194             countdown = 5;
195             user_selected = false;
196         }
197         if (!user_selected) {
198             message_shown(msg);
199         }
200
201         do {
202             for (;;) {
203                 int c = getch();
204                 if (c == ERR) {
205                     break;
206                 }
207
208                 if (c != last_key || time_msec() > last_key_time + 250) {
209                     repeat_count = 0;
210                 }
211                 last_key = c;
212                 last_key_time = time_msec();
213                 repeat_count++;
214
215                 if (c == KEY_DOWN || c == KEY_UP) {
216                     msg = (c == KEY_DOWN ? next_message(msg)
217                            : prev_message(msg));
218                     countdown = 5;
219                     user_selected = true;
220                 } else if (c == '\r' || c == '\n') {
221                     countdown = 60;
222                     user_selected = true;
223                     if (repeat_count >= 20) {
224                         debug_mode = !debug_mode;
225                         show_string(debug_mode
226                                     ? "Debug Mode\nEnabled"
227                                     : "Debug Mode\nDisabled");
228                     }
229                 } else if (c == '\b' || c == '\x7f' ||
230                            c == '\x1b' || c == KEY_BACKSPACE || c == KEY_DC) {
231                     menu(&dict);
232                     drain_keyboard_buffer();
233                     break;
234                 }
235             }
236
237             erase();
238             curs_set(0);
239             move(0, 0);
240             put_message(msg);
241             refresh();
242
243             poll_fd_wait(STDIN_FILENO, POLLIN);
244             poll_timer_wait(timeout - time_msec());
245             poll_block();
246         } while (time_msec() < timeout);
247         age_messages();
248         dict_free(&dict);
249     }
250
251     return 0;
252 }
253
254 static void
255 compose_messages(const struct dict *dict, struct rconn *rconn)
256 {
257     if (!show_reboot_state()) {
258         show_flows(rconn);
259         show_dpid_ip(rconn, dict);
260         show_ofproto_state(dict);
261         show_fail_open_state(dict);
262         show_discovery_state(dict);
263         show_remote_state(dict);
264         show_data_rates(rconn, dict);
265     }
266 }
267
268 struct put_flows_data {
269     struct rconn *rconn;
270     uint32_t xid;
271     uint32_t flow_count;
272     bool got_reply;
273 };
274
275 static void
276 parse_flow_reply(void *data, struct put_flows_data *pfd)
277 {
278     struct ofp_header *oh;
279     struct ofp_stats_reply *rpy;
280     struct ofp_aggregate_stats_reply *asr;
281     const size_t min_size = sizeof *rpy + sizeof *asr;
282
283     oh = data;
284     if (ntohs(oh->length) < min_size) {
285         VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
286         return;
287     }
288     if (oh->xid != pfd->xid) {
289         VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
290                   oh->xid, pfd->xid);
291         return;
292     }
293     if (oh->type != OFPT_STATS_REPLY) {
294         VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
295         return;
296     }
297
298     rpy = data;
299     if (rpy->type != htons(OFPST_AGGREGATE)) {
300         VLOG_WARN("reply has wrong stat type ID %08"PRIx16, rpy->type);
301         return;
302     }
303
304     asr = (struct ofp_aggregate_stats_reply *) rpy->body;
305     pfd->flow_count = ntohl(asr->flow_count);
306     pfd->got_reply = true;
307 }
308
309 static bool
310 have_icons(void)
311 {
312     const char *dico = tigetstr("dico");
313     return dico && dico != (const char *) -1;
314 }
315
316 static void
317 set_icon(int num, int r0, int r1, int r2, int r3, int r4, int r5, int r6,
318          int r7)
319 {
320     if (have_icons()) {
321         putp(tparm(tigetstr("dico"), num, r0, r1, r2, r3, r4, r5, r6, r7));
322     }
323 }
324
325 static void
326 set_repeated_icon(int num, int row)
327 {
328     set_icon(num, row, row, row, row, row, row, row, row);
329 }
330
331 #if 0
332 static void
333 set_brick_icon(int num, int n_solid)
334 {
335     const static int rows[6] = {_____, X____, XX___, XXX__, XXXX_, XXXXX};
336     set_repeated_icon(num, rows[n_solid < 0 ? 0
337                                 : n_solid > 5 ? 5
338                                 : n_solid]);
339 }
340 #endif
341
342 static int
343 icon_char(int num, int alternate)
344 {
345     return have_icons() ? 0x80 | num | A_ALTCHARSET : alternate;
346 }
347
348 static void
349 put_icon(int num, char alternate)
350 {
351     addch(icon_char(num, alternate));
352 }
353
354 #if 0
355 static void
356 bar_graph(int n_chars, int n_pixels)
357 {
358     int i;
359
360     if (n_pixels < 0) {
361         n_pixels = 0;
362     } else if (n_pixels > n_chars * 5) {
363         n_pixels = n_chars * 5;
364     }
365
366     if (n_pixels > 5) {
367         set_brick_icon(0, 5);
368         for (i = 0; i < n_pixels / 5; i++) {
369             put_icon(0, "#");
370         }
371     }
372     if (n_pixels % 5) {
373         set_brick_icon(1, n_pixels % 5);
374         put_icon(1, "#");
375     }
376 }
377 #endif
378
379 static void
380 put_flows(void *pfd_)
381 {
382     struct put_flows_data *pfd = pfd_;
383     static struct rconn_packet_counter *counter;
384     char host[64];
385
386     if (!counter) {
387         counter = rconn_packet_counter_create();
388     }
389
390     if (!pfd->xid) {
391         struct ofp_stats_request *rq;
392         struct ofp_aggregate_stats_request *asr;
393         struct ofpbuf *b;
394
395         pfd->xid = random_uint32();
396         rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
397                                pfd->xid, &b);
398         rq->type = htons(OFPST_AGGREGATE);
399         rq->flags = htons(0);
400         asr = ofpbuf_put_uninit(b, sizeof *asr);
401         memset(asr, 0, sizeof *asr);
402         asr->match.wildcards = htonl(OFPFW_ALL);
403         asr->table_id = 0xff;
404         asr->out_port = htons(OFPP_NONE);
405         update_openflow_length(b);
406         rconn_send_with_limit(pfd->rconn, b, counter, 10);
407     }
408
409     if (!pfd->got_reply) {
410         int i;
411
412         rconn_run(pfd->rconn);
413         for (i = 0; i < 50; i++) {
414             struct ofpbuf *b;
415
416             b = rconn_recv(pfd->rconn);
417             if (!b) {
418                 break;
419             }
420
421             parse_flow_reply(b->data, pfd);
422             ofpbuf_delete(b);
423             if (pfd->got_reply) {
424                 break;
425             }
426         }
427     }
428
429     gethostname(host, sizeof host);
430     host[sizeof host - 1] = '\0';
431     if (strlen(host) + 6 <= 16) {
432         addf("Host: %s\n", host); 
433     } else {
434         addf("%s\n", host);
435     }
436     if (pfd->got_reply) {
437         addf("Flows: %"PRIu32, pfd->flow_count);
438     }
439
440     if (!pfd->got_reply) {
441         rconn_run_wait(pfd->rconn);
442         rconn_recv_wait(pfd->rconn);
443     }
444 }
445
446 static void
447 show_flows(struct rconn *rconn)
448 {
449     static struct message *m;
450     static struct put_flows_data pfd;
451
452     memset(&pfd, 0, sizeof pfd);
453     pfd.rconn = rconn;
454     emit_function(&m, P_STATUS, put_flows, &pfd);
455
456 }
457
458 struct put_dpid_ip_data {
459     struct rconn *rconn;
460     uint32_t xid;
461     uint64_t dpid;
462     char ip[16];
463     bool got_reply;
464 };
465
466 static void
467 parse_dp_reply(void *data, struct put_dpid_ip_data *pdid)
468 {
469     struct ofp_switch_features *osf;
470     struct ofp_header *oh;
471
472     oh = data;
473     if (ntohs(oh->length) < sizeof *osf) {
474         VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
475         return;
476     }
477     if (oh->xid != pdid->xid) {
478         VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
479                   oh->xid, pdid->xid);
480         return;
481     }
482     if (oh->type != OFPT_FEATURES_REPLY) {
483         VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
484         return;
485     }
486
487     osf = data;
488     pdid->dpid = ntohll(osf->datapath_id);
489     pdid->got_reply = true;
490 }
491
492 static void
493 put_dpid_id(void *pdid_)
494 {
495     struct put_dpid_ip_data *pdid = pdid_;
496     static struct rconn_packet_counter *counter;
497
498     if (!counter) {
499         counter = rconn_packet_counter_create();
500     }
501
502     if (!pdid->xid) {
503         struct ofp_header *oh;
504         struct ofpbuf *b;
505
506         pdid->xid = random_uint32();
507         oh = make_openflow_xid(sizeof *oh, OFPT_FEATURES_REQUEST,
508                                pdid->xid, &b);
509         rconn_send_with_limit(pdid->rconn, b, counter, 10);
510     }
511
512     if (!pdid->got_reply) {
513         int i;
514
515         rconn_run(pdid->rconn);
516         for (i = 0; i < 50; i++) {
517             struct ofpbuf *b;
518
519             b = rconn_recv(pdid->rconn);
520             if (!b) {
521                 break;
522             }
523
524             parse_dp_reply(b->data, pdid);
525             ofpbuf_delete(b);
526             if (pdid->got_reply) {
527                 break;
528             }
529         }
530     }
531
532     addf("DP: ");
533     if (pdid->got_reply) {
534         addf("%012"PRIx64, pdid->dpid);
535     }
536     addf("\nIP: %s", pdid->ip);
537
538     if (!pdid->got_reply) {
539         rconn_run_wait(pdid->rconn);
540         rconn_recv_wait(pdid->rconn);
541     }
542 }
543
544 static void
545 show_dpid_ip(struct rconn *rconn, const struct dict *dict)
546 {
547     static struct message *m;
548     static struct put_dpid_ip_data pdid;
549     const char *is_connected, *local_ip;
550
551     dict_lookup(dict, "local.is-connected", &is_connected);
552     dict_lookup(dict, "in-band.local-ip", &local_ip);
553     if (!is_connected && !local_ip) {
554         /* If we're not connected to the datapath and don't have a local IP,
555          * then we won't have anything useful to show anyhow. */
556         return;
557     }
558
559     memset(&pdid, 0, sizeof pdid);
560     pdid.rconn = rconn;
561     ovs_strlcpy(pdid.ip, local_ip ? local_ip : "", sizeof pdid.ip);
562     emit_function(&m, P_STATUS, put_dpid_id, &pdid);
563 }
564
565 static size_t
566 dict_find(const struct dict *dict, const char *name)
567 {
568     size_t i;
569
570     for (i = 0; i < dict->n; i++) {
571         const struct pair *p = &dict->pairs[i];
572         if (!strcmp(p->name, name)) {
573             return i;
574         }
575     }
576
577     return SIZE_MAX;
578 }
579
580 static bool
581 dict_lookup(const struct dict *dict, const char *name, const char **value)
582 {
583     size_t idx = dict_find(dict, name);
584     if (idx != SIZE_MAX) {
585         *value = dict->pairs[idx].value;
586         return true;
587     } else {
588         *value = NULL;
589         return false;
590     }
591 }
592
593 static const char *
594 dict_get(const struct dict *dict, const char *name)
595 {
596     const char *value;
597     return dict_lookup(dict, name, &value) ? value : NULL;
598 }
599
600 static int
601 dict_get_int(const struct dict *dict, const char *name, int def)
602 {
603     const char *value;
604     return dict_lookup(dict, name, &value) ? atoi(value) : def;
605 }
606
607 static bool
608 dict_get_bool(const struct dict *dict, const char *name, bool def)
609 {
610     const char *value;
611     if (dict_lookup(dict, name, &value)) {
612         if (!strcmp(value, "true")) {
613             return true;
614         }
615         if (!strcmp(value, "false")) {
616             return false;
617         }
618     }
619     return def;
620 }
621
622 static const char *
623 dict_get_string(const struct dict *dict, const char *name, const char *def)
624 {
625     const char *value;
626     return dict_lookup(dict, name, &value) ? value : def;
627 }
628
629 static uint32_t
630 dict_get_ip(const struct dict *dict, const char *name)
631 {
632     struct in_addr in;
633     return (inet_aton(dict_get_string(dict, name, ""), &in) ? in.s_addr
634             : htonl(0));
635 }
636
637 static void
638 addf(const char *format, ...)
639 {
640     char buf[128];
641     va_list args;
642
643     va_start(args, format);
644     vsnprintf(buf, sizeof buf, format, args);
645     va_end(args);
646
647     addstr(buf);
648 }
649
650 static void
651 show_ofproto_state(const struct dict *dict)
652 {
653     static struct message *msg;
654     const char *is_connected;
655
656     if (!dict_lookup(dict, "remote.is-connected", &is_connected)) {
657         /* Secchan not running or not responding. */
658         emit(&msg, P_ERROR, "Switch disabled");
659     }
660 }
661
662 static const char *
663 discovery_state_label(const char *name)
664 {
665     static struct dict *states;
666     if (!states) {
667         states = xmalloc(sizeof *states);
668         dict_init(states);
669         dict_add(states, "INIT", "Init");
670         dict_add(states, "INIT_REBOOT", "Init");
671         dict_add(states, "REBOOTING", "Init");
672         dict_add(states, "SELECTING", "Searching");
673         dict_add(states, "REQUESTING", "Requesting");
674         dict_add(states, "BOUND", "Got");
675         dict_add(states, "RENEWING", "Renewing");
676         dict_add(states, "REBINDING", "Rebinding");
677         dict_add(states, "RELEASED", "Released");
678     }
679     return dict_get_string(states, name, "Error");
680 }
681
682 static void
683 show_discovery_state(const struct dict *dict)
684 {
685     static struct message *m_bound, *m_other;
686     struct message **m;
687     const char *state, *ip;
688     enum priority priority;
689     int state_elapsed;
690
691     state = dict_get_string(dict, "discovery.state", NULL);
692     if (!state) {
693         return;
694     }
695     ip = dict_get_string(dict, "discovery.ip", NULL);
696     state_elapsed = dict_get_int(dict, "discovery.state-elapsed", 0);
697
698     if (!strcmp(state, "BOUND")) {
699         m = &m_bound;
700         priority = P_STATUS;
701     } else {
702         m = &m_other;
703         priority = P_PROGRESS;
704     }
705     emit(m, priority, "Discovery %s\n%s",
706          progress(), discovery_state_label(state));
707     if (ip) {
708         emit(m, priority, " %s", ip);
709     }
710 }
711
712 static void
713 human_time(int seconds, char *buf, size_t size)
714 {
715     const char *sign = "";
716     if (seconds < 0) {
717         sign = "-";
718         seconds = seconds == INT_MIN ? INT_MAX : -seconds;
719     }
720
721     if (seconds <= 60) {
722         snprintf(buf, size, "%s%d s", sign, seconds);
723     } else if (seconds <= 60 * 60) {
724         snprintf(buf, size, "%s%d min", sign, seconds / 60);
725     } else if (seconds <= 60 * 60 * 24 * 2) {
726         snprintf(buf, size, "%s%d h", sign, seconds / 60 / 60);
727     } else {
728         snprintf(buf, size, "%s%d days", sign, seconds / 60 / 60 / 24);
729     }
730 }
731
732 static void
733 show_fail_open_state(const struct dict *dict)
734 {
735     static struct message *m;
736     int cur_duration, trigger_duration;
737
738     if (!dict_get_bool(dict, "fail-open.triggered", false)) {
739         return;
740     }
741     trigger_duration = dict_get_int(dict, "fail-open.trigger-duration", 0);
742     cur_duration = dict_get_int(dict, "fail-open.current-duration", 0);
743     if (shown(&m) < 5) {
744         emit(&m, P_WARNING, "Failed open %s\nafter %d secs",
745              progress(), trigger_duration);
746     } else {
747         char buf[16];
748         human_time(cur_duration - trigger_duration, buf, sizeof buf);
749         emit(&m, P_WARNING, "In fail open for\n%s now %s", buf, progress());
750     }
751 }
752
753 static const char *
754 progress(void)
755 {
756     return "..." + (3 - (unsigned int) time_now() % 4);
757 }
758
759 static void
760 show_remote_state(const struct dict *dict)
761 {
762     bool debug_mode = dict_get_bool(dict, "debug", false);
763     const char *state, *is_connected;
764
765     state = dict_get_string(dict, "remote.state", NULL);
766     if (!state) {
767         return;
768     }
769     is_connected = dict_get_string(dict, "remote.is-connected", "false");
770     if (!strcmp(is_connected, "true")) {
771         if (debug_mode) {
772             static struct message *m_connected;
773             char buf[16];
774             human_time(dict_get_int(dict, "remote.last-connection", 0),
775                        buf, sizeof buf);
776             emit(&m_connected, P_STATUS,
777                  "Connected for\nlast %s %s", buf, progress());
778         }
779
780         if (!strcmp(state, "IDLE")) {
781             static struct message *m_idle;
782             emit(&m_idle, P_PROGRESS, "Sent idle probe");
783         }
784
785         if (debug_mode) {
786             const char *name = dict_get_string(dict, "remote.name", NULL);
787             if (name) {
788                 static struct message *m_name;
789                 emit(&m_name, P_STATUS, "Connected to\n%s", name);
790             }
791         }
792     } else {
793         int elapsed, backoff;
794         const char *name, *error;
795
796         elapsed = dict_get_int(dict, "remote.state-elapsed", 0);
797         backoff = dict_get_int(dict, "remote.backoff", 0);
798         name = dict_get_string(dict, "remote.name", "unknown");
799         state = dict_get_string(dict, "remote.state", "VOID");
800         error = dict_get_string(dict, "remote.last-connect-error", NULL);
801         if (!strcmp(state, "VOID")) {
802             static struct message *m;
803             emit(&m, P_PROGRESS, "Controller not\nfound");
804         } else if (!strcmp(state, "BACKOFF")) {
805             static struct message *m[3];
806             char buf[16];
807
808             if (error) {
809                 emit(&m[0], P_PROGRESS, "Connect failed:\n%s", error);
810             }
811             emit(&m[2], P_STATUS, "Last connected\n%s ago", buf);
812             emit(&m[1], P_PROGRESS,
813                  "Disconnected\nReconnect in %d", backoff - elapsed);
814             human_time(dict_get_int(dict, "remote.last-connection", 0),
815                        buf, sizeof buf);
816         } else if (!strcmp(state, "CONNECTING")) {
817             static struct message *m;
818             emit(&m, P_PROGRESS, "Connecting %s\n%s", progress(), name);
819         }
820     }
821 }
822
823 static void
824 fetch_status(struct rconn *rconn, struct dict *dict, long long timeout)
825 {
826     static struct rconn_packet_counter *counter;
827     static uint32_t xid;
828     struct nicira_header *rq;
829     struct ofpbuf *b;
830     int retval;
831
832     if (!counter) {
833         counter = rconn_packet_counter_create();
834     }
835     if (!xid) {
836         xid = random_uint32();
837     }
838
839     rq = make_openflow_xid(sizeof *rq, OFPT_VENDOR, ++xid, &b);
840     rq->vendor = htonl(NX_VENDOR_ID);
841     rq->subtype = htonl(NXT_STATUS_REQUEST);
842     retval = rconn_send_with_limit(rconn, b, counter, 10);
843     if (retval) {
844         /* continue into the loop so that we pause for a while */
845     }
846
847     while (time_msec() < timeout) {
848         int i;
849
850         rconn_run(rconn);
851
852         for (i = 0; i < 50; i++) {
853             struct ofpbuf *b;
854             bool got_reply;
855
856             b = rconn_recv(rconn);
857             if (!b) {
858                 break;
859             }
860
861             got_reply = parse_reply(b->data, dict, xid);
862             ofpbuf_delete(b);
863             if (got_reply) {
864                 return;
865             }
866         }
867
868         rconn_run_wait(rconn);
869         rconn_recv_wait(rconn);
870         poll_timer_wait(timeout - time_msec());
871         poll_block();
872     }
873 }
874
875 static bool
876 parse_reply(void *data, struct dict *dict, uint32_t xid)
877 {
878     struct ofp_header *oh;
879     struct nicira_header *rpy;
880
881     oh = data;
882     if (ntohs(oh->length) < sizeof *rpy) {
883         VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
884         return false;
885     }
886     if (oh->xid != xid) {
887         VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32, oh->xid, xid);
888         return false;
889     }
890     if (oh->type != OFPT_VENDOR) {
891         VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
892         return false;
893     }
894
895     rpy = data;
896     if (rpy->vendor != htonl(NX_VENDOR_ID)) {
897         VLOG_WARN("reply has wrong vendor ID %08"PRIx32, rpy->vendor);
898         return false;
899     }
900     if (rpy->subtype != htonl(NXT_STATUS_REPLY)) {
901         VLOG_WARN("reply has wrong subtype %08"PRIx32, rpy->subtype);
902         return false;
903     }
904
905     dict_parse(dict, (const char *) (rpy + 1),
906                ntohs(oh->length) - sizeof *rpy);
907     return true;
908 }
909
910 static void
911 dict_parse(struct dict *dict, const char *data, size_t nbytes)
912 {
913     char *save_ptr = NULL;
914     char *copy, *name;
915
916     copy = xmemdup0(data, nbytes);
917     for (name = strtok_r(copy, "=", &save_ptr); name;
918          name = strtok_r(NULL, "=", &save_ptr))
919     {
920         char *value = strtok_r(NULL, "\n", &save_ptr);
921         if (!value) {
922             break;
923         }
924         dict_add(dict, name, value);
925     }
926     free(copy);
927 }
928
929 static void
930 dict_init(struct dict *dict)
931 {
932     dict->n = 0;
933     dict->max = 16;
934     dict->pairs = xmalloc(sizeof *dict->pairs * dict->max);
935 }
936
937 static void
938 dict_add(struct dict *dict, const char *name, const char *value)
939 {
940     dict_add_nocopy(dict, xstrdup(name), xstrdup(value));
941 }
942
943 static void
944 dict_add_nocopy(struct dict *dict, char *name, char *value)
945 {
946     struct pair *p;
947
948     if (dict->n >= dict->max) {
949         dict->max *= 2;
950         dict->pairs = xrealloc(dict->pairs, sizeof *dict->pairs * dict->max);
951     }
952     p = &dict->pairs[dict->n++];
953     p->name = name;
954     p->value = value;
955 }
956
957 static void
958 dict_delete(struct dict *dict, const char *name)
959 {
960     size_t idx;
961     while ((idx = dict_find(dict, name)) != SIZE_MAX) {
962         struct pair *pair = &dict->pairs[idx];
963         free(pair->name);
964         free(pair->value);
965         dict->pairs[idx] = dict->pairs[--dict->n];
966     }
967 }
968
969 static void
970 dict_free(struct dict *dict)
971 {
972     if (dict) {
973         size_t i;
974
975         for (i = 0; i < dict->n; i++) {
976             free(dict->pairs[i].name);
977             free(dict->pairs[i].value);
978         }
979         free(dict->pairs);
980     }
981 }
982
983 static void
984 initialize_terminal(void)
985 {
986     initscr();
987     cbreak();
988     noecho();
989     nonl();
990     intrflush(stdscr, FALSE);
991     keypad(stdscr, TRUE);
992     nodelay(stdscr, TRUE);
993     typeahead(-1);
994     scrollok(stdscr, TRUE);
995 }
996
997 static void
998 restore_terminal(void *aux UNUSED)
999 {
1000     endwin();
1001 }
1002 \f
1003 struct byte_count {
1004     long long int when;
1005     uint64_t tx_bytes;
1006 };
1007
1008 struct show_rates_data {
1009     struct rconn *rconn;
1010     uint32_t xid;
1011     struct byte_count prev, now;
1012     bool got_reply;
1013 };
1014
1015 static void
1016 parse_port_reply(void *data, struct show_rates_data *rates)
1017 {
1018     struct ofp_header *oh;
1019     struct ofp_stats_reply *rpy;
1020     struct ofp_port_stats *ops;
1021     size_t n_ports;
1022     size_t i;
1023
1024     oh = data;
1025     if (ntohs(oh->length) < sizeof *rpy) {
1026         VLOG_WARN("reply is too short (%"PRIu16")", ntohs(oh->length));
1027         return;
1028     }
1029     if (oh->xid != rates->xid) {
1030         VLOG_WARN("xid 0x%08"PRIx32" != expected 0x%08"PRIx32,
1031                   oh->xid, rates->xid);
1032         return;
1033     }
1034     if (oh->type != OFPT_STATS_REPLY) {
1035         VLOG_WARN("reply is wrong type %"PRIu8, oh->type);
1036         return;
1037     }
1038
1039     rpy = data;
1040     if (rpy->type != htons(OFPST_PORT)) {
1041         VLOG_WARN("reply has wrong stat type ID %08"PRIx16, rpy->type);
1042         return;
1043     }
1044
1045     n_ports = ((ntohs(oh->length) - offsetof(struct ofp_stats_reply, body))
1046                / sizeof *ops);
1047     ops = (struct ofp_port_stats *) rpy->body;
1048     rates->prev = rates->now;
1049     rates->now.when = time_msec();
1050     rates->now.tx_bytes = UINT64_MAX;
1051     for (i = 0; i < n_ports; i++, ops++) {
1052         if (ops->tx_bytes != htonll(UINT64_MAX)) {
1053             if (rates->now.tx_bytes == UINT64_MAX) {
1054                 rates->now.tx_bytes = 0;
1055             }
1056             rates->now.tx_bytes += ntohll(ops->tx_bytes);
1057         }
1058     }
1059     rates->got_reply = true;
1060 }
1061
1062 static void
1063 dump_graph(const bool graph[80])
1064 {
1065     signed char icons[32];
1066     int n_icons = 3;
1067     int i;
1068
1069     memset(icons, -1, sizeof icons);
1070     for (i = 0; i < 16; i++) {
1071         uint8_t row;
1072         int j;
1073
1074         row = 0;
1075         for (j = 0; j < 5; j++) {
1076             row = (row << 1) | graph[i * 5 + j];
1077         }
1078         if (!row) {
1079             addch(' ');
1080             continue;
1081         }
1082
1083         if (icons[row] < 0) {
1084             if (n_icons >= 8) {
1085                 addch('X');
1086                 continue;
1087             }
1088             set_repeated_icon(n_icons, row);
1089             icons[row] = n_icons++;
1090         }
1091         put_icon(icons[row], row == 0x1f ? '#' : ' ');
1092     }
1093 }
1094
1095 static void
1096 do_show_data_rates(void *rates_)
1097 {
1098     struct show_rates_data *rates = rates_;
1099     static struct rconn_packet_counter *counter;
1100     bool graph[80];
1101
1102     if (!counter) {
1103         counter = rconn_packet_counter_create();
1104     }
1105     if (!rates->xid) {
1106         struct ofp_stats_request *rq;
1107         struct ofpbuf *b;
1108
1109         rates->xid = random_uint32();
1110         rq = make_openflow_xid(sizeof *rq, OFPT_STATS_REQUEST,
1111                                rates->xid, &b);
1112         rq->type = htons(OFPST_PORT);
1113         rq->flags = htons(0);
1114         rconn_send_with_limit(rates->rconn, b, counter, 10);
1115     }
1116
1117     if (!rates->got_reply) {
1118         int i;
1119
1120         rconn_run(rates->rconn);
1121         for (i = 0; i < 50; i++) {
1122             struct ofpbuf *b;
1123
1124             b = rconn_recv(rates->rconn);
1125             if (!b) {
1126                 break;
1127             }
1128
1129             parse_port_reply(b->data, rates);
1130             ofpbuf_delete(b);
1131             if (rates->got_reply) {
1132                 break;
1133             }
1134         }
1135     }
1136
1137     set_icon(0,
1138              e_____,
1139              e_____,
1140              e_____,
1141              e__X__,
1142              e__X__,
1143              e__X_X,
1144              e__XX_,
1145              e__X_X);
1146     set_icon(1,
1147              e_____,
1148              e_____,
1149              e_____,
1150              eX___X,
1151              eXX_XX,
1152              eX_X_X,
1153              eX___X,
1154              eX___X);
1155     set_icon(2,
1156              e_____,
1157              e_____,
1158              e_____,
1159              e_XXX_,
1160              eX____,
1161              eX_XXX,
1162              eX___X,
1163              e_XXX_);
1164
1165     memset(graph, 0, sizeof graph);
1166     graph[24] = 1;
1167     graph[48] = 1;
1168     graph[72] = 1;
1169
1170     addstr("TX: ");
1171     put_icon(0, 'k');
1172     addstr("    ");
1173     put_icon(1, 'M');
1174     addstr("    ");
1175     put_icon(2, 'G');
1176     addch('\n');
1177
1178     if (rates->now.tx_bytes != UINT64_MAX
1179         && rates->prev.tx_bytes != UINT64_MAX
1180         && rates->now.when - rates->prev.when > 500
1181         && time_msec() - rates->now.when < 2000)
1182     {
1183         uint64_t bits = (rates->now.tx_bytes - rates->prev.tx_bytes) * 8;
1184         uint64_t msecs = rates->now.when - rates->prev.when;
1185         double bps = (double) bits * 1000.0 / msecs;
1186         int pixels = bps > 0 ? log(bps) / log(10.0) * 8 + .5 : 0;
1187         if (pixels < 0) {
1188             pixels = 0;
1189         } else if (pixels > 80) {
1190             pixels = 80;
1191         }
1192         memset(graph, 1, pixels);
1193     }
1194
1195     dump_graph(graph);
1196
1197     if (!rates->got_reply) {
1198         rconn_run_wait(rates->rconn);
1199         rconn_recv_wait(rates->rconn);
1200     }
1201 }
1202
1203 static void
1204 show_data_rates(struct rconn *rconn, const struct dict *dict)
1205 {
1206     static struct message *m;
1207     static struct show_rates_data rates;
1208     const char *is_connected, *local_ip;
1209     static bool inited = false;
1210
1211     dict_lookup(dict, "local.is-connected", &is_connected);
1212     dict_lookup(dict, "in-band.local-ip", &local_ip);
1213     if (!is_connected && !local_ip) {
1214         /* If we're not connected to the datapath and don't have a local IP,
1215          * then we won't have anything useful to show anyhow. */
1216         return;
1217     }
1218
1219     rates.rconn = rconn;
1220     rates.xid = 0;
1221     rates.got_reply = false;
1222     if (!inited) {
1223         rates.now.tx_bytes = UINT64_MAX;
1224         rates.prev.tx_bytes = UINT64_MAX;
1225         inited = true;
1226     }
1227     emit_function(&m, P_STATUS, do_show_data_rates, &rates);
1228 }
1229 \f
1230 struct message {
1231     /* Content. */
1232     void (*function)(void *aux);
1233     void *aux;
1234     char string[128];
1235
1236     size_t index;
1237     enum priority priority;
1238     int age;
1239     int shown;
1240 };
1241
1242 static struct message **messages;
1243 static size_t n_messages, allocated_messages;
1244
1245 static struct message *
1246 allocate_message(struct message **msgp)
1247 {
1248     if (!*msgp) {
1249         /* Allocate and initialize message. */
1250         *msgp = xcalloc(1, sizeof **msgp);
1251         (*msgp)->index = n_messages;
1252
1253         /* Add to list of messages. */
1254         if (n_messages >= allocated_messages) {
1255             allocated_messages = 2 * allocated_messages + 1;
1256             messages = xrealloc(messages,
1257                                 sizeof *messages * allocated_messages);
1258         }
1259         messages[n_messages++] = *msgp;
1260     }
1261     return *msgp;
1262 }
1263
1264 static void
1265 emit(struct message **msgp, enum priority priority, const char *format, ...)
1266 {
1267     struct message *msg = allocate_message(msgp);
1268     va_list args;
1269     size_t length;
1270
1271     msg->priority = priority;
1272
1273     va_start(args, format);
1274     length = strlen(msg->string);
1275     vsnprintf(msg->string + length, sizeof msg->string - length, format, args);
1276     va_end(args);
1277 }
1278
1279 static void
1280 emit_function(struct message **msgp, enum priority priority,
1281               void (*function)(void *aux), void *aux)
1282 {
1283     struct message *msg = allocate_message(msgp);
1284     msg->priority = priority;
1285     msg->function = function;
1286     msg->aux = aux;
1287 }
1288
1289 static int
1290 shown(struct message **msgp)
1291 {
1292     struct message *msg = allocate_message(msgp);
1293     return msg->shown;
1294 }
1295
1296 static void
1297 clear_messages(void)
1298 {
1299     size_t i;
1300
1301     for (i = 0; i < n_messages; i++) {
1302         struct message *msg = messages[i];
1303         msg->string[0] = '\0';
1304         msg->function = NULL;
1305     }
1306 }
1307
1308 static struct message *
1309 best_message(void)
1310 {
1311     struct message *best_msg;
1312     int best_score;
1313     size_t i;
1314
1315     best_score = INT_MIN;
1316     best_msg = NULL;
1317     for (i = 0; i < n_messages; i++) {
1318         struct message *msg = messages[i];
1319         int score;
1320
1321         if (empty_message(msg)) {
1322             continue;
1323         }
1324
1325         score = msg->priority;
1326         if (!msg->shown) {
1327             score += msg->age;
1328         } else {
1329             score -= msg->shown;
1330         }
1331         if (score > best_score) {
1332             best_score = score;
1333             best_msg = msg;
1334         }
1335     }
1336     return best_msg;
1337 }
1338
1339 static void
1340 message_shown(struct message *msg)
1341 {
1342     if (msg && msg->shown++ > 3600) {
1343         msg->shown = 0;
1344     }
1345 }
1346
1347 static bool
1348 empty_message(const struct message *msg) 
1349 {
1350     return !msg || (!msg->string[0] && !msg->function);
1351 }
1352
1353 static struct message *get_message(size_t index)
1354 {
1355     assert(index <= n_messages || index == SIZE_MAX);
1356     return (index < n_messages ? messages[index]
1357             : index == SIZE_MAX ? messages[n_messages - 1]
1358             : messages[0]);
1359 }
1360
1361 static struct message *
1362 next_message(struct message *msg)
1363 {
1364     struct message *p;
1365
1366     for (p = get_message(msg->index + 1); p != msg;
1367          p = get_message(p->index + 1)) {
1368         if (!empty_message(p)) {
1369             break;
1370         }
1371     }
1372     return p;
1373 }
1374
1375 static struct message *
1376 prev_message(struct message *msg)
1377 {
1378     struct message *p;
1379
1380     for (p = get_message(msg->index - 1); p != msg;
1381          p = get_message(p->index - 1)) {
1382         if (!empty_message(p)) {
1383             break;
1384         }
1385     }
1386     return p;
1387 }
1388
1389 static void
1390 put_message(const struct message *m)
1391 {
1392     if (m->string[0]) {
1393         addstr(m->string);
1394     } else if (m->function) {
1395         m->function(m->aux);
1396     }
1397 }
1398
1399 static void
1400 age_messages(void)
1401 {
1402     size_t i;
1403     int load;
1404
1405     load = 0;
1406     for (i = 0; i < n_messages; i++) {
1407         struct message *msg = messages[i];
1408         if (!empty_message(msg)) {
1409             load++;
1410         }
1411     }
1412
1413     for (i = 0; i < n_messages; i++) {
1414         struct message *msg = messages[i];
1415         if (empty_message(msg)) {
1416             msg->age = msg->shown = 0;
1417         } else {
1418             if (msg->age && msg->age % 60 == 0) {
1419                 msg->shown -= MAX(0, 5 - (load + 6) / 12);
1420                 if (msg->shown < 0) {
1421                     msg->shown = 0;
1422                 }
1423             }
1424             if (msg->age++ > 3600) {
1425                 msg->age = 0;
1426             }
1427         }
1428     }
1429 }
1430 \f
1431 /* Set by SIGUSR1 handler. */
1432 static volatile sig_atomic_t sigusr1_triggered;
1433
1434 /* The time after which we stop indicating that the switch is rebooting.
1435  * (This is just in case the reboot fails.) */
1436 static time_t reboot_deadline = TIME_MIN;
1437
1438 static void sigusr1_handler(int);
1439
1440 static void
1441 init_reboot_notifier(void)
1442 {
1443     signal(SIGUSR1, sigusr1_handler);
1444 }
1445
1446 static void
1447 sigusr1_handler(int signr UNUSED)
1448 {
1449     sigusr1_triggered = true;
1450 }
1451
1452 static bool
1453 show_reboot_state(void)
1454 {
1455     if (sigusr1_triggered) {
1456         reboot_deadline = time_now() + 30;
1457         sigusr1_triggered = false;
1458     }
1459     if (time_now() < reboot_deadline) {
1460         static struct message *msg;
1461         emit(&msg, P_FATAL, "Rebooting");
1462         return true;
1463     }
1464     return false;
1465 }
1466 \f
1467 struct menu_item {
1468     char *text;
1469     void (*f)(const struct dict *);
1470     int id;
1471     bool enabled;
1472     int toggle;
1473 };
1474
1475 struct menu {
1476     struct menu_item **items;
1477     size_t n_items, allocated_items;
1478 };
1479
1480 static void menu_init(struct menu *);
1481 static void menu_free(struct menu *);
1482 static struct menu_item *menu_add_item(struct menu *, const char *text, ...)
1483     PRINTF_FORMAT(2, 3);
1484 static int menu_show(const struct menu *, int start, bool select);
1485
1486 static void cmd_shell(const struct dict *);
1487 static void cmd_show_version(const struct dict *);
1488 static void cmd_configure(const struct dict *);
1489 static void cmd_setup_pki(const struct dict *);
1490 static void cmd_browse_status(const struct dict *);
1491 static void cmd_show_motto(const struct dict *);
1492
1493 static void
1494 menu_init(struct menu *menu)
1495 {
1496     memset(menu, 0, sizeof *menu);
1497 }
1498
1499 static void
1500 menu_free(struct menu *menu)
1501 {
1502     size_t i;
1503
1504     for (i = 0; i < menu->n_items; i++) {
1505         struct menu_item *item = menu->items[i];
1506         free(item->text);
1507         free(item);
1508     }
1509     free(menu->items);
1510 }
1511
1512 static struct menu_item *
1513 menu_add_item(struct menu *menu, const char *text, ...)
1514 {
1515     struct menu_item *item;
1516     va_list args;
1517
1518     if (menu->n_items >= menu->allocated_items) {
1519         menu->allocated_items = 2 * menu->allocated_items + 1;
1520         menu->items = xrealloc(menu->items,
1521                                sizeof *menu->items * menu->allocated_items);
1522     }
1523     item = menu->items[menu->n_items++] = xmalloc(sizeof *item);
1524     va_start(args, text);
1525     item->text = xvasprintf(text, args);
1526     va_end(args);
1527     item->f = NULL;
1528     item->id = -1;
1529     item->enabled = true;
1530     item->toggle = -1;
1531     return item;
1532 }
1533
1534 static void
1535 menu(const struct dict *dict)
1536 {
1537     bool debug_mode = dict_get_bool(dict, "debug", false);
1538     struct menu menu;
1539     int choice;
1540
1541     menu_init(&menu);
1542     menu_add_item(&menu, "Exit");
1543     menu_add_item(&menu, "Show Version")->f = cmd_show_version;
1544     menu_add_item(&menu, "Configure")->f = cmd_configure;
1545     menu_add_item(&menu, "Setup PKI")->f = cmd_setup_pki;
1546     if (debug_mode) {
1547         menu_add_item(&menu, "Browse Status")->f = cmd_browse_status;
1548         menu_add_item(&menu, "Shell")->f = cmd_shell;
1549         menu_add_item(&menu, "Show Motto")->f = cmd_show_motto;
1550     }
1551
1552     choice = menu_show(&menu, 0, true);
1553     if (choice >= 0) {
1554         void (*f)(const struct dict *) = menu.items[choice]->f;
1555         if (f) {
1556             (f)(dict);
1557         }
1558     }
1559
1560     menu_free(&menu);
1561 }
1562
1563 static int
1564 menu_show(const struct menu *menu, int start, bool select)
1565 {
1566     long long int adjust = LLONG_MAX;
1567     int min = 0, max = MAX(menu->n_items - 2, 0);
1568     int pos, selection;
1569     set_icon(0,
1570              eXX___,
1571              eXXX__,
1572              eXXXX_,
1573              eXXXXX,
1574              eXXXX_,
1575              eXXX__,
1576              eXX___,
1577              e_____);
1578     set_icon(1,
1579              eXXXXX,
1580              eX___X,
1581              eX___X,
1582              eX___X,
1583              eX___X,
1584              eX___X,
1585              eXXXXX,
1586              e_____);
1587     set_icon(2,
1588              eXXXXX,
1589              eX___X,
1590              eXX_XX,
1591              eX_X_X,
1592              eXX_XX,
1593              eX___X,
1594              eXXXXX,
1595              e_____);
1596     if (menu->n_items) {
1597         pos = MIN(menu->n_items - 1, MAX(0, start));
1598         selection = pos;
1599     } else {
1600         pos = 0;
1601         selection = -1;
1602     }
1603     for (;;) {
1604         int key;
1605
1606         while ((key = getch()) != ERR) {
1607             switch (key) {
1608             case KEY_UP:
1609                 if (select && selection > 0) {
1610                     selection--;
1611                     if (selection >= pos) {
1612                         break;
1613                     }
1614                 }
1615                 if (pos >= min) {
1616                     pos--;
1617                 }
1618                 break;
1619
1620             case KEY_DOWN:
1621                 if (select && selection < menu->n_items - 1) {
1622                     selection++;
1623                     if (selection <= pos + 1) {
1624                         break;
1625                     }
1626                 }
1627                 if (pos <= max) {
1628                     pos++;
1629                 }
1630                 break;
1631
1632             case '\r': case '\n':
1633                 if (select && selection >= 0 && selection < menu->n_items) {
1634                     struct menu_item *item = menu->items[selection];
1635                     if (!item->enabled) {
1636                         show_string("Item disabled");
1637                         break;
1638                     } else if (item->toggle >= 0) {
1639                         item->toggle = !item->toggle;
1640                         break;
1641                     }
1642                 }
1643                 return selection;
1644
1645             case '\b': case '\x7f': case '\x1b':
1646             case KEY_BACKSPACE: case KEY_DC:
1647                 return -1;
1648             }
1649             adjust = time_msec() + 1000;
1650         }
1651         if (time_msec() >= adjust && menu->n_items > 1) {
1652             if (pos < min) {
1653                 pos = min;
1654             } else if (pos > max) {
1655                 pos = max;
1656             }
1657         }
1658
1659         erase();
1660         curs_set(0);
1661         move(0, 0);
1662         if (!menu->n_items) {
1663             addstr("[Empty]");
1664         } else {
1665             int idx;
1666             for (idx = pos; idx < pos + 2; idx++) {
1667                 size_t width = 40;
1668
1669                 if (select) {
1670                     width--;
1671                     if (selection == idx) {
1672                         put_icon(0, '>');
1673                     } else {
1674                         addch(' ');
1675                     }
1676                 }
1677
1678                 if (idx < 0) {
1679                     addstr("[Top]");
1680                 } else if (idx >= menu->n_items) {
1681                     addstr("[Bottom]");
1682                 } else {
1683                     const struct menu_item *item = menu->items[idx];
1684                     size_t length = strlen(item->text);
1685                     if (!item->enabled) {
1686                         width -= 2;
1687                         addch('(');
1688                     }
1689                     if (item->toggle >= 0) {
1690                         if (have_icons()) {
1691                             addch(icon_char(item->toggle ? 2 : 1, 0));
1692                             width--;
1693                         } else {
1694                             addstr(item->toggle ? "[X]" : "[ ]");
1695                             width -= 3;
1696                         }
1697                     }
1698                     addnstr(item->text, MIN(width, length));
1699                     if (!item->enabled) {
1700                         addch(')');
1701                     }
1702                 }
1703                 if (idx == pos) {
1704                     addch('\n');
1705                 }
1706             }
1707         }
1708         refresh();
1709
1710         if (pos < min || pos > max) {
1711             poll_timer_wait(adjust - time_msec());
1712         }
1713         poll_fd_wait(STDIN_FILENO, POLLIN);
1714         poll_block();
1715     }
1716 }
1717
1718 static int
1719 menu_show2(const struct menu *menu, int start, bool select)
1720 {
1721     int pos;
1722     if (menu->n_items) {
1723         pos = MIN(menu->n_items - 1, MAX(0, start));
1724     } else {
1725         pos = -1;
1726     }
1727     set_icon(0,
1728              e__X__,
1729              e_XXX_,
1730              eXXXXX,
1731              e__X__,
1732              e__X__,
1733              e__X__,
1734              e__X__,
1735              e__X__);
1736     set_icon(1,
1737              e__X__,
1738              e__X__,
1739              e__X__,
1740              e__X__,
1741              e__X__,
1742              eXXXXX,
1743              e_XXX_,
1744              e__X__);
1745     for (;;) {
1746         int key;
1747
1748         while ((key = getch()) != ERR) {
1749             switch (key) {
1750             case KEY_UP:
1751                 if (pos > 0) {
1752                     pos--;
1753                 }
1754                 break;
1755
1756             case KEY_DOWN:
1757                 if (menu->n_items > 0 && pos < menu->n_items - 1) {
1758                     pos++;
1759                 }
1760                 break;
1761
1762             case '\r': case '\n':
1763                 if (select && !menu->items[pos]->enabled) {
1764                     show_string("Item disabled");
1765                     break;
1766                 }
1767                 return pos;
1768
1769             case '\b': case '\x7f': case '\x1b':
1770             case KEY_BACKSPACE: case KEY_DC:
1771                 return -1;
1772             }
1773         }
1774
1775         erase();
1776         curs_set(0);
1777         move(0, 0);
1778         if (pos == -1) {
1779             addstr("[Empty]");
1780         } else {
1781             const struct menu_item *item = menu->items[pos];
1782             const char *line1 = item->text;
1783             size_t len1 = strcspn(line1, "\n");
1784             const char *line2 = line1[len1] ? &line1[len1 + 1] : "";
1785             size_t len2 = strcspn(line2, "\n");
1786             size_t width = 39 - 2 * !item->enabled;
1787
1788             /* First line. */
1789             addch(pos > 0 ? icon_char(0, '^') : ' ');
1790             if (!item->enabled && len1) {
1791                 addch('(');
1792             }
1793             addnstr(line1, MIN(len1, width));
1794             if (!item->enabled && len1) {
1795                 addch(')');
1796             }
1797             addch('\n');
1798
1799             /* Second line. */
1800             addch(pos < menu->n_items - 1 ? icon_char(1, 'V') : ' ');
1801             if (!item->enabled && len2) {
1802                 addch('(');
1803             }
1804             addnstr(line2, MIN(len2, width));
1805             if (!item->enabled && len2) {
1806                 addch(')');
1807             }
1808         }
1809         refresh();
1810
1811         poll_fd_wait(STDIN_FILENO, POLLIN);
1812         poll_block();
1813     }
1814 }
1815
1816 static bool
1817 yesno(const char *title, bool def)
1818 {
1819     bool answer = def;
1820
1821     set_icon(0,
1822              eXX___,
1823              eXXX__,
1824              eXXXX_,
1825              eXXXXX,
1826              eXXXX_,
1827              eXXX__,
1828              eXX___,
1829              e_____);
1830
1831     for (;;) {
1832         int key;
1833
1834         while ((key = getch()) != ERR) {
1835             switch (key) {
1836             case KEY_UP:
1837             case KEY_DOWN:
1838             case KEY_LEFT:
1839             case KEY_RIGHT:
1840                 answer = !answer;
1841                 break;
1842
1843             case 'y': case 'Y':
1844                 answer = true;
1845                 break;
1846
1847             case 'n': case 'N':
1848                 answer = false;
1849                 break;
1850
1851             case '\r': case '\n':
1852                 return answer;
1853             }
1854         }
1855
1856         erase();
1857         curs_set(0);
1858         move(0, 0);
1859         addstr(title);
1860
1861         move(0, 12);
1862         addch(answer ? icon_char(0, '>') : ' ');
1863         addstr("Yes");
1864
1865         move(1, 12);
1866         addch(!answer ? icon_char(0, '>') : ' ');
1867         addstr("No");
1868
1869         refresh();
1870
1871         poll_fd_wait(STDIN_FILENO, POLLIN);
1872         poll_block();
1873     }
1874 }
1875
1876 static void
1877 cmd_show_version(const struct dict *dict UNUSED)
1878 {
1879     show_string(VERSION BUILDNR);
1880 }
1881
1882 static void
1883 cmd_browse_status(const struct dict *dict)
1884 {
1885     struct menu menu;
1886     size_t i;
1887
1888     menu_init(&menu);
1889     for (i = 0; i < dict->n; i++) {
1890         const struct pair *p = &dict->pairs[i];
1891         menu_add_item(&menu, "%s = %s", p->name, p->value); 
1892     }
1893     menu_show(&menu, 0, false);
1894     menu_free(&menu);
1895 }
1896
1897 static void
1898 cmd_shell(const struct dict *dict UNUSED)
1899 {
1900     const char *home;
1901
1902     erase();
1903     refresh();
1904     endwin();
1905
1906     printf("Type ^D to exit\n");
1907     fflush(stdout);
1908
1909     putenv("PS1=#");
1910     putenv("PS2=>");
1911     putenv("PS3=?");
1912     putenv("PS4=+");
1913     home = getenv("HOME");
1914     if (home) {
1915         chdir(home);
1916     }
1917     system("/bin/sh");
1918     initialize_terminal();
1919 }
1920
1921 static void
1922 cmd_show_motto(const struct dict *dict UNUSED)
1923 {
1924     show_string("\"Just Add Ice\"");
1925 }
1926
1927 static void
1928 show_string(const char *string)
1929 {
1930     VLOG_INFO("%s", string);
1931     erase();
1932     curs_set(0);
1933     move(0, 0);
1934     addstr(string);
1935     refresh();
1936     block_until(time_msec() + 5000);
1937 }
1938
1939 static void
1940 block_until(long long timeout)
1941 {
1942     while (timeout > time_msec()) {
1943         poll_timer_wait(timeout - time_msec());
1944         poll_block();
1945     }
1946     drain_keyboard_buffer();
1947 }
1948
1949 static void
1950 drain_keyboard_buffer(void)
1951 {
1952     while (getch() != ERR) {
1953         continue;
1954     }
1955 }
1956 \f
1957 static int
1958 read_vars(const char *cmd, struct dict *dict)
1959 {
1960     struct ds ds;
1961     FILE *stream;
1962     int status;
1963
1964     stream = popen(cmd, "r");
1965     if (!stream) {
1966         VLOG_ERR("popen(\"%s\") failed: %s", cmd, strerror(errno));
1967         return errno;
1968     }
1969
1970     dict_init(dict);
1971     ds_init(&ds);
1972     while (!ds_get_line(&ds, stream)) {
1973         const char *s = ds_cstr(&ds);
1974         const char *equals = strchr(s, '=');
1975         if (equals) {
1976             dict_add_nocopy(dict,
1977                             xmemdup0(s, equals - s), xstrdup(equals + 1));
1978         }
1979     }
1980     status = pclose(stream);
1981     if (status) {
1982         char *msg = process_status_msg(status);
1983         VLOG_ERR("pclose(\"%s\") reported subprocess failure: %s",
1984                  cmd, msg);
1985         free(msg);
1986         dict_free(dict);
1987         return ECHILD;
1988     }
1989     return 0;
1990 }
1991
1992 static bool
1993 run_and_report_failure(char **argv, const char *title)
1994 {
1995     int null_fds[3] = {0, 1, 2};
1996     int status;
1997     int retval;
1998     char *s;
1999
2000     s = process_escape_args(argv);
2001     VLOG_INFO("starting subprocess: %s", s);
2002     free(s);
2003
2004     retval = process_run(argv, NULL, 0, null_fds, 3, &status);
2005     if (retval) {
2006         char *s = xasprintf("%s:\n%s", title, strerror(retval));
2007         show_string(s);
2008         free(s);
2009         return false;
2010     } else if (status) {
2011         char *msg = process_status_msg(status);
2012         char *s = xasprintf("%s:\n%s", title, msg);
2013         show_string(s);
2014         free(msg);
2015         free(s);
2016         return false;
2017     } else {
2018         VLOG_INFO("subprocess exited with status 0");
2019         return true;
2020     }
2021 }
2022
2023 static int
2024 do_load_config(const char *file_name, struct dict *dict)
2025 {
2026     struct dict auto_vars;
2027     int retval;
2028     char *cmd;
2029     size_t i;
2030
2031     /* Get the list of the variables that the shell sets automatically. */
2032     retval = read_vars("set -a && env", &auto_vars);
2033     if (retval) {
2034         return retval;
2035     }
2036
2037     /* Get the variables from 'file_name'. */
2038     cmd = xasprintf("set -a && . '%s' && env", file_name);
2039     retval = read_vars(cmd, dict);
2040     free(cmd);
2041     if (retval) {
2042         dict_free(&auto_vars);
2043         return retval;
2044     }
2045
2046     /* Subtract. */
2047     for (i = 0; i < auto_vars.n; i++) {
2048         dict_delete(dict, auto_vars.pairs[i].name);
2049     }
2050     dict_free(&auto_vars);
2051     return 0;
2052 }
2053
2054 static bool
2055 load_config(struct dict *dict)
2056 {
2057     static const char default_file[] = "/etc/default/openflow-switch";
2058     int retval = do_load_config(default_file, dict);
2059     if (!retval) {
2060         return true;
2061     } else {
2062         char *s = xasprintf("Cfg load failed:\n%s", strerror(retval));
2063         show_string(s);
2064         free(s);
2065         return false;
2066     }
2067 }
2068
2069 static bool
2070 save_config(const struct svec *settings)
2071 {
2072     struct svec argv;
2073     size_t i;
2074     bool ok;
2075
2076     VLOG_INFO("Saving configuration:");
2077     for (i = 0; i < settings->n; i++) {
2078         VLOG_INFO("%s", settings->names[i]);
2079     }
2080
2081     svec_init(&argv);
2082     svec_add(&argv, "/usr/share/openvswitch/commands/reconfigure");
2083     svec_append(&argv, settings);
2084     svec_terminate(&argv);
2085     ok = run_and_report_failure(argv.names, "Save failed");
2086     if (ok) {
2087         long long int timeout = time_msec() + 5000;
2088
2089         erase();
2090         curs_set(0);
2091         move(0, 0);
2092         addstr("Saved.\nRestarting...");
2093         refresh();
2094
2095         svec_clear(&argv);
2096         svec_add(&argv, "/bin/sh");
2097         svec_add(&argv, "-c");
2098         svec_add(&argv,
2099                  "/etc/init.d/openflow-switch restart >/dev/null 2>&1");
2100         svec_terminate(&argv);
2101
2102         ok = run_and_report_failure(argv.names, "Restart failed");
2103         if (ok) {
2104             block_until(timeout);
2105         }
2106     }
2107     svec_destroy(&argv);
2108
2109     if (ok) {
2110         VLOG_INFO("Save completed successfully");
2111     } else {
2112         VLOG_WARN("Save failed");
2113     }
2114     return ok;
2115 }
2116
2117 static int
2118 match(pcre *re, const char *string, int length)
2119 {
2120     int ovec[999];
2121     int retval;
2122
2123     retval = pcre_exec(re, NULL, string, length, 0, PCRE_PARTIAL,
2124                        ovec, ARRAY_SIZE(ovec));
2125     if (retval >= 0) {
2126         if (ovec[0] >= 0 && ovec[1] >= length) {
2127             /* 're' matched all of 'string'. */
2128             return 0;
2129         } else {
2130             /* 're' matched the initial part of 'string' but not all of it. */
2131             return PCRE_ERROR_NOMATCH;
2132         }
2133     } else {
2134         return retval;
2135     }
2136 }
2137
2138 static void
2139 figure_choices(pcre *re, struct ds *s, int pos, struct ds *choices)
2140 {
2141     struct ds tmp;
2142     int retval;
2143     char c;
2144
2145     ds_clear(choices);
2146
2147     /* See whether the current string is a complete match. */
2148     if (!match(re, s->string, pos)) {
2149         ds_put_char(choices, '\n');
2150     }
2151
2152     /* Then try all the other possibilities. */
2153     ds_init(&tmp);
2154     ds_put_buffer(&tmp, s->string, pos);
2155     for (c = 0x20; c < 0x7f; c++) {
2156         ds_put_char(&tmp, c);
2157         retval = match(re, tmp.string, pos + 1);
2158         if (retval == PCRE_ERROR_PARTIAL || !retval) {
2159             ds_put_char(choices, c);
2160         }
2161         tmp.length--;
2162     }
2163     ds_destroy(&tmp);
2164
2165     if (!choices->length) {
2166         ds_put_char(choices, '\n');
2167     }
2168 }
2169
2170 static void
2171 figure_completion(pcre *re, struct ds *s)
2172 {
2173     for (;;) {
2174         int found = -1;
2175         int c;
2176
2177         /* See whether the current string is a complete match. */
2178         if (!match(re, s->string, s->length)) {
2179             return;
2180         }
2181         for (c = 0x20; c < 0x7f; c++) {
2182             int retval;
2183
2184             ds_put_char(s, c);
2185             retval = match(re, s->string, s->length);
2186             s->length--;
2187
2188             if (retval == PCRE_ERROR_PARTIAL || !retval) {
2189                 if (found != -1) {
2190                     return;
2191                 }
2192                 found = c;
2193             }
2194         }
2195         if (found == -1) {
2196             return;
2197         }
2198         ds_put_char(s, found);
2199     }
2200 }
2201
2202 #define OCTET_RE "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
2203 #define IP_RE "("OCTET_RE"\\."OCTET_RE"\\."OCTET_RE"\\."OCTET_RE")"
2204 #define PORT_RE                                 \
2205     "([0-9]|"                                   \
2206     "[1-9][0-9]|"                               \
2207     "[1-9][0-9][0-9]|"                          \
2208     "[1-9][0-9][0-9][0-9]|"                     \
2209     "[1-5][0-9][0-9][0-9][0-9]|"                \
2210     "6[1-4][0-9][0-9][0-9]|"                    \
2211     "65[1-4][0-9][0-9]|"                        \
2212     "655[1-2][0-9]|"                            \
2213     "6553[1-5])"
2214 #define XOCTET_RE "[0-9A-F][0-9A-F]"
2215 #define MAC_RE \
2216         XOCTET_RE":"XOCTET_RE":"XOCTET_RE":"\
2217         XOCTET_RE":"XOCTET_RE":"XOCTET_RE
2218 #define NUM100_TO_99999_RE                      \
2219     "([1-9][0-9][0-9]|"                         \
2220     "[1-9][0-9][0-9][0-9]|"                     \
2221     "[1-9][0-9][0-9][0-9][0-9])"
2222 #define NUM5_TO_99999_RE                        \
2223     "([5-9]|"                                   \
2224     "[1-9][0-9]|"                               \
2225     "[1-9][0-9][0-9]|"                          \
2226     "[1-9][0-9][0-9][0-9]|"                     \
2227     "[1-9][0-9][0-9][0-9][0-9])"
2228 #define NUM1_TO_99999_RE                        \
2229     "([1-9]|"                                   \
2230     "[1-9][0-9]|"                               \
2231     "[1-9][0-9][0-9]|"                          \
2232     "[1-9][0-9][0-9][0-9]|"                     \
2233     "[1-9][0-9][0-9][0-9][0-9])"
2234
2235 static char *
2236 prompt(const char *prompt, const char *initial, const char *pattern)
2237 {
2238     struct ds ds;
2239     int pos, chidx;
2240     struct ds choices;
2241     const char *error;
2242     int erroffset;
2243     pcre *re;
2244     int retval;
2245     int okpartial;
2246     char *p;
2247
2248     set_icon(0,
2249              e____X,
2250              e____X,
2251              e__X_X,
2252              e_X__X,
2253              eXXXXX,
2254              e_X___,
2255              e__X__,
2256              e_____);
2257
2258     re = pcre_compile(pattern, PCRE_ANCHORED, &error, &erroffset, NULL);
2259     if (!re) {
2260         VLOG_ERR("PCRE error for pattern \"%s\" at offset %d: %s",
2261                  pattern, erroffset, error);
2262         return xstrdup(initial);
2263     }
2264
2265     retval = pcre_fullinfo(re, NULL, PCRE_INFO_OKPARTIAL, &okpartial);
2266     assert(!retval);
2267     assert(okpartial);
2268
2269     pos = 0;
2270     ds_init(&ds);
2271     ds_put_cstr(&ds, initial);
2272     ds_init(&choices);
2273     figure_choices(re, &ds, pos, &choices);
2274     p = memchr(choices.string, initial[0], choices.length);
2275     chidx = p ? p - choices.string : 0;
2276     for (;;) {
2277         int c, key;
2278
2279         while ((key = getch()) != ERR) {
2280             switch (key) {
2281             case KEY_UP:
2282                 if (choices.length > 1) {
2283                     if (++chidx >= choices.length) {
2284                         chidx = 0;
2285                     }
2286                     ds.string[pos] = choices.string[chidx];
2287                     ds_truncate(&ds, pos + 1);
2288                     figure_completion(re, &ds);
2289                 }
2290                 break;
2291
2292             case KEY_DOWN:
2293                 if (choices.length > 1) {
2294                     if (--chidx < 0) {
2295                         chidx = choices.length - 1;
2296                     }
2297                     ds.string[pos] = choices.string[chidx];
2298                     ds_truncate(&ds, pos + 1);
2299                     figure_completion(re, &ds);
2300                 }
2301                 break;
2302
2303             case '\r': case '\n':
2304                 if (choices.string[chidx] == '\n') {
2305                     ds_truncate(&ds, pos);
2306                     return ds_cstr(&ds);
2307                 } else {
2308                     if (pos >= ds.length) {
2309                         pos++;
2310                         ds_put_char(&ds, choices.string[chidx]);
2311                         figure_choices(re, &ds, pos, &choices);
2312                         chidx = 0;
2313                         figure_completion(re, &ds);
2314                     } else {
2315                         pos = ds.length;
2316                         figure_choices(re, &ds, pos, &choices);
2317                         chidx = 0;
2318                         figure_completion(re, &ds);
2319                     }
2320                 }
2321                 break;
2322
2323             case '\f':
2324                 ds_truncate(&ds, pos + 1);
2325                 figure_choices(re, &ds, pos, &choices);
2326                 chidx = 0;
2327                 break;
2328
2329             case '\b': case '\x7f': case '\x1b':
2330             case KEY_BACKSPACE: case KEY_DC:
2331                 if (pos) {
2332                     pos--;
2333                 } else {
2334                     return xstrdup(initial);
2335                 }
2336                 figure_choices(re, &ds, pos, &choices);
2337                 chidx = 0;
2338                 if (pos < ds.length) {
2339                     p = memchr(choices.string, ds.string[pos],
2340                                choices.length);
2341                     if (p) {
2342                         chidx = p - choices.string;
2343                     }
2344                 }
2345                 break;
2346
2347             default:
2348                 if (key >= 0x20 && key < 0x7f) {
2349                     /* Check whether 'key' is valid and toggle case if
2350                      * necessary. */
2351                     if (!memchr(choices.string, key, choices.length)) {
2352                         if (memchr(choices.string, toupper(key),
2353                                    choices.length)) {
2354                             key = toupper(key);
2355                         } else if (memchr(choices.string, tolower(key),
2356                                           choices.length)) {
2357                             key = tolower(key);
2358                         } else {
2359                             break;
2360                         }
2361                     }
2362
2363                     /* Insert 'key' and advance the position. */
2364                     if (pos >= ds.length) {
2365                         ds_put_char(&ds, key);
2366                     } else {
2367                         ds.string[pos] = key;
2368                     }
2369                     pos++;
2370
2371                     if (choices.string[chidx] != key) {
2372                         ds_truncate(&ds, pos);
2373                     }
2374                     figure_choices(re, &ds, pos, &choices);
2375                     chidx = 0;
2376                     if (pos < ds.length) {
2377                         p = memchr(choices.string, ds.string[pos],
2378                                    choices.length);
2379                         if (p) {
2380                             chidx = p - choices.string;
2381                         }
2382                     }
2383                     figure_completion(re, &ds);
2384                 }
2385             }
2386         }
2387
2388         erase();
2389         curs_set(1);
2390         move(0, 0);
2391         addnstr(prompt, MIN(40, strlen(prompt)));
2392
2393         c = choices.string[chidx];
2394         move(1, 0);
2395         addstr(ds_cstr(&ds));
2396         move(1, pos);
2397         if (c == '\n') {
2398             put_icon(0, '$');
2399         } else {
2400             addch(c);
2401         }
2402         move(1, pos);
2403         refresh();
2404
2405         poll_fd_wait(STDIN_FILENO, POLLIN);
2406         poll_block();
2407     }
2408 }
2409
2410 static void
2411 prompt_ip(const char *title, uint32_t *ip)
2412 {
2413     char *in = xasprintf(IP_FMT, IP_ARGS(ip));
2414     char *out = prompt(title, in, "^"IP_RE"$");
2415     *ip = inet_addr(out);
2416     free(in);
2417     free(out);
2418 }
2419
2420 static void
2421 abbreviate_netdevs(const struct svec *netdevs, struct ds *abbrev)
2422 {
2423     size_t i;
2424
2425     ds_init(abbrev);
2426     for (i = 0; i < netdevs->n; ) {
2427         size_t i_len = strlen(netdevs->names[i]);
2428         size_t j;
2429
2430         for (j = i + 1; j < netdevs->n; j++) {
2431             size_t j_len = strlen(netdevs->names[j]);
2432             if (!i_len || !j_len || i_len != j_len
2433                 || memcmp(netdevs->names[i], netdevs->names[j], i_len - 1)) {
2434                 break;
2435             }
2436         }
2437
2438         if (abbrev->length) {
2439             ds_put_char(abbrev, ' ');
2440         }
2441         if (j - i == 1) {
2442             ds_put_cstr(abbrev, netdevs->names[i]);
2443         } else {
2444             size_t k;
2445
2446             ds_put_buffer(abbrev, netdevs->names[i], i_len - 1);
2447             ds_put_char(abbrev, '[');
2448             for (k = i; k < j; k++) {
2449                 ds_put_char(abbrev, netdevs->names[k][i_len - 1]);
2450             }
2451             ds_put_char(abbrev, ']');
2452         }
2453         i = j;
2454     }
2455 }
2456
2457 static void
2458 choose_netdevs(struct svec *choices)
2459 {
2460     struct svec netdevs;
2461     struct menu menu;
2462     size_t i;
2463
2464     netdev_enumerate(&netdevs);
2465     svec_sort(&netdevs);
2466
2467     menu_init(&menu);
2468     menu_add_item(&menu, "Exit");
2469     for (i = 0; i < netdevs.n; i++) {
2470         const char *name = netdevs.names[i];
2471         struct menu_item *item;
2472         struct netdev *netdev;
2473         int retval;
2474
2475         if (!strncmp(name, "wmaster", strlen("wmaster"))
2476             || !strncmp(name, "of", strlen("of"))
2477             || !strcmp(name, "lo")) {
2478             continue;
2479         }
2480
2481         retval = netdev_open(name, NETDEV_ETH_TYPE_NONE, &netdev);
2482         if (!retval) {
2483             bool exclude = netdev_get_in4(netdev, NULL);
2484             netdev_close(netdev);
2485             if (exclude) {
2486                 continue;
2487             }
2488         }
2489
2490         item = menu_add_item(&menu, "%s", name);
2491         item->toggle = svec_contains(choices, name);
2492     }
2493     if (menu.n_items > 1) {
2494         menu_show(&menu, 0, true);
2495     } else {
2496         show_string("No available\nbridge ports");
2497     }
2498
2499     svec_clear(choices);
2500     for (i = 0; i < menu.n_items; i++) {
2501         struct menu_item *item = menu.items[i];
2502         if (item->toggle > 0) {
2503             svec_add(choices, item->text);
2504         }
2505     }
2506
2507     menu_free(&menu);
2508 }
2509
2510 static bool
2511 is_datapath_id_in_dmi(void)
2512 {
2513     FILE *dmidecode;
2514     char line[256];
2515     bool is_in_dmi;
2516
2517     dmidecode = popen("dmidecode -s system-uuid", "r");
2518     if (!dmidecode) {
2519         return false;
2520     }
2521     is_in_dmi = fgets(line, sizeof line, dmidecode) && strstr(line, "-002320");
2522     fclose(dmidecode);
2523     return is_in_dmi;
2524 }
2525
2526 struct switch_config {
2527     struct svec netdevs;
2528     enum { DISCOVERY, IN_BAND } mode;
2529     uint32_t switch_ip;
2530     uint32_t switch_mask;
2531     uint32_t switch_gw;
2532     enum { FAIL_DROP, FAIL_SWITCH } disconnected;
2533     bool stp;
2534     int rate_limit;
2535     int inactivity_probe;
2536     int max_backoff;
2537     char *controller_vconn;
2538     char *datapath_id;
2539 };
2540
2541 static const char *
2542 disconnected_string(int value)
2543 {
2544 #define FAIL_SWITCH_STRING "Switch packets"
2545 #define FAIL_DROP_STRING "Drop packets"
2546     return value == FAIL_SWITCH ? FAIL_SWITCH_STRING : FAIL_DROP_STRING;
2547 }
2548
2549 static void
2550 cmd_configure(const struct dict *dict UNUSED)
2551 {
2552     bool debug_mode = dict_get_bool(dict, "debug", false);
2553     struct dict config_dict;
2554     struct switch_config config;
2555     int start;
2556
2557     if (!load_config(&config_dict)) {
2558         return;
2559     }
2560     svec_init(&config.netdevs);
2561     svec_parse_words(&config.netdevs,
2562                      dict_get_string(&config_dict, "NETDEVS", ""));
2563     config.mode = (!strcmp(dict_get_string(&config_dict, "MODE", "discovery"),
2564                            "in-band") ? IN_BAND : DISCOVERY);
2565     config.switch_ip = dict_get_ip(&config_dict, "SWITCH_IP");
2566     config.switch_mask = dict_get_ip(&config_dict, "SWITCH_NETMASK");
2567     config.switch_gw = dict_get_ip(&config_dict, "SWITCH_GATEWAY");
2568     config.controller_vconn = xstrdup(dict_get_string(&config_dict,
2569                                                       "CONTROLLER", ""));
2570     config.disconnected = (!strcmp(dict_get_string(&config_dict,
2571                                                    "DISCONNECTED_MODE", ""),
2572                                    "switch")
2573                            ? FAIL_SWITCH : FAIL_DROP);
2574     config.stp = !strcmp(dict_get_string(&config_dict, "stp", ""), "yes");
2575     config.rate_limit = dict_get_int(&config_dict, "RATE_LIMIT", -1);
2576     config.inactivity_probe = dict_get_int(&config_dict, "INACTIVITY_PROBE",
2577                                            -1);
2578     config.max_backoff = dict_get_int(&config_dict, "MAX_BACKOFF", -1);
2579     if (is_datapath_id_in_dmi()) {
2580         config.datapath_id = xstrdup("DMI");
2581     } else {
2582         const char *dpid = dict_get(&config_dict, "DATAPATH_ID");
2583         if (dpid) {
2584             struct ds ds = DS_EMPTY_INITIALIZER;
2585             const char *cp;
2586             for (cp = dpid; *cp != '\0'; cp++) {
2587                 if (*cp != ':') {
2588                     ds_put_char(&ds, toupper((unsigned char) *cp));
2589                 }
2590             }
2591             config.datapath_id = ds_cstr(&ds);
2592         } else {
2593             config.datapath_id = xstrdup("Random");
2594         }
2595     }
2596     dict_free(&config_dict);
2597
2598     start = 0;
2599     while (start != -1) {
2600         enum {
2601             MENU_EXIT,
2602             MENU_NETDEVS,
2603             MENU_MODE,
2604             MENU_IP,
2605             MENU_NETMASK,
2606             MENU_GATEWAY,
2607             MENU_CONTROLLER,
2608             MENU_DISCONNECTED_MODE,
2609             MENU_DATAPATH_ID,
2610             MENU_STP,
2611             MENU_RATE_LIMIT,
2612             MENU_INACTIVITY_PROBE,
2613             MENU_MAX_BACKOFF,
2614         };
2615
2616         struct ds ports;
2617         struct menu_item *item;
2618         struct menu menu;
2619         char *in, *out;
2620         uint32_t ip;
2621
2622         menu_init(&menu);
2623
2624         /* Exit. */
2625         item = menu_add_item(&menu, "Exit");
2626         item->id = MENU_EXIT;
2627
2628         /* Bridge Ports. */
2629         abbreviate_netdevs(&config.netdevs, &ports);
2630         item = menu_add_item(&menu, "Bridge Ports:\n%s", ds_cstr(&ports));
2631         item->id = MENU_NETDEVS;
2632         ds_destroy(&ports);
2633
2634         /* Mode. */
2635         item = menu_add_item(&menu, "Mode:\n%s",
2636                              (config.mode == DISCOVERY
2637                               ? "Discovery" : "In-Band"));
2638         item->id = MENU_MODE;
2639
2640         /* IP address. */
2641         if (config.switch_ip == htonl(0)) {
2642             item = menu_add_item(&menu, "Switch IP Addr:\nDHCP");
2643         } else {
2644             item = menu_add_item(&menu, "Switch IP Addr:\n"IP_FMT,
2645                                  IP_ARGS(&config.switch_ip));
2646         }
2647         item->id = MENU_IP;
2648         item->enabled = config.mode == IN_BAND;
2649
2650         /* Netmask. */
2651         item = menu_add_item(&menu, "Switch Netmask:\n"IP_FMT,
2652                              IP_ARGS(&config.switch_mask));
2653         item->id = MENU_NETMASK;
2654         item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2655
2656         /* Gateway. */
2657         item = menu_add_item(&menu, "Switch Gateway:\n"IP_FMT,
2658                              IP_ARGS(&config.switch_gw));
2659         item->id = MENU_GATEWAY;
2660         item->enabled = config.mode == IN_BAND && config.switch_ip != htonl(0);
2661
2662         /* Controller. */
2663         item = menu_add_item(&menu, "Controller:\n%s",
2664                              config.controller_vconn);
2665         item->id = MENU_CONTROLLER;
2666         item->enabled = config.mode == IN_BAND;
2667
2668         /* Disconnected mode. */
2669         item = menu_add_item(&menu, "If disconnected:\n%s\n",
2670                              disconnected_string(config.disconnected));
2671         item->id = MENU_DISCONNECTED_MODE;
2672
2673         /* Datapath ID. */
2674         item = menu_add_item(&menu, "Datapath ID:\n%s", config.datapath_id);
2675         item->id = MENU_DATAPATH_ID;
2676         item->enabled = strcmp(config.datapath_id, "DMI");
2677
2678         /* Spanning tree protocol. */
2679         if (debug_mode) {
2680             item = menu_add_item(&menu, "802.1D-1998 STP:\n%s",
2681                                  config.stp ? "Enabled" : "Disabled");
2682             item->id = MENU_STP;
2683         }
2684
2685         /* Rate-limiting. */
2686         if (debug_mode) {
2687             if (config.rate_limit < 0) {
2688                 item = menu_add_item(&menu, "Ctlr rate limit:\nDisabled");
2689             } else {
2690                 item = menu_add_item(&menu, "Ctlr rate limit:\n%d/s",
2691                                      config.rate_limit);
2692             }
2693             item->id = MENU_RATE_LIMIT;
2694         }
2695
2696         /* Inactivity probe. */
2697         if (debug_mode) {
2698             if (config.inactivity_probe < 0) {
2699                 item = menu_add_item(&menu, "Activity probe:\nDefault");
2700             } else {
2701                 item = menu_add_item(&menu, "Activity probe:\n%d s",
2702                                      config.inactivity_probe);
2703             }
2704             item->id = MENU_INACTIVITY_PROBE;
2705         }
2706
2707         /* Max backoff. */
2708         if (debug_mode) {
2709             if (config.max_backoff < 0) {
2710                 item = menu_add_item(&menu, "Max backoff:\nDefault");
2711             } else {
2712                 item = menu_add_item(&menu, "Max backoff:\n%d s",
2713                                      config.max_backoff);
2714             }
2715             item->id = MENU_MAX_BACKOFF;
2716         }
2717
2718         start = menu_show2(&menu, start, true);
2719         menu_free(&menu);
2720
2721         in = out = NULL;
2722         switch (start) {
2723         case MENU_EXIT:
2724             start = -1;
2725             break;
2726
2727         case MENU_NETDEVS:
2728             choose_netdevs(&config.netdevs);
2729             break;
2730
2731         case MENU_MODE:
2732             out = prompt("Mode:",
2733                          config.mode == DISCOVERY ? "Discovery" : "In-Band",
2734                          "^(Discovery|In-Band)$");
2735             config.mode = !strcmp(out, "Discovery") ? DISCOVERY : IN_BAND;
2736             free(out);
2737             break;
2738
2739         case MENU_IP:
2740             in = (config.switch_ip == htonl(0) ? xstrdup("DHCP")
2741                   : xasprintf(IP_FMT, IP_ARGS(&config.switch_ip)));
2742             out = prompt("Switch IP:", in, "^(DHCP|"IP_RE")$");
2743             ip = strcmp(out, "DHCP") ? inet_addr(out) : htonl(0);
2744             free(in);
2745             free(out);
2746             if (ip != config.switch_ip) {
2747                 config.switch_ip = ip;
2748                 if (ip != htonl(0)) {
2749                     uint32_t mask = guess_netmask(ip);
2750                     if (mask) {
2751                         config.switch_mask = mask;
2752                         config.switch_gw = (ip & mask) | htonl(1);
2753                     }
2754                 }
2755             }
2756             break;
2757
2758         case MENU_NETMASK:
2759             prompt_ip("Switch Netmask:", &config.switch_mask);
2760             break;
2761
2762         case MENU_GATEWAY:
2763             prompt_ip("Switch Gateway:", &config.switch_gw);
2764             break;
2765
2766         case MENU_CONTROLLER:
2767             out = prompt("Controller:", config.controller_vconn,
2768                          "^(tcp|ssl):"IP_RE"(:"PORT_RE")?$");
2769             free(config.controller_vconn);
2770             config.controller_vconn = out;
2771             break;
2772
2773         case MENU_DISCONNECTED_MODE:
2774             out = prompt("If disconnected",
2775                          disconnected_string(config.disconnected),
2776                          "^("FAIL_DROP_STRING"|"FAIL_SWITCH_STRING")$");
2777             config.disconnected = (!strcmp(out, FAIL_DROP_STRING)
2778                                    ? FAIL_DROP : FAIL_SWITCH);
2779             free(out);
2780             break;
2781
2782         case MENU_DATAPATH_ID:
2783             out = prompt("Datapath ID:", config.datapath_id,
2784                          "^Random|"MAC_RE"$");
2785             free(config.datapath_id);
2786             config.datapath_id = out;
2787             break;
2788
2789         case MENU_STP:
2790             out = prompt("802.1D-1998 STP:",
2791                          config.stp ? "Enabled" : "Disabled",
2792                          "^(Enabled|Disabled)$");
2793             config.stp = !strcmp(out, "Enabled");
2794             free(out);
2795             break;
2796
2797         case MENU_RATE_LIMIT:
2798             in = (config.rate_limit < 0
2799                   ? xstrdup("Disabled")
2800                   : xasprintf("%d/s", config.rate_limit));
2801             out = prompt("Ctlr rate limit:", in,
2802                          "^(Disabled|("NUM100_TO_99999_RE")/s)$");
2803             free(in);
2804             config.rate_limit = isdigit(out[0]) ? atoi(out) : -1;
2805             free(out);
2806             break;
2807
2808         case MENU_INACTIVITY_PROBE:
2809             in = (config.inactivity_probe < 0
2810                   ? xstrdup("Default")
2811                   : xasprintf("%d s", config.inactivity_probe));
2812             out = prompt("Activity probe:", in,
2813                          "^(Default|("NUM5_TO_99999_RE") s)$");
2814             free(in);
2815             config.inactivity_probe = isdigit(out[0]) ? atoi(out) : -1;
2816             free(out);
2817             break;
2818
2819         case MENU_MAX_BACKOFF:
2820             in = (config.max_backoff < 0
2821                   ? xstrdup("Default")
2822                   : xasprintf("%d s", config.max_backoff));
2823             out = prompt("Max backoff:", in,
2824                          "^(Default|("NUM1_TO_99999_RE") s)$");
2825             free(in);
2826             config.max_backoff = isdigit(out[0]) ? atoi(out) : -1;
2827             free(out);
2828             break;
2829         }
2830     }
2831
2832     if (yesno("Save\nChanges?", false)) {
2833         struct svec set;
2834         char *netdevs;
2835
2836         svec_init(&set);
2837         netdevs = svec_join(&config.netdevs, " ", "");
2838         svec_add_nocopy(&set, xasprintf("NETDEVS=%s", netdevs));
2839         free(netdevs);
2840         svec_add(&set,
2841                  config.mode == IN_BAND ? "MODE=in-band" : "MODE=discovery");
2842         if (config.mode == IN_BAND) {
2843             if (config.switch_ip == htonl(0)) {
2844                 svec_add(&set, "SWITCH_IP=dhcp");
2845             } else {
2846                 svec_add_nocopy(&set, xasprintf("SWITCH_IP="IP_FMT,
2847                                                 IP_ARGS(&config.switch_ip)));
2848                 svec_add_nocopy(&set,
2849                                 xasprintf("SWITCH_NETMASK="IP_FMT,
2850                                           IP_ARGS(&config.switch_mask)));
2851                 svec_add_nocopy(&set, xasprintf("SWITCH_GATEWAY="IP_FMT,
2852                                                 IP_ARGS(&config.switch_gw)));
2853                 svec_add_nocopy(&set, xasprintf("CONTROLLER=%s",
2854                                                 config.controller_vconn));
2855             }
2856         }
2857         svec_add(&set, (config.disconnected == FAIL_DROP
2858                         ? "DISCONNECTED_MODE=drop"
2859                         : "DISCONNECTED_MODE=switch"));
2860         svec_add_nocopy(&set, xasprintf("STP=%s", config.stp ? "yes" : "no"));
2861         if (config.rate_limit < 0) {
2862             svec_add(&set, "RATE_LIMIT=");
2863         } else {
2864             svec_add_nocopy(&set,
2865                             xasprintf("RATE_LIMIT=%d", config.rate_limit));
2866         }
2867         if (config.inactivity_probe < 0) {
2868             svec_add(&set, "INACTIVITY_PROBE=");
2869         } else {
2870             svec_add_nocopy(&set, xasprintf("INACTIVITY_PROBE=%d",
2871                                             config.inactivity_probe));
2872         }
2873         if (config.max_backoff < 0) {
2874             svec_add(&set, "MAX_BACKOFF=");
2875         } else {
2876             svec_add_nocopy(&set, xasprintf("MAX_BACKOFF=%d",
2877                                             config.max_backoff));
2878         }
2879         save_config(&set);
2880         svec_destroy(&set);
2881     }
2882
2883     svec_destroy(&config.netdevs);
2884     free(config.controller_vconn);
2885     free(config.datapath_id);
2886 }
2887
2888 static void
2889 cmd_setup_pki(const struct dict *dict UNUSED)
2890 {
2891     static const char def_privkey_file[]
2892         = "/etc/openflow-switch/of0-privkey.pem";
2893     static const char def_cert_file[] = "/etc/openflow-switch/of0-cert.pem";
2894     static const char def_cacert_file[] = "/etc/openflow-switch/cacert.pem";
2895     struct dict config_dict;
2896     const char *privkey_file, *cert_file, *cacert_file;
2897     bool bootstrap;
2898     struct stat s;
2899     struct svec set;
2900     bool has_keys;
2901
2902     if (!load_config(&config_dict)) {
2903         return;
2904     }
2905     privkey_file = dict_get_string(&config_dict, "PRIVKEY", def_privkey_file);
2906     cert_file = dict_get_string(&config_dict, "CERT", def_cert_file);
2907     cacert_file = dict_get_string(&config_dict, "CACERT", def_cacert_file);
2908     bootstrap = !strcmp(dict_get_string(&config_dict, "CACERT_MODE", "secure"),
2909                         "bootstrap");
2910
2911     has_keys = !stat(privkey_file, &s) && !stat(cert_file, &s);
2912     if (!has_keys
2913         ? yesno("Generate\nkeys?", true)
2914         : yesno("Generate\nnew keys?", false)) {
2915         struct svec argv;
2916         bool ok;
2917
2918         privkey_file = def_privkey_file;
2919         cert_file = def_cert_file;
2920
2921         svec_init(&argv);
2922         svec_parse_words(&argv, "sh -c 'cd /etc/openflow-switch "
2923                          "&& ovs-pki --force req of0"
2924                          "&& ovs-pki --force self-sign of0'");
2925         svec_terminate(&argv);
2926         ok = run_and_report_failure(argv.names, "Key gen failed");
2927         svec_destroy(&argv);
2928         if (!ok) {
2929             return;
2930         }
2931         has_keys = true;
2932     }
2933     if (!has_keys) {
2934         return;
2935     }
2936
2937     if (stat(cacert_file, &s) && errno == ENOENT) {
2938         bootstrap = yesno("Bootstrap\nCA cert?", bootstrap);
2939     } else if (yesno("Replace\nCA cert?", false)) {
2940         unlink(cacert_file);
2941         bootstrap = true;
2942     }
2943
2944     svec_init(&set);
2945     svec_add_nocopy(&set, xasprintf("PRIVKEY=%s", privkey_file));
2946     svec_add_nocopy(&set, xasprintf("CERT=%s", cert_file));
2947     svec_add_nocopy(&set, xasprintf("CACERT=%s", cacert_file));
2948     svec_add_nocopy(&set, xasprintf("CACERT_MODE=%s",
2949                                     bootstrap ? "bootstrap" : "secure"));
2950     save_config(&set);
2951     svec_destroy(&set);
2952 }
2953 \f
2954 static void
2955 parse_options(int argc, char *argv[])
2956 {
2957     enum {
2958         OPT_DUMMY = UCHAR_MAX + 1,
2959         VLOG_OPTION_ENUMS
2960     };
2961     static struct option long_options[] = {
2962         {"verbose", optional_argument, 0, 'v'},
2963         {"help", no_argument, 0, 'h'},
2964         {"version", no_argument, 0, 'V'},
2965         DAEMON_LONG_OPTIONS,
2966         VLOG_LONG_OPTIONS,
2967         {0, 0, 0, 0},
2968     };
2969     char *short_options = long_options_to_short_options(long_options);
2970
2971     for (;;) {
2972         int c;
2973
2974         c = getopt_long(argc, argv, short_options, long_options, NULL);
2975         if (c == -1) {
2976             break;
2977         }
2978
2979         switch (c) {
2980         case 'h':
2981             usage();
2982
2983         case 'V':
2984             OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
2985             exit(EXIT_SUCCESS);
2986
2987         VLOG_OPTION_HANDLERS
2988         DAEMON_OPTION_HANDLERS
2989
2990         case '?':
2991             exit(EXIT_FAILURE);
2992
2993         default:
2994             abort();
2995         }
2996     }
2997     free(short_options);
2998 }
2999
3000 static void
3001 usage(void)
3002 {
3003     printf("%s: OpenFlow switch monitoring user interface\n"
3004            "usage: %s [OPTIONS] SWITCH\n"
3005            "where SWITCH is an active OpenFlow connection method.\n",
3006            program_name, program_name);
3007     vconn_usage(true, false, false);
3008     printf("\nOptions:\n"
3009            "  -v, --verbose=MODULE:FACILITY:LEVEL  configure logging levels\n"
3010            "  -v, --verbose               set maximum verbosity level\n"
3011            "  -h, --help             display this help message\n"
3012            "  -V, --version          display version information\n");
3013     exit(EXIT_SUCCESS);
3014 }