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