Add new --max-backoff option to secchan and switch programs.
[sliver-openvswitch.git] / 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 /* The OpenFlow virtual network device ofX. */
107 static struct netdev *of_device;
108
109 /* --inactivity-probe: Number of seconds without receiving a message from the
110    controller before sending an inactivity probe. */
111 static int probe_interval = 15;
112
113 /* --max-idle: Idle time to assign to flows created by learning switch when in
114  * fail-open mode. */
115 static int max_idle = 15;
116
117 /* --max-backoff: Maximum interval between controller connection attempts, in
118  * seconds. */
119 static int max_backoff = 15;
120
121 static void parse_options(int argc, char *argv[]);
122 static void usage(void) NO_RETURN;
123
124 static void new_management_connection(const char *nl_name, struct vconn *new_remote);
125 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
126                                   bool is_mgmt_conn);
127 static void relay_run(struct relay *);
128 static void relay_wait(struct relay *);
129 static void relay_destroy(struct relay *);
130
131 static bool local_hook(struct relay *r);
132 static bool failing_open(struct relay *r);
133 static bool fail_open_hook(struct relay *r);
134
135 int
136 main(int argc, char *argv[])
137 {
138     struct vconn *listen_vconn;
139     struct relay *controller_relay;
140     const char *nl_name;
141     char of_name[16];
142     int retval;
143
144     set_program_name(argv[0]);
145     register_fault_handlers();
146     vlog_init();
147     parse_options(argc, argv);
148
149     if (argc - optind != 2) {
150         fatal(0,
151               "need exactly two non-option arguments; use --help for usage");
152     }
153     nl_name = argv[optind];
154     if (strncmp(nl_name, "nl:", 3)
155         || strlen(nl_name) < 4
156         || nl_name[strspn(nl_name + 3, "0123456789") + 3]) {
157         fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", nl_name);
158     }
159
160     if (listen_vconn_name) {
161         retval = vconn_open(listen_vconn_name, &listen_vconn);
162         if (retval && retval != EAGAIN) {
163             fatal(retval, "opening %s", listen_vconn_name);
164         }
165         if (!vconn_is_passive(listen_vconn)) {
166             fatal(0, "%s is not a passive vconn", listen_vconn_name);
167         }
168     } else {
169         listen_vconn = NULL;
170     }
171
172     snprintf(of_name, sizeof of_name, "of%s", nl_name + 3);
173     retval = netdev_open(of_name, NETDEV_ETH_TYPE_NONE, &of_device);
174     if (!retval) {
175         enum netdev_flags flags;
176         retval = netdev_get_flags(of_device, &flags);
177         if (!retval) {
178             if (flags & NETDEV_UP) {
179                 struct in6_addr in6;
180
181                 local_port = true;
182                 memcpy(local_mac, netdev_get_etheraddr(of_device),
183                        ETH_ADDR_LEN);
184                 if (netdev_get_in6(of_device, &in6)) {
185                     VLOG_WARN("Ignoring IPv6 address on %s device: "
186                               "IPv6 not supported", of_name);
187                 }
188                 local_ml = mac_learning_create();
189             }
190         } else {
191             error(retval, "Could not get flags for %s device", of_name);
192         }
193     } else {
194         error(retval, "Could not open %s device", of_name);
195     }
196
197     retval = vlog_server_listen(NULL, NULL);
198     if (retval) {
199         fatal(retval, "Could not listen for vlog connections");
200     }
201
202     daemonize();
203
204     controller_relay = relay_create(rconn_new(argv[optind], 1, 0, max_backoff),
205                                     rconn_new(argv[optind + 1], 1,
206                                               probe_interval, max_backoff),
207                                     false);
208     for (;;) {
209         struct relay *r, *n;
210
211         /* Do work. */
212         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
213             relay_run(r);
214         }
215         if (listen_vconn) {
216             for (;;) {
217                 struct vconn *new_remote;
218                 retval = vconn_accept(listen_vconn, &new_remote);
219                 if (retval) {
220                     if (retval != EAGAIN) {
221                         VLOG_WARN("accept failed (%s)", strerror(retval));
222                     }
223                     break;
224                 }
225                 new_management_connection(nl_name, new_remote);
226             }
227         }
228         failing_open(controller_relay);
229
230         /* Wait for something to happen. */
231         LIST_FOR_EACH (r, struct relay, node, &relays) {
232             relay_wait(r);
233         }
234         if (listen_vconn) {
235             vconn_accept_wait(listen_vconn);
236         }
237         poll_block();
238     }
239
240     return 0;
241 }
242
243 static void
244 new_management_connection(const char *nl_name, struct vconn *new_remote)
245 {
246     char *nl_name_without_subscription;
247     struct vconn *new_local;
248     struct rconn *r1, *r2;
249     int retval;
250
251     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
252      * only accept the former syntax in main().
253      *
254      * nl:123:0 opens a netlink connection to local datapath 123 without
255      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
256      * messages.*/
257     nl_name_without_subscription = xasprintf("%s:0", nl_name);
258     retval = vconn_open(nl_name_without_subscription, &new_local);
259     if (retval) {
260         VLOG_ERR("could not connect to %s (%s)",
261                  nl_name_without_subscription, strerror(retval));
262         vconn_close(new_remote);
263         free(nl_name_without_subscription);
264         return;
265     }
266
267     /* Add it to the relay list. */
268     r1 = rconn_new_from_vconn(nl_name_without_subscription, 1, new_local);
269     r2 = rconn_new_from_vconn("passive", 1, new_remote);
270     relay_create(r1, r2, true);
271
272     free(nl_name_without_subscription);
273 }
274
275 static struct relay *
276 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
277 {
278     struct relay *r;
279     int i;
280
281     r = xmalloc(sizeof *r);
282     r->halves[HALF_LOCAL].rconn = local;
283     r->halves[HALF_REMOTE].rconn = remote;
284     for (i = 0; i < 2; i++) {
285         r->halves[i].rxbuf = NULL;
286     }
287     r->is_mgmt_conn = is_mgmt_conn;
288     r->lswitch = NULL;
289     list_push_back(&relays, &r->node);
290     return r;
291 }
292
293 static void
294 relay_run(struct relay *r)
295 {
296     int iteration;
297     int i;
298
299     for (i = 0; i < 2; i++) {
300         rconn_run(r->halves[i].rconn);
301     }
302
303     /* Limit the number of iterations to prevent other tasks from starving. */
304     for (iteration = 0; iteration < 50; iteration++) {
305         bool progress = false;
306         for (i = 0; i < 2; i++) {
307             struct half *this = &r->halves[i];
308             struct half *peer = &r->halves[!i];
309
310             if (!this->rxbuf) {
311                 this->rxbuf = rconn_recv(this->rconn);
312                 if (this->rxbuf && !r->is_mgmt_conn && i == HALF_LOCAL
313                     && (local_hook(r) || fail_open_hook(r))) {
314                     buffer_delete(this->rxbuf);
315                     this->rxbuf = NULL;
316                 }
317             }
318
319             if (this->rxbuf) {
320                 int retval = rconn_send(peer->rconn, this->rxbuf);
321                 if (retval != EAGAIN) {
322                     if (!retval) {
323                         progress = true;
324                     } else {
325                         buffer_delete(this->rxbuf);
326                     }
327                     this->rxbuf = NULL;
328                 }
329             }
330         }
331         if (!progress) {
332             break;
333         }
334     }
335
336     for (i = 0; i < 2; i++) {
337         struct half *this = &r->halves[i];
338         if (!rconn_is_alive(this->rconn)) {
339             relay_destroy(r);
340             return;
341         }
342     }
343 }
344
345 static void
346 relay_wait(struct relay *r)
347 {
348     int i;
349
350     for (i = 0; i < 2; i++) {
351         struct half *this = &r->halves[i];
352
353         rconn_run_wait(this->rconn);
354         if (!this->rxbuf) {
355             rconn_recv_wait(this->rconn);
356         }
357     }
358 }
359
360 static void
361 relay_destroy(struct relay *r)
362 {
363     int i;
364
365     list_remove(&r->node);
366     for (i = 0; i < 2; i++) {
367         struct half *this = &r->halves[i];
368         rconn_destroy(this->rconn);
369         buffer_delete(this->rxbuf);
370     }
371     free(r);
372 }
373
374 static bool
375 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
376                   struct rconn *controller) 
377 {
378     static uint32_t ip, last_nonzero_ip;
379     static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
380     static time_t next_refresh = 0;
381
382     uint32_t last_ip = ip;
383
384     time_t now = time(0);
385
386     ip = rconn_get_ip(controller);
387     if (last_ip != ip || !next_refresh || now >= next_refresh) {
388         bool have_mac;
389
390         /* Look up MAC address. */
391         memset(mac, 0, sizeof mac);
392         if (ip) {
393             int retval = netdev_arp_lookup(of_device, ip, mac);
394             if (retval) {
395                 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
396                          IP_ARGS(&ip), strerror(retval));
397             }
398         }
399         have_mac = !eth_addr_is_zero(mac);
400
401         /* Log changes in IP, MAC addresses. */
402         if (ip && ip != last_nonzero_ip) {
403             VLOG_DBG("controller IP address changed from "IP_FMT
404                      " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
405             last_nonzero_ip = ip;
406         }
407         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
408             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
409                      ETH_ADDR_FMT,
410                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
411             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
412         }
413
414         /* Schedule next refresh.
415          *
416          * If we have an IP address but not a MAC address, then refresh
417          * quickly, since we probably will get a MAC address soon (via ARP).
418          * Otherwise, we can afford to wait a little while. */
419         next_refresh = now + (!ip || have_mac ? 10 : 1);
420     }
421     return !eth_addr_is_zero(mac) && eth_addr_equals(mac, dl_addr);
422 }
423
424 static bool
425 local_hook(struct relay *r)
426 {
427     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
428     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
429     struct ofp_packet_in *opi;
430     struct ofp_header *oh;
431     size_t pkt_ofs, pkt_len;
432     struct buffer pkt, *b;
433     struct flow flow;
434     uint16_t in_port, out_port;
435
436     if (!local_port) {
437         return false;
438     }
439
440     oh = msg->data;
441     if (oh->type != OFPT_PACKET_IN) {
442         return false;
443     }
444     if (msg->size < offsetof (struct ofp_packet_in, data)) {
445         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
446         return false;
447     }
448
449     /* Extract flow data from 'opi' into 'flow'. */
450     opi = msg->data;
451     in_port = ntohs(opi->in_port);
452     pkt_ofs = offsetof(struct ofp_packet_in, data);
453     pkt_len = ntohs(opi->header.length) - pkt_ofs;
454     pkt.data = opi->data;
455     pkt.size = pkt_len;
456     flow_extract(&pkt, in_port, &flow);
457
458     /* Deal with local stuff. */
459     if (in_port == OFPP_LOCAL) {
460         out_port = mac_learning_lookup(local_ml, flow.dl_dst);
461     } else if (eth_addr_equals(flow.dl_dst, local_mac)) {
462         out_port = OFPP_LOCAL;
463         if (mac_learning_learn(local_ml, flow.dl_src, in_port)) {
464             VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
465                      ETH_ADDR_ARGS(flow.dl_src), in_port);
466         }
467     } else if (flow.dl_type == htons(ETH_TYPE_ARP)
468                && eth_addr_is_broadcast(flow.dl_dst)
469                && is_controller_mac(flow.dl_src,
470                                     r->halves[HALF_REMOTE].rconn)) {
471         out_port = OFPP_FLOOD;
472     } else {
473         return false;
474     }
475
476     /* Add new flow. */
477     if (out_port != OFPP_FLOOD) {
478         b = make_add_simple_flow(&flow, ntohl(opi->buffer_id), out_port,
479                                  max_idle);
480         if (rconn_force_send(rc, b)) {
481             buffer_delete(b);
482         }
483     }
484
485     /* If the switch didn't buffer the packet, we need to send a copy. */
486     if (out_port == OFPP_FLOOD || ntohl(opi->buffer_id) == UINT32_MAX) {
487         b = make_unbuffered_packet_out(&pkt, in_port, out_port);
488         if (rconn_force_send(rc, b)) {
489             buffer_delete(b);
490         }
491     }
492     return true;
493 }
494
495 /* Causess 'r' to enter or leave fail-open mode, if appropriate.  Returns true
496  * if 'r' is in fail-open fail, false otherwise. */
497 static bool
498 failing_open(struct relay *r)
499 {
500     struct rconn *local = r->halves[HALF_LOCAL].rconn;
501     struct rconn *remote = r->halves[HALF_REMOTE].rconn;
502     int disconnected_duration;
503
504     if (fail_mode == FAIL_CLOSED) {
505         /* We fail closed, so there's never anything to do. */
506         return false;
507     }
508
509     disconnected_duration = rconn_disconnected_duration(remote);
510     if (disconnected_duration < probe_interval * 3) {
511         /* It's not time to fail open yet. */
512         if (r->lswitch && rconn_is_connected(remote)) {
513             /* We're connected, so drop the learning switch. */
514             VLOG_WARN("No longer in fail-open mode");
515             lswitch_destroy(r->lswitch);
516             r->lswitch = NULL;
517         }
518         return false;
519     }
520
521     if (!r->lswitch) {
522         VLOG_WARN("Could not connect to controller for %d seconds, "
523                   "failing open", disconnected_duration);
524         r->lswitch = lswitch_create(local, true, max_idle);
525     }
526     return true;
527 }
528
529 static bool
530 fail_open_hook(struct relay *r)
531 {
532     if (!failing_open(r)) {
533         return false;
534     } else {
535         struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
536         struct rconn *local = r->halves[HALF_LOCAL].rconn;
537         lswitch_process_packet(r->lswitch, local, msg);
538         rconn_run(local);
539         return true;
540     }
541 }
542
543 static void
544 parse_options(int argc, char *argv[]) 
545 {
546     enum {
547         OPT_INACTIVITY_PROBE = UCHAR_MAX + 1,
548         OPT_MAX_IDLE,
549         OPT_MAX_BACKOFF
550     };
551     static struct option long_options[] = {
552         {"fail",        required_argument, 0, 'f'},
553         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
554         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
555         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
556         {"listen",      required_argument, 0, 'l'},
557         {"detach",      no_argument, 0, 'D'},
558         {"pidfile",     optional_argument, 0, 'P'},
559         {"verbose",     optional_argument, 0, 'v'},
560         {"help",        no_argument, 0, 'h'},
561         {"version",     no_argument, 0, 'V'},
562         VCONN_SSL_LONG_OPTIONS
563         {0, 0, 0, 0},
564     };
565     char *short_options = long_options_to_short_options(long_options);
566     
567     for (;;) {
568         int c;
569
570         c = getopt_long(argc, argv, short_options, long_options, NULL);
571         if (c == -1) {
572             break;
573         }
574
575         switch (c) {
576         case 'f':
577             if (!strcmp(optarg, "open")) {
578                 fail_mode = FAIL_OPEN;
579             } else if (!strcmp(optarg, "closed")) {
580                 fail_mode = FAIL_CLOSED;
581             } else {
582                 fatal(0,
583                       "-f or --fail argument must be \"open\" or \"closed\"");
584             }
585             break;
586
587         case OPT_INACTIVITY_PROBE:
588             probe_interval = atoi(optarg);
589             if (probe_interval < 5) {
590                 fatal(0, "--inactivity-probe argument must be at least 5");
591             }
592             break;
593
594         case OPT_MAX_IDLE:
595             if (!strcmp(optarg, "permanent")) {
596                 max_idle = OFP_FLOW_PERMANENT;
597             } else {
598                 max_idle = atoi(optarg);
599                 if (max_idle < 1 || max_idle > 65535) {
600                     fatal(0, "--max-idle argument must be between 1 and "
601                           "65535 or the word 'permanent'");
602                 }
603             }
604             break;
605
606         case OPT_MAX_BACKOFF:
607             max_backoff = atoi(optarg);
608             if (max_backoff < 1) {
609                 fatal(0, "--max-backoff argument must be at least 1");
610             } else if (max_backoff > 3600) {
611                 max_backoff = 3600;
612             }
613             break;
614
615         case 'D':
616             set_detach();
617             break;
618
619         case 'P':
620             set_pidfile(optarg ? optarg : "secchan.pid");
621             break;
622
623         case 'l':
624             if (listen_vconn_name) {
625                 fatal(0, "-l or --listen may be only specified once");
626             }
627             listen_vconn_name = optarg;
628             break;
629
630         case 'h':
631             usage();
632
633         case 'V':
634             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
635             exit(EXIT_SUCCESS);
636
637         case 'v':
638             vlog_set_verbosity(optarg);
639             break;
640
641         VCONN_SSL_OPTION_HANDLERS
642
643         case '?':
644             exit(EXIT_FAILURE);
645
646         default:
647             abort();
648         }
649     }
650     free(short_options);
651 }
652
653 static void
654 usage(void)
655 {
656     printf("%s: secure channel, a relay for OpenFlow messages.\n"
657            "usage: %s [OPTIONS] nl:DP_IDX CONTROLLER\n"
658            "where nl:DP_IDX is a datapath that has been added with dpctl\n"
659            "and CONTROLLER is an active OpenFlow connection method.\n",
660            program_name, program_name);
661     vconn_usage(true, true);
662     printf("\nNetworking options:\n"
663            "  -f, --fail=open|closed  when controller connection fails:\n"
664            "                            closed: drop all packets\n"
665            "                            open (default): act as learning switch\n"
666            "  --inactivity-probe=SECS time between inactivity probes\n"
667            "  --max-idle=SECS         max idle for flows set up by secchan\n"
668            "  --max-backoff=SECS      max time between controller connection\n"
669            "                          attempts (default: 15 seconds)\n"
670            "  -l, --listen=METHOD     allow management connections on METHOD\n"
671            "                          (a passive OpenFlow connection method)\n"
672            "\nOther options:\n"
673            "  -D, --detach            run in background as daemon\n"
674            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
675            "  -v, --verbose=MODULE:FACILITY:LEVEL  configure logging levels\n"
676            "  -v, --verbose           set maximum verbosity level\n"
677            "  -h, --help              display this help message\n"
678            "  -V, --version           display version information\n",
679            RUNDIR);
680     exit(EXIT_SUCCESS);
681 }