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