Make in-band communication work.
[openvswitch] / 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 "fault.h"
48 #include "flow.h"
49 #include "list.h"
50 #include "mac-learning.h"
51 #include "netdev.h"
52 #include "openflow.h"
53 #include "packets.h"
54 #include "poll-loop.h"
55 #include "rconn.h"
56 #include "util.h"
57 #include "vconn-ssl.h"
58 #include "vconn.h"
59 #include "vlog-socket.h"
60
61 #include "vlog.h"
62 #define THIS_MODULE VLM_secchan
63
64 #include "ofp-print.h"
65
66 static const char *listen_vconn_name;
67
68 struct half {
69     struct rconn *rconn;
70     struct buffer *rxbuf;
71 };
72
73 struct relay {
74     struct list node;
75
76 #define HALF_LOCAL 0
77 #define HALF_REMOTE 1
78     struct half halves[2];
79 };
80
81 static struct list relays = LIST_INITIALIZER(&relays);
82
83 /* Enable the local port? */
84 static int local_port;
85
86 /* MAC address of local port. */
87 static uint8_t local_mac[ETH_ADDR_LEN];
88
89 /* MAC learning table for local port. */
90 static struct mac_learning *local_ml;
91
92 static void parse_options(int argc, char *argv[]);
93 static void usage(void) NO_RETURN;
94
95 static void new_management_connection(const char *nl_name, struct vconn *new_remote);
96 static void relay_create(struct rconn *local, struct rconn *remote);
97 static void relay_run(struct relay *);
98 static void relay_wait(struct relay *);
99 static void relay_destroy(struct relay *);
100
101 static bool local_hook(struct relay *r);
102
103 int
104 main(int argc, char *argv[])
105 {
106     struct vconn *listen_vconn;
107     struct netdev *of_device;
108     const char *nl_name;
109     char of_name[16];
110     int retval;
111
112     set_program_name(argv[0]);
113     register_fault_handlers();
114     vlog_init();
115     parse_options(argc, argv);
116
117     if (argc - optind != 2) {
118         fatal(0,
119               "need exactly two non-option arguments; use --help for usage");
120     }
121     nl_name = argv[optind];
122     if (strncmp(nl_name, "nl:", 3)
123         || strlen(nl_name) < 4
124         || nl_name[strspn(nl_name + 3, "0123456789") + 3]) {
125         fatal(0, "%s: argument is not of the form \"nl:DP_ID\"", nl_name);
126     }
127
128     if (listen_vconn_name) {
129         retval = vconn_open(listen_vconn_name, &listen_vconn);
130         if (retval && retval != EAGAIN) {
131             fatal(retval, "opening %s", listen_vconn_name);
132         }
133         if (!vconn_is_passive(listen_vconn)) {
134             fatal(0, "%s is not a passive vconn", listen_vconn_name);
135         }
136     } else {
137         listen_vconn = NULL;
138     }
139
140
141     snprintf(of_name, sizeof of_name, "of%s", nl_name + 3);
142     retval = netdev_open(of_name, &of_device);
143     if (!retval) {
144         enum netdev_flags flags;
145         retval = netdev_get_flags(of_device, &flags);
146         if (!retval) {
147             if (flags & NETDEV_UP) {
148                 struct in6_addr in6;
149
150                 local_port = true;
151                 memcpy(local_mac, netdev_get_etheraddr(of_device),
152                        ETH_ADDR_LEN);
153                 if (netdev_get_in6(of_device, &in6)) {
154                     VLOG_WARN("Ignoring IPv6 address on %s device: "
155                               "IPv6 not supported", of_name);
156                 }
157                 local_ml = mac_learning_create();
158             }
159         } else {
160             error(retval, "Could not get flags for %s device", of_name);
161         }
162         netdev_close(of_device);
163     } else {
164         error(retval, "Could not open %s device", of_name);
165     }
166
167     retval = vlog_server_listen(NULL, NULL);
168     if (retval) {
169         fatal(retval, "Could not listen for vlog connections");
170     }
171
172     relay_create(rconn_new(argv[optind], 1), rconn_new(argv[optind + 1], 1));
173     for (;;) {
174         struct relay *r, *n;
175
176         /* Do work. */
177         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
178             relay_run(r);
179         }
180         if (listen_vconn) {
181             for (;;) {
182                 struct vconn *new_remote;
183                 retval = vconn_accept(listen_vconn, &new_remote);
184                 if (retval) {
185                     if (retval != EAGAIN) {
186                         VLOG_WARN("accept failed (%s)", strerror(retval));
187                     }
188                     break;
189                 }
190                 new_management_connection(nl_name, new_remote);
191             }
192         }
193
194         /* Wait for something to happen. */
195         LIST_FOR_EACH (r, struct relay, node, &relays) {
196             relay_wait(r);
197         }
198         if (listen_vconn) {
199             vconn_accept_wait(listen_vconn);
200         }
201         poll_block();
202     }
203
204     return 0;
205 }
206
207 static void
208 new_management_connection(const char *nl_name, struct vconn *new_remote)
209 {
210     char *nl_name_without_subscription;
211     struct vconn *new_local;
212     struct rconn *r1, *r2;
213     int retval;
214
215     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
216      * only accept the former syntax in main().
217      *
218      * nl:123:0 opens a netlink connection to local datapath 123 without
219      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
220      * messages.*/
221     nl_name_without_subscription = xasprintf("%s:0", nl_name);
222     retval = vconn_open(nl_name_without_subscription, &new_local);
223     if (retval) {
224         VLOG_ERR("could not connect to %s (%s)",
225                  nl_name_without_subscription, strerror(retval));
226         vconn_close(new_remote);
227         return;
228     }
229     free(nl_name_without_subscription);
230
231     /* Add it to the relay list. */
232     r1 = rconn_new_from_vconn(nl_name_without_subscription, 1, new_local);
233     r2 = rconn_new_from_vconn("passive", 1, new_remote);
234     relay_create(r1, r2);
235 }
236
237 static void
238 relay_create(struct rconn *local, struct rconn *remote)
239 {
240     struct relay *r;
241     int i;
242
243     r = xmalloc(sizeof *r);
244     r->halves[HALF_LOCAL].rconn = local;
245     r->halves[HALF_REMOTE].rconn = remote;
246     for (i = 0; i < 2; i++) {
247         r->halves[i].rxbuf = NULL;
248     }
249     list_push_back(&relays, &r->node);
250 }
251
252 static void
253 relay_run(struct relay *r)
254 {
255     int iteration;
256     int i;
257
258     for (i = 0; i < 2; i++) {
259         rconn_run(r->halves[i].rconn);
260     }
261
262     /* Limit the number of iterations to prevent other tasks from starving. */
263     for (iteration = 0; iteration < 50; iteration++) {
264         bool progress = false;
265         for (i = 0; i < 2; i++) {
266             struct half *this = &r->halves[i];
267             struct half *peer = &r->halves[!i];
268
269             if (!this->rxbuf) {
270                 this->rxbuf = rconn_recv(this->rconn);
271                 if (this->rxbuf && i == HALF_LOCAL && local_hook(r)) {
272                     buffer_delete(this->rxbuf);
273                     this->rxbuf = NULL;
274                 }
275             }
276
277             if (this->rxbuf) {
278                 int retval = rconn_send(peer->rconn, this->rxbuf);
279                 if (retval != EAGAIN) {
280                     if (!retval) {
281                         progress = true;
282                     } else {
283                         buffer_delete(this->rxbuf);
284                     }
285                     this->rxbuf = NULL;
286                 }
287             }
288         }
289         if (!progress) {
290             break;
291         }
292     }
293
294     for (i = 0; i < 2; i++) {
295         struct half *this = &r->halves[i];
296         if (!rconn_is_alive(this->rconn)) {
297             relay_destroy(r);
298             return;
299         }
300     }
301 }
302
303 static void
304 relay_wait(struct relay *r)
305 {
306     int i;
307
308     for (i = 0; i < 2; i++) {
309         struct half *this = &r->halves[i];
310
311         rconn_run_wait(this->rconn);
312         if (!this->rxbuf) {
313             rconn_recv_wait(this->rconn);
314         }
315     }
316 }
317
318 static void
319 relay_destroy(struct relay *r)
320 {
321     int i;
322
323     list_remove(&r->node);
324     for (i = 0; i < 2; i++) {
325         struct half *this = &r->halves[i];
326         rconn_destroy(this->rconn);
327         buffer_delete(this->rxbuf);
328     }
329     free(r);
330 }
331
332 static bool
333 local_hook(struct relay *r)
334 {
335     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
336     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
337     struct ofp_packet_in *opi;
338     struct ofp_header *oh;
339     size_t pkt_ofs, pkt_len;
340     struct buffer pkt, *b;
341     struct flow flow;
342     uint16_t in_port, out_port;
343
344     if (!local_port) {
345         return false;
346     }
347
348     oh = msg->data;
349     if (oh->type != OFPT_PACKET_IN) {
350         return false;
351     }
352     if (msg->size < offsetof (struct ofp_packet_in, data)) {
353         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
354         return false;
355     }
356
357     /* Extract flow data from 'opi' into 'flow'. */
358     opi = msg->data;
359     in_port = ntohs(opi->in_port);
360     pkt_ofs = offsetof(struct ofp_packet_in, data);
361     pkt_len = ntohs(opi->header.length) - pkt_ofs;
362     pkt.data = opi->data;
363     pkt.size = pkt_len;
364     flow_extract(&pkt, in_port, &flow);
365
366     /* Deal with local stuff. */
367     if (!rconn_is_connected(r->halves[HALF_REMOTE].rconn)
368         && eth_addr_is_broadcast(flow.dl_dst)) {
369         out_port = OFPP_FLOOD;
370     } else if (in_port == OFPP_LOCAL) {
371         out_port = mac_learning_lookup(local_ml, flow.dl_dst);
372     } else if (eth_addr_equals(flow.dl_dst, local_mac)) {
373         out_port = OFPP_LOCAL;
374         if (mac_learning_learn(local_ml, flow.dl_src, in_port)) {
375             VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
376                      ETH_ADDR_ARGS(flow.dl_src), in_port);
377         }
378     } else {
379         return false;
380     }
381
382     /* Add new flow. */
383     if (out_port != OFPP_FLOOD) {
384         b = make_add_simple_flow(&flow, ntohl(opi->buffer_id), out_port);
385         if (rconn_force_send(rc, b)) {
386             buffer_delete(b);
387         }
388     }
389
390     /* If the switch didn't buffer the packet, we need to send a copy. */
391     if (out_port == OFPP_FLOOD || ntohl(opi->buffer_id) == UINT32_MAX) {
392         b = make_unbuffered_packet_out(&pkt, in_port, out_port);
393         if (rconn_force_send(rc, b)) {
394             buffer_delete(b);
395         }
396     }
397     return true;
398 }
399
400 static void
401 parse_options(int argc, char *argv[]) 
402 {
403     static struct option long_options[] = {
404         {"listen",      required_argument, 0, 'l'},
405         {"verbose",     optional_argument, 0, 'v'},
406         {"help",        no_argument, 0, 'h'},
407         {"version",     no_argument, 0, 'V'},
408         VCONN_SSL_LONG_OPTIONS
409         {0, 0, 0, 0},
410     };
411     char *short_options = long_options_to_short_options(long_options);
412     
413     for (;;) {
414         int c;
415
416         c = getopt_long(argc, argv, short_options, long_options, NULL);
417         if (c == -1) {
418             break;
419         }
420
421         switch (c) {
422         case 'l':
423             if (listen_vconn_name) {
424                 fatal(0, "-l or --listen may be only specified once");
425             }
426             listen_vconn_name = optarg;
427             break;
428
429         case 'h':
430             usage();
431
432         case 'V':
433             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
434             exit(EXIT_SUCCESS);
435
436         case 'v':
437             vlog_set_verbosity(optarg);
438             break;
439
440         VCONN_SSL_OPTION_HANDLERS
441
442         case '?':
443             exit(EXIT_FAILURE);
444
445         default:
446             abort();
447         }
448     }
449     free(short_options);
450 }
451
452 static void
453 usage(void)
454 {
455     printf("%s: Secure Channel, a relay for OpenFlow messages.\n"
456            "usage: %s [OPTIONS] LOCAL REMOTE\n"
457            "where LOCAL and REMOTE are active OpenFlow connection methods.\n",
458            program_name, program_name);
459     vconn_usage(true, true);
460     printf("\nNetworking options:\n"
461            "  -l, --listen=METHOD     allow management connections on METHOD\n"
462            "                          (a passive OpenFlow connection method)\n"
463            "\nOther options:\n"
464            "  -v, --verbose           set maximum verbosity level\n"
465            "  -h, --help              display this help message\n"
466            "  -V, --version           display version information\n");
467     exit(EXIT_SUCCESS);
468 }