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