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