Announce fail-open mode more aggressively in secchan.
[openvswitch] / secchan / secchan.c
1  /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <errno.h>
35 #include <getopt.h>
36 #include <inttypes.h>
37 #include <netinet/in.h>
38 #include <poll.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42 #include <unistd.h>
43
44 #include "buffer.h"
45 #include "command-line.h"
46 #include "compiler.h"
47 #include "daemon.h"
48 #include "fault.h"
49 #include "flow.h"
50 #include "learning-switch.h"
51 #include "list.h"
52 #include "mac-learning.h"
53 #include "netdev.h"
54 #include "openflow.h"
55 #include "packets.h"
56 #include "poll-loop.h"
57 #include "rconn.h"
58 #include "util.h"
59 #include "vconn-ssl.h"
60 #include "vconn.h"
61 #include "vlog-socket.h"
62
63 #include "vlog.h"
64 #define THIS_MODULE VLM_secchan
65
66 #include "ofp-print.h"
67
68 static const char *listen_vconn_name;
69
70 struct half {
71     struct rconn *rconn;
72     struct buffer *rxbuf;
73 };
74
75 /* Behavior when the connection to the controller fails. */
76 enum fail_mode {
77     FAIL_OPEN,                  /* Act as learning switch. */
78     FAIL_CLOSED                 /* Drop all packets. */
79 };
80
81 struct relay {
82     struct list node;
83
84 #define HALF_LOCAL 0
85 #define HALF_REMOTE 1
86     struct half halves[2];
87
88     bool is_mgmt_conn;
89     struct lswitch *lswitch;
90 };
91
92 static struct list relays = LIST_INITIALIZER(&relays);
93
94 /* Enable the local port? */
95 static int local_port;
96
97 /* MAC address of local port. */
98 static uint8_t local_mac[ETH_ADDR_LEN];
99
100 /* MAC learning table for local port. */
101 static struct mac_learning *local_ml;
102
103 /* -f, --fail: Behavior when the connection to the controller fails. */
104 static enum fail_mode fail_mode = FAIL_OPEN;
105
106 /* --inactivity-probe: Number of seconds without receiving a message from the
107    controller before sending an inactivity probe. */
108 static int probe_interval = 15;
109
110 /* --max-idle: Idle time to assign to flows created by learning switch when in
111  * fail-open mode. */
112 static int max_idle = 15;
113
114 static void parse_options(int argc, char *argv[]);
115 static void usage(void) NO_RETURN;
116
117 static void new_management_connection(const char *nl_name, struct vconn *new_remote);
118 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
119                                   bool is_mgmt_conn);
120 static void relay_run(struct relay *);
121 static void relay_wait(struct relay *);
122 static void relay_destroy(struct relay *);
123
124 static bool local_hook(struct relay *r);
125 static bool failing_open(struct relay *r);
126 static bool fail_open_hook(struct relay *r);
127
128 int
129 main(int argc, char *argv[])
130 {
131     struct vconn *listen_vconn;
132     struct netdev *of_device;
133     struct relay *controller_relay;
134     const char *nl_name;
135     char of_name[16];
136     int retval;
137
138     set_program_name(argv[0]);
139     register_fault_handlers();
140     vlog_init();
141     parse_options(argc, argv);
142
143     if (argc - optind != 2) {
144         fatal(0,
145               "need exactly two non-option arguments; use --help for usage");
146     }
147     nl_name = argv[optind];
148     if (strncmp(nl_name, "nl:", 3)
149         || strlen(nl_name) < 4
150         || nl_name[strspn(nl_name + 3, "0123456789") + 3]) {
151         fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", nl_name);
152     }
153
154     if (listen_vconn_name) {
155         retval = vconn_open(listen_vconn_name, &listen_vconn);
156         if (retval && retval != EAGAIN) {
157             fatal(retval, "opening %s", listen_vconn_name);
158         }
159         if (!vconn_is_passive(listen_vconn)) {
160             fatal(0, "%s is not a passive vconn", listen_vconn_name);
161         }
162     } else {
163         listen_vconn = NULL;
164     }
165
166     snprintf(of_name, sizeof of_name, "of%s", nl_name + 3);
167     retval = netdev_open(of_name, &of_device);
168     if (!retval) {
169         enum netdev_flags flags;
170         retval = netdev_get_flags(of_device, &flags);
171         if (!retval) {
172             if (flags & NETDEV_UP) {
173                 struct in6_addr in6;
174
175                 local_port = true;
176                 memcpy(local_mac, netdev_get_etheraddr(of_device),
177                        ETH_ADDR_LEN);
178                 if (netdev_get_in6(of_device, &in6)) {
179                     VLOG_WARN("Ignoring IPv6 address on %s device: "
180                               "IPv6 not supported", of_name);
181                 }
182                 local_ml = mac_learning_create();
183             }
184         } else {
185             error(retval, "Could not get flags for %s device", of_name);
186         }
187         netdev_close(of_device);
188     } else {
189         error(retval, "Could not open %s device", of_name);
190     }
191
192     retval = vlog_server_listen(NULL, NULL);
193     if (retval) {
194         fatal(retval, "Could not listen for vlog connections");
195     }
196
197     daemonize();
198
199     controller_relay = relay_create(rconn_new(argv[optind], 1, 0),
200                                     rconn_new(argv[optind + 1], 1,
201                                               probe_interval),
202                                     false);
203     for (;;) {
204         struct relay *r, *n;
205
206         /* Do work. */
207         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
208             relay_run(r);
209         }
210         if (listen_vconn) {
211             for (;;) {
212                 struct vconn *new_remote;
213                 retval = vconn_accept(listen_vconn, &new_remote);
214                 if (retval) {
215                     if (retval != EAGAIN) {
216                         VLOG_WARN("accept failed (%s)", strerror(retval));
217                     }
218                     break;
219                 }
220                 new_management_connection(nl_name, new_remote);
221             }
222         }
223         failing_open(controller_relay);
224
225         /* Wait for something to happen. */
226         LIST_FOR_EACH (r, struct relay, node, &relays) {
227             relay_wait(r);
228         }
229         if (listen_vconn) {
230             vconn_accept_wait(listen_vconn);
231         }
232         poll_block();
233     }
234
235     return 0;
236 }
237
238 static void
239 new_management_connection(const char *nl_name, struct vconn *new_remote)
240 {
241     char *nl_name_without_subscription;
242     struct vconn *new_local;
243     struct rconn *r1, *r2;
244     int retval;
245
246     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
247      * only accept the former syntax in main().
248      *
249      * nl:123:0 opens a netlink connection to local datapath 123 without
250      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
251      * messages.*/
252     nl_name_without_subscription = xasprintf("%s:0", nl_name);
253     retval = vconn_open(nl_name_without_subscription, &new_local);
254     if (retval) {
255         VLOG_ERR("could not connect to %s (%s)",
256                  nl_name_without_subscription, strerror(retval));
257         vconn_close(new_remote);
258         free(nl_name_without_subscription);
259         return;
260     }
261
262     /* Add it to the relay list. */
263     r1 = rconn_new_from_vconn(nl_name_without_subscription, 1, new_local);
264     r2 = rconn_new_from_vconn("passive", 1, new_remote);
265     relay_create(r1, r2, true);
266
267     free(nl_name_without_subscription);
268 }
269
270 static struct relay *
271 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
272 {
273     struct relay *r;
274     int i;
275
276     r = xmalloc(sizeof *r);
277     r->halves[HALF_LOCAL].rconn = local;
278     r->halves[HALF_REMOTE].rconn = remote;
279     for (i = 0; i < 2; i++) {
280         r->halves[i].rxbuf = NULL;
281     }
282     r->is_mgmt_conn = is_mgmt_conn;
283     r->lswitch = NULL;
284     list_push_back(&relays, &r->node);
285     return r;
286 }
287
288 static void
289 relay_run(struct relay *r)
290 {
291     int iteration;
292     int i;
293
294     for (i = 0; i < 2; i++) {
295         rconn_run(r->halves[i].rconn);
296     }
297
298     /* Limit the number of iterations to prevent other tasks from starving. */
299     for (iteration = 0; iteration < 50; iteration++) {
300         bool progress = false;
301         for (i = 0; i < 2; i++) {
302             struct half *this = &r->halves[i];
303             struct half *peer = &r->halves[!i];
304
305             if (!this->rxbuf) {
306                 this->rxbuf = rconn_recv(this->rconn);
307                 if (this->rxbuf && !r->is_mgmt_conn && i == HALF_LOCAL
308                     && (local_hook(r) || fail_open_hook(r))) {
309                     buffer_delete(this->rxbuf);
310                     this->rxbuf = NULL;
311                 }
312             }
313
314             if (this->rxbuf) {
315                 int retval = rconn_send(peer->rconn, this->rxbuf);
316                 if (retval != EAGAIN) {
317                     if (!retval) {
318                         progress = true;
319                     } else {
320                         buffer_delete(this->rxbuf);
321                     }
322                     this->rxbuf = NULL;
323                 }
324             }
325         }
326         if (!progress) {
327             break;
328         }
329     }
330
331     for (i = 0; i < 2; i++) {
332         struct half *this = &r->halves[i];
333         if (!rconn_is_alive(this->rconn)) {
334             relay_destroy(r);
335             return;
336         }
337     }
338 }
339
340 static void
341 relay_wait(struct relay *r)
342 {
343     int i;
344
345     for (i = 0; i < 2; i++) {
346         struct half *this = &r->halves[i];
347
348         rconn_run_wait(this->rconn);
349         if (!this->rxbuf) {
350             rconn_recv_wait(this->rconn);
351         }
352     }
353 }
354
355 static void
356 relay_destroy(struct relay *r)
357 {
358     int i;
359
360     list_remove(&r->node);
361     for (i = 0; i < 2; i++) {
362         struct half *this = &r->halves[i];
363         rconn_destroy(this->rconn);
364         buffer_delete(this->rxbuf);
365     }
366     free(r);
367 }
368
369 static bool
370 local_hook(struct relay *r)
371 {
372     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
373     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
374     struct ofp_packet_in *opi;
375     struct ofp_header *oh;
376     size_t pkt_ofs, pkt_len;
377     struct buffer pkt, *b;
378     struct flow flow;
379     uint16_t in_port, out_port;
380
381     if (!local_port) {
382         return false;
383     }
384
385     oh = msg->data;
386     if (oh->type != OFPT_PACKET_IN) {
387         return false;
388     }
389     if (msg->size < offsetof (struct ofp_packet_in, data)) {
390         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
391         return false;
392     }
393
394     /* Extract flow data from 'opi' into 'flow'. */
395     opi = msg->data;
396     in_port = ntohs(opi->in_port);
397     pkt_ofs = offsetof(struct ofp_packet_in, data);
398     pkt_len = ntohs(opi->header.length) - pkt_ofs;
399     pkt.data = opi->data;
400     pkt.size = pkt_len;
401     flow_extract(&pkt, in_port, &flow);
402
403     /* Deal with local stuff. */
404     if (in_port == OFPP_LOCAL) {
405         out_port = mac_learning_lookup(local_ml, flow.dl_dst);
406     } else if (eth_addr_equals(flow.dl_dst, local_mac)) {
407         out_port = OFPP_LOCAL;
408         if (mac_learning_learn(local_ml, flow.dl_src, in_port)) {
409             VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
410                      ETH_ADDR_ARGS(flow.dl_src), in_port);
411         }
412     } else {
413         return false;
414     }
415
416     /* Add new flow. */
417     if (out_port != OFPP_FLOOD) {
418         b = make_add_simple_flow(&flow, ntohl(opi->buffer_id), out_port,
419                                  max_idle);
420         if (rconn_force_send(rc, b)) {
421             buffer_delete(b);
422         }
423     }
424
425     /* If the switch didn't buffer the packet, we need to send a copy. */
426     if (out_port == OFPP_FLOOD || ntohl(opi->buffer_id) == UINT32_MAX) {
427         b = make_unbuffered_packet_out(&pkt, in_port, out_port);
428         if (rconn_force_send(rc, b)) {
429             buffer_delete(b);
430         }
431     }
432     return true;
433 }
434
435 /* Causess 'r' to enter or leave fail-open mode, if appropriate.  Returns true
436  * if 'r' is in fail-open fail, false otherwise. */
437 static bool
438 failing_open(struct relay *r)
439 {
440     struct rconn *local = r->halves[HALF_LOCAL].rconn;
441     struct rconn *remote = r->halves[HALF_REMOTE].rconn;
442     int disconnected_duration;
443
444     if (fail_mode == FAIL_CLOSED) {
445         /* We fail closed, so there's never anything to do. */
446         return false;
447     }
448
449     disconnected_duration = rconn_disconnected_duration(remote);
450     if (disconnected_duration < probe_interval * 3) {
451         /* It's not time to fail open yet. */
452         if (r->lswitch && rconn_is_connected(remote)) {
453             /* We're connected, so drop the learning switch. */
454             VLOG_WARN("No longer in fail-open mode");
455             lswitch_destroy(r->lswitch);
456             r->lswitch = NULL;
457         }
458         return false;
459     }
460
461     if (!r->lswitch) {
462         VLOG_WARN("Could not connect to controller for %d seconds, "
463                   "failing open", disconnected_duration);
464         r->lswitch = lswitch_create(local, true, max_idle);
465     }
466     return true;
467 }
468
469 static bool
470 fail_open_hook(struct relay *r)
471 {
472     if (!failing_open(r)) {
473         return false;
474     } else {
475         struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
476         struct rconn *local = r->halves[HALF_LOCAL].rconn;
477         lswitch_process_packet(r->lswitch, local, msg);
478         rconn_run(local);
479         return true;
480     }
481 }
482
483 static void
484 parse_options(int argc, char *argv[]) 
485 {
486     enum { OPT_INACTIVITY_PROBE = UCHAR_MAX + 1, OPT_MAX_IDLE };
487     static struct option long_options[] = {
488         {"fail",        required_argument, 0, 'f'},
489         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
490         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
491         {"listen",      required_argument, 0, 'l'},
492         {"detach",      no_argument, 0, 'D'},
493         {"pidfile",     optional_argument, 0, 'P'},
494         {"verbose",     optional_argument, 0, 'v'},
495         {"help",        no_argument, 0, 'h'},
496         {"version",     no_argument, 0, 'V'},
497         VCONN_SSL_LONG_OPTIONS
498         {0, 0, 0, 0},
499     };
500     char *short_options = long_options_to_short_options(long_options);
501     
502     for (;;) {
503         int c;
504
505         c = getopt_long(argc, argv, short_options, long_options, NULL);
506         if (c == -1) {
507             break;
508         }
509
510         switch (c) {
511         case 'f':
512             if (!strcmp(optarg, "open")) {
513                 fail_mode = FAIL_OPEN;
514             } else if (!strcmp(optarg, "closed")) {
515                 fail_mode = FAIL_CLOSED;
516             } else {
517                 fatal(0,
518                       "-f or --fail argument must be \"open\" or \"closed\"");
519             }
520             break;
521
522         case OPT_INACTIVITY_PROBE:
523             probe_interval = atoi(optarg);
524             if (probe_interval < 5) {
525                 fatal(0, "--inactivity-probe argument must be at least 5");
526             }
527             break;
528
529         case OPT_MAX_IDLE:
530             if (!strcmp(optarg, "permanent")) {
531                 max_idle = OFP_FLOW_PERMANENT;
532             } else {
533                 max_idle = atoi(optarg);
534                 if (max_idle < 1 || max_idle > 65535) {
535                     fatal(0, "--max-idle argument must be between 1 and "
536                           "65535 or the word 'permanent'");
537                 }
538             }
539             break;
540
541         case 'D':
542             set_detach();
543             break;
544
545         case 'P':
546             set_pidfile(optarg ? optarg : "secchan.pid");
547             break;
548
549         case 'l':
550             if (listen_vconn_name) {
551                 fatal(0, "-l or --listen may be only specified once");
552             }
553             listen_vconn_name = optarg;
554             break;
555
556         case 'h':
557             usage();
558
559         case 'V':
560             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
561             exit(EXIT_SUCCESS);
562
563         case 'v':
564             vlog_set_verbosity(optarg);
565             break;
566
567         VCONN_SSL_OPTION_HANDLERS
568
569         case '?':
570             exit(EXIT_FAILURE);
571
572         default:
573             abort();
574         }
575     }
576     free(short_options);
577 }
578
579 static void
580 usage(void)
581 {
582     printf("%s: secure channel, a relay for OpenFlow messages.\n"
583            "usage: %s [OPTIONS] nl:DP_IDX CONTROLLER\n"
584            "where nl:DP_IDX is a datapath that has been added with dpctl\n"
585            "and CONTROLLER is an active OpenFlow connection method.\n",
586            program_name, program_name);
587     vconn_usage(true, true);
588     printf("\nNetworking options:\n"
589            "  -f, --fail=open|closed  when controller connection fails:\n"
590            "                            closed: drop all packets\n"
591            "                            open (default): act as learning switch\n"
592            "  --inactivity-probe=SECS time between inactivity probes\n"
593            "  --max-idle=SECS         max idle for flows set up by secchan\n"
594            "  -l, --listen=METHOD     allow management connections on METHOD\n"
595            "                          (a passive OpenFlow connection method)\n"
596            "\nOther options:\n"
597            "  -D, --detach            run in background as daemon\n"
598            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
599            "  -v, --verbose=MODULE:FACILITY:LEVEL  configure logging levels\n"
600            "  -v, --verbose           set maximum verbosity level\n"
601            "  -h, --help              display this help message\n"
602            "  -V, --version           display version information\n",
603            RUNDIR);
604     exit(EXIT_SUCCESS);
605 }