26621dfee7bde884c4bd4adaa0358af5b2fa960e
[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 "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         free(nl_name_without_subscription);
228         return;
229     }
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     free(nl_name_without_subscription);
237 }
238
239 static void
240 relay_create(struct rconn *local, struct rconn *remote)
241 {
242     struct relay *r;
243     int i;
244
245     r = xmalloc(sizeof *r);
246     r->halves[HALF_LOCAL].rconn = local;
247     r->halves[HALF_REMOTE].rconn = remote;
248     for (i = 0; i < 2; i++) {
249         r->halves[i].rxbuf = NULL;
250     }
251     list_push_back(&relays, &r->node);
252 }
253
254 static void
255 relay_run(struct relay *r)
256 {
257     int iteration;
258     int i;
259
260     for (i = 0; i < 2; i++) {
261         rconn_run(r->halves[i].rconn);
262     }
263
264     /* Limit the number of iterations to prevent other tasks from starving. */
265     for (iteration = 0; iteration < 50; iteration++) {
266         bool progress = false;
267         for (i = 0; i < 2; i++) {
268             struct half *this = &r->halves[i];
269             struct half *peer = &r->halves[!i];
270
271             if (!this->rxbuf) {
272                 this->rxbuf = rconn_recv(this->rconn);
273                 if (this->rxbuf && i == HALF_LOCAL && local_hook(r)) {
274                     buffer_delete(this->rxbuf);
275                     this->rxbuf = NULL;
276                 }
277             }
278
279             if (this->rxbuf) {
280                 int retval = rconn_send(peer->rconn, this->rxbuf);
281                 if (retval != EAGAIN) {
282                     if (!retval) {
283                         progress = true;
284                     } else {
285                         buffer_delete(this->rxbuf);
286                     }
287                     this->rxbuf = NULL;
288                 }
289             }
290         }
291         if (!progress) {
292             break;
293         }
294     }
295
296     for (i = 0; i < 2; i++) {
297         struct half *this = &r->halves[i];
298         if (!rconn_is_alive(this->rconn)) {
299             relay_destroy(r);
300             return;
301         }
302     }
303 }
304
305 static void
306 relay_wait(struct relay *r)
307 {
308     int i;
309
310     for (i = 0; i < 2; i++) {
311         struct half *this = &r->halves[i];
312
313         rconn_run_wait(this->rconn);
314         if (!this->rxbuf) {
315             rconn_recv_wait(this->rconn);
316         }
317     }
318 }
319
320 static void
321 relay_destroy(struct relay *r)
322 {
323     int i;
324
325     list_remove(&r->node);
326     for (i = 0; i < 2; i++) {
327         struct half *this = &r->halves[i];
328         rconn_destroy(this->rconn);
329         buffer_delete(this->rxbuf);
330     }
331     free(r);
332 }
333
334 static bool
335 local_hook(struct relay *r)
336 {
337     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
338     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
339     struct ofp_packet_in *opi;
340     struct ofp_header *oh;
341     size_t pkt_ofs, pkt_len;
342     struct buffer pkt, *b;
343     struct flow flow;
344     uint16_t in_port, out_port;
345
346     if (!local_port) {
347         return false;
348     }
349
350     oh = msg->data;
351     if (oh->type != OFPT_PACKET_IN) {
352         return false;
353     }
354     if (msg->size < offsetof (struct ofp_packet_in, data)) {
355         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
356         return false;
357     }
358
359     /* Extract flow data from 'opi' into 'flow'. */
360     opi = msg->data;
361     in_port = ntohs(opi->in_port);
362     pkt_ofs = offsetof(struct ofp_packet_in, data);
363     pkt_len = ntohs(opi->header.length) - pkt_ofs;
364     pkt.data = opi->data;
365     pkt.size = pkt_len;
366     flow_extract(&pkt, in_port, &flow);
367
368     /* Deal with local stuff. */
369     if (!rconn_is_connected(r->halves[HALF_REMOTE].rconn)
370         && eth_addr_is_broadcast(flow.dl_dst)) {
371         out_port = OFPP_FLOOD;
372     } else if (in_port == OFPP_LOCAL) {
373         out_port = mac_learning_lookup(local_ml, flow.dl_dst);
374     } else if (eth_addr_equals(flow.dl_dst, local_mac)) {
375         out_port = OFPP_LOCAL;
376         if (mac_learning_learn(local_ml, flow.dl_src, in_port)) {
377             VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
378                      ETH_ADDR_ARGS(flow.dl_src), in_port);
379         }
380     } else {
381         return false;
382     }
383
384     /* Add new flow. */
385     if (out_port != OFPP_FLOOD) {
386         b = make_add_simple_flow(&flow, ntohl(opi->buffer_id), out_port);
387         if (rconn_force_send(rc, b)) {
388             buffer_delete(b);
389         }
390     }
391
392     /* If the switch didn't buffer the packet, we need to send a copy. */
393     if (out_port == OFPP_FLOOD || ntohl(opi->buffer_id) == UINT32_MAX) {
394         b = make_unbuffered_packet_out(&pkt, in_port, out_port);
395         if (rconn_force_send(rc, b)) {
396             buffer_delete(b);
397         }
398     }
399     return true;
400 }
401
402 static void
403 parse_options(int argc, char *argv[]) 
404 {
405     static struct option long_options[] = {
406         {"listen",      required_argument, 0, 'l'},
407         {"verbose",     optional_argument, 0, 'v'},
408         {"help",        no_argument, 0, 'h'},
409         {"version",     no_argument, 0, 'V'},
410         VCONN_SSL_LONG_OPTIONS
411         {0, 0, 0, 0},
412     };
413     char *short_options = long_options_to_short_options(long_options);
414     
415     for (;;) {
416         int c;
417
418         c = getopt_long(argc, argv, short_options, long_options, NULL);
419         if (c == -1) {
420             break;
421         }
422
423         switch (c) {
424         case 'l':
425             if (listen_vconn_name) {
426                 fatal(0, "-l or --listen may be only specified once");
427             }
428             listen_vconn_name = optarg;
429             break;
430
431         case 'h':
432             usage();
433
434         case 'V':
435             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
436             exit(EXIT_SUCCESS);
437
438         case 'v':
439             vlog_set_verbosity(optarg);
440             break;
441
442         VCONN_SSL_OPTION_HANDLERS
443
444         case '?':
445             exit(EXIT_FAILURE);
446
447         default:
448             abort();
449         }
450     }
451     free(short_options);
452 }
453
454 static void
455 usage(void)
456 {
457     printf("%s: Secure Channel, a relay for OpenFlow messages.\n"
458            "usage: %s [OPTIONS] LOCAL REMOTE\n"
459            "where LOCAL and REMOTE are active OpenFlow connection methods.\n",
460            program_name, program_name);
461     vconn_usage(true, true);
462     printf("\nNetworking options:\n"
463            "  -l, --listen=METHOD     allow management connections on METHOD\n"
464            "                          (a passive OpenFlow connection method)\n"
465            "\nOther options:\n"
466            "  -v, --verbose           set maximum verbosity level\n"
467            "  -h, --help              display this help message\n"
468            "  -V, --version           display version information\n");
469     exit(EXIT_SUCCESS);
470 }