Fix arguments to printf in usage message.
[sliver-openvswitch.git] / controller / controller.c
1 /* Copyright (C) 2007 Board of Trustees, Leland Stanford Jr. University.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to
5  * deal in the Software without restriction, including without limitation the
6  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7  * sell copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19  * IN THE SOFTWARE.
20  */
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <getopt.h>
25 #include <inttypes.h>
26 #include <netinet/in.h>
27 #include <poll.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #include "buffer.h"
33 #include "command-line.h"
34 #include "compiler.h"
35 #include "fault.h"
36 #include "flow.h"
37 #include "hash.h"
38 #include "list.h"
39 #include "mac.h"
40 #include "ofp-print.h"
41 #include "openflow.h"
42 #include "time.h"
43 #include "util.h"
44 #include "vconn-ssl.h"
45 #include "vconn.h"
46 #include "vlog-socket.h"
47 #include "xtoxll.h"
48
49 #include "vlog.h"
50 #define THIS_MODULE VLM_controller
51
52 #define MAX_SWITCHES 16
53 #define MAX_TXQ 128
54
55 struct switch_ {
56     char *name;
57     struct vconn *vconn;
58     struct pollfd *pollfd;
59
60     uint64_t datapath_id;
61     time_t last_control_hello;
62
63     int n_txq;
64     struct buffer *txq, *tx_tail;
65 };
66
67 /* -H, --hub: Use dumb hub instead of learning switch? */
68 static bool hub = false;
69
70 /* -n, --noflow: Pass traffic, but don't setup flows in switch */
71 static bool noflow = false;
72
73 static void parse_options(int argc, char *argv[]);
74 static void usage(void) NO_RETURN;
75
76 static struct switch_ *connect_switch(const char *name);
77 static struct switch_ *new_switch(const char *name, struct vconn *);
78 static void close_switch(struct switch_ *);
79
80 static void queue_tx(struct switch_ *, struct buffer *);
81
82 static void send_control_hello(struct switch_ *);
83
84 static int do_switch_recv(struct switch_ *this);
85 static int do_switch_send(struct switch_ *this);
86
87 static void process_packet(struct switch_ *, struct buffer *);
88 static void process_hub(struct switch_ *, struct ofp_packet_in *);
89 static void process_noflow(struct switch_ *, struct ofp_packet_in *);
90
91 static void switch_init(void);
92 static void process_switch(struct switch_ *, struct ofp_packet_in *);
93
94 int
95 main(int argc, char *argv[])
96 {
97     struct switch_ *switches[MAX_SWITCHES];
98     struct pollfd pollfds[MAX_SWITCHES + 1];
99     struct vlog_server *vlog_server;
100     int n_switches;
101     int retval;
102     int i;
103
104     set_program_name(argv[0]);
105     register_fault_handlers();
106     vlog_init();
107     parse_options(argc, argv);
108
109     if (!hub && !noflow) {
110         switch_init();
111     }
112
113     if (argc - optind < 1) {
114         fatal(0, "at least one vconn argument required; use --help for usage");
115     }
116
117     retval = vlog_server_listen(NULL, &vlog_server);
118     if (retval) {
119         fatal(retval, "Could not listen for vlog connections");
120     }
121
122     n_switches = 0;
123     for (i = 0; i < argc - optind; i++) {
124         struct switch_ *this = connect_switch(argv[optind + i]);
125         if (this) {
126             if (n_switches >= MAX_SWITCHES) {
127                 fatal(0, "max %d switch connections", n_switches);
128             }
129             switches[n_switches++] = this;
130         }
131     }
132     if (n_switches == 0) {
133         fatal(0, "could not connect to any switches");
134     }
135     
136     while (n_switches > 0) {
137         size_t n_ready;
138         int retval;
139
140         /* Wait until there's something to do. */
141         n_ready = 0;
142         for (i = 0; i < n_switches; i++) {
143             struct switch_ *this = switches[i];
144             int want;
145
146             if (vconn_is_passive(this->vconn)) {
147                 want = n_switches < MAX_SWITCHES ? WANT_ACCEPT : 0;
148             } else {
149                 want = WANT_RECV;
150                 if (this->n_txq) {
151                     want |= WANT_SEND;
152                 }
153             }
154
155             this->pollfd = &pollfds[i];
156             this->pollfd->fd = -1;
157             this->pollfd->events = 0;
158             n_ready += vconn_prepoll(this->vconn, want, this->pollfd);
159         }
160         if (vlog_server) {
161             pollfds[n_switches].fd = vlog_server_get_fd(vlog_server);
162             pollfds[n_switches].events = POLLIN;
163         }
164         do {
165             retval = poll(pollfds, n_switches + (vlog_server != NULL),
166                           n_ready ? 0 : -1);
167         } while (retval < 0 && errno == EINTR);
168         if (retval < 0 || (retval == 0 && !n_ready)) {
169             fatal(retval < 0 ? errno : 0, "poll");
170         }
171
172         /* Let each connection deal with any pending operations. */
173         for (i = 0; i < n_switches; i++) {
174             struct switch_ *this = switches[i];
175             vconn_postpoll(this->vconn, &this->pollfd->revents);
176             if (this->pollfd->revents & POLLERR) {
177                 this->pollfd->revents |= POLLIN | POLLOUT;
178             }
179         }
180         if (vlog_server && pollfds[n_switches].revents) {
181             vlog_server_poll(vlog_server);
182         }
183
184         for (i = 0; i < n_switches; ) {
185             struct switch_ *this = switches[i];
186
187             if (this->pollfd) {
188                 retval = 0;
189                 if (vconn_is_passive(this->vconn)) {
190                     if (this->pollfd->revents & POLLIN) {
191                         struct vconn *new_vconn;
192                         while (n_switches < MAX_SWITCHES 
193                                && (retval = vconn_accept(this->vconn,
194                                                          &new_vconn)) == 0) {
195                             switches[n_switches++] = new_switch("tcp",
196                                                                 new_vconn);
197                         }
198                     }
199                 } else {
200                     bool may_read = this->pollfd->revents & POLLIN;
201                     bool may_write = this->pollfd->revents & POLLOUT;
202                     if (may_read) {
203                         retval = do_switch_recv(this);
204                         if (!retval || retval == EAGAIN) {
205                             retval = 0;
206
207                             /* Enable writing to avoid round trip through poll
208                              * in common case. */
209                             may_write = true;
210                         }
211                     }
212                     while ((!retval || retval == EAGAIN) && may_write) {
213                         retval = do_switch_send(this);
214                         may_write = !retval;
215                     }
216                 }
217
218                 if (retval && retval != EAGAIN) {
219                     close_switch(this);
220                     switches[i] = switches[--n_switches];
221                     continue;
222                 }
223             } else {
224                 /* New switch that hasn't been polled yet. */
225             }
226             i++;
227         }
228     }
229
230     return 0;
231 }
232
233 static int
234 do_switch_recv(struct switch_ *this) 
235 {
236     struct buffer *msg;
237     int retval;
238
239     retval = vconn_recv(this->vconn, &msg);
240     if (!retval) {
241         process_packet(this, msg);
242         buffer_delete(msg);
243     }
244     return retval;
245 }
246
247 static int
248 do_switch_send(struct switch_ *this) 
249 {
250     int retval = 0;
251     if (this->n_txq) {
252         struct buffer *next = this->txq->next;
253
254         retval = vconn_send(this->vconn, this->txq);
255         if (retval) {
256             return retval;
257         }
258
259         this->txq = next;
260         if (this->txq == NULL) {
261             this->tx_tail = NULL;
262         }
263         this->n_txq--;
264         return 0;
265     }
266     return EAGAIN;
267 }
268
269 struct switch_ *
270 connect_switch(const char *name) 
271 {
272     struct vconn *vconn;
273     int retval;
274
275     retval = vconn_open(name, &vconn);
276     if (retval) {
277         VLOG_ERR("%s: connect: %s", name, strerror(retval));
278         return NULL;
279     }
280
281     return new_switch(name, vconn);
282 }
283
284 static struct switch_ *
285 new_switch(const char *name, struct vconn *vconn) 
286 {
287     struct switch_ *this = xmalloc(sizeof *this);
288     memset(this, 0, sizeof *this);
289     this->name = xstrdup(name);
290     this->vconn = vconn;
291     this->pollfd = NULL;
292     this->n_txq = 0;
293     this->txq = NULL;
294     this->tx_tail = NULL;
295     this->last_control_hello = 0;
296     if (!vconn_is_passive(vconn)) {
297         send_control_hello(this);
298     }
299     return this;
300 }
301
302 static void
303 close_switch(struct switch_ *this) 
304 {
305     if (this) {
306         struct buffer *cur, *next;
307
308         free(this->name);
309         vconn_close(this->vconn);
310         for (cur = this->txq; cur != NULL; cur = next) {
311             next = cur->next;
312             buffer_delete(cur);
313         }
314         free(this);
315     }
316 }
317
318 static void
319 send_control_hello(struct switch_ *this)
320 {
321     time_t now = time(0);
322     if (now >= this->last_control_hello + 1) {
323         struct buffer *b;
324         struct ofp_control_hello *och;
325
326         b = buffer_new(0);
327         och = buffer_put_uninit(b, sizeof *och);
328         memset(och, 0, sizeof *och);
329         och->header.version = OFP_VERSION;
330         och->header.length = htons(sizeof *och);
331
332         och->version = htonl(OFP_VERSION);
333         och->flags = htons(OFP_CHELLO_SEND_FLOW_EXP);
334         och->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
335         queue_tx(this, b);
336
337         this->last_control_hello = now;
338     }
339 }
340
341 static void
342 check_txq(struct switch_ *this UNUSED)
343 {
344 #if 0
345     struct buffer *iter;
346     size_t n;
347
348     assert(this->n_txq == 0
349            ? this->txq == NULL && this->tx_tail == NULL
350            : this->txq != NULL && this->tx_tail != NULL);
351
352     n = 0;
353     for (iter = this->txq; iter != NULL; iter = iter->next) {
354         n++;
355         assert((iter->next != NULL) == (iter != this->tx_tail));
356     }
357     assert(n == this->n_txq);
358 #endif
359 }
360
361 static void
362 queue_tx(struct switch_ *this, struct buffer *b) 
363 {
364     check_txq(this);
365
366     b->next = NULL;
367     if (this->n_txq++) {
368         this->tx_tail->next = b;
369     } else {
370         this->txq = b;
371     }
372     this->tx_tail = b;
373
374     check_txq(this);
375 }
376
377 static void
378 process_packet(struct switch_ *sw, struct buffer *msg) 
379 {
380     static const size_t min_size[UINT8_MAX + 1] = {
381         [0 ... UINT8_MAX] = SIZE_MAX,
382         [OFPT_CONTROL_HELLO] = sizeof (struct ofp_control_hello),
383         [OFPT_DATA_HELLO] = sizeof (struct ofp_data_hello),
384         [OFPT_PACKET_IN] = offsetof (struct ofp_packet_in, data),
385         [OFPT_PACKET_OUT] = sizeof (struct ofp_packet_out),
386         [OFPT_FLOW_MOD] = sizeof (struct ofp_flow_mod),
387         [OFPT_FLOW_EXPIRED] = sizeof (struct ofp_flow_expired),
388         [OFPT_TABLE] = sizeof (struct ofp_table),
389         [OFPT_PORT_MOD] = sizeof (struct ofp_port_mod),
390         [OFPT_PORT_STATUS] = sizeof (struct ofp_port_status),
391         [OFPT_FLOW_STAT_REQUEST] = sizeof (struct ofp_flow_stat_request),
392         [OFPT_FLOW_STAT_REPLY] = sizeof (struct ofp_flow_stat_reply),
393     };
394     struct ofp_header *oh;
395
396     oh = msg->data;
397     if (msg->size < min_size[oh->type]) {
398         VLOG_WARN("%s: too short (%zu bytes) for type %"PRIu8" (min %zu)",
399                   sw->name, msg->size, oh->type, min_size[oh->type]);
400         return;
401     }
402
403     if (oh->type == OFPT_DATA_HELLO) {
404         struct ofp_data_hello *odh = msg->data;
405         sw->datapath_id = odh->datapath_id;
406     } else if (sw->datapath_id == 0) {
407         send_control_hello(sw);
408         return;
409     }
410
411     if (oh->type == OFPT_PACKET_IN) {
412         if (sw->n_txq >= MAX_TXQ) {
413             VLOG_WARN("%s: tx queue overflow", sw->name);
414         } else if (noflow) {
415             process_noflow(sw, msg->data);
416         } else if (hub) {
417             process_hub(sw, msg->data);
418         } else {
419             process_switch(sw, msg->data);
420         }
421         return;
422     }
423
424     ofp_print(stdout, msg->data, msg->size, 2);
425 }
426
427 static void
428 process_hub(struct switch_ *sw, struct ofp_packet_in *opi)
429 {
430     size_t pkt_ofs, pkt_len;
431     struct buffer pkt;
432     struct flow flow;
433
434     /* Extract flow data from 'opi' into 'flow'. */
435     pkt_ofs = offsetof(struct ofp_packet_in, data);
436     pkt_len = ntohs(opi->header.length) - pkt_ofs;
437     pkt.data = opi->data;
438     pkt.size = pkt_len;
439     flow_extract(&pkt, ntohs(opi->in_port), &flow);
440
441     /* Add new flow. */
442     queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
443                                       OFPP_FLOOD));
444
445     /* If the switch didn't buffer the packet, we need to send a copy. */
446     if (ntohl(opi->buffer_id) == UINT32_MAX) {
447         queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(flow.in_port),
448                                                 OFPP_FLOOD));
449     }
450 }
451
452 static void
453 process_noflow(struct switch_ *sw, struct ofp_packet_in *opi)
454 {
455     /* If the switch didn't buffer the packet, we need to send a copy. */
456     if (ntohl(opi->buffer_id) == UINT32_MAX) {
457         size_t pkt_ofs, pkt_len;
458         struct buffer pkt;
459
460         /* Extract flow data from 'opi' into 'flow'. */
461         pkt_ofs = offsetof(struct ofp_packet_in, data);
462         pkt_len = ntohs(opi->header.length) - pkt_ofs;
463         pkt.data = opi->data;
464         pkt.size = pkt_len;
465
466         queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(opi->in_port),
467                     OFPP_FLOOD));
468     } else {
469         queue_tx(sw, make_buffered_packet_out(ntohl(opi->buffer_id), 
470                     ntohs(opi->in_port), OFPP_FLOOD));
471     }
472 }
473
474
475 #define MAC_HASH_BITS 10
476 #define MAC_HASH_MASK (MAC_HASH_SIZE - 1)
477 #define MAC_HASH_SIZE (1u << MAC_HASH_BITS)
478
479 #define MAC_MAX 1024
480
481 struct mac_source {
482     struct list hash_list;
483     struct list lru_list;
484     uint64_t datapath_id;
485     uint8_t mac[ETH_ADDR_LEN];
486     uint16_t port;
487 };
488
489 static struct list mac_table[MAC_HASH_SIZE];
490 static struct list lrus;
491 static size_t mac_count;
492
493 static void
494 switch_init(void)
495 {
496     int i;
497
498     list_init(&lrus);
499     for (i = 0; i < MAC_HASH_SIZE; i++) {
500         list_init(&mac_table[i]);
501     }
502 }
503
504 static struct list *
505 mac_table_bucket(uint64_t datapath_id, const uint8_t mac[ETH_ADDR_LEN]) 
506 {
507     uint32_t hash;
508     hash = hash_fnv(&datapath_id, sizeof datapath_id, HASH_FNV_BASIS);
509     hash = hash_fnv(mac, ETH_ADDR_LEN, hash);
510     return &mac_table[hash & MAC_HASH_BITS];
511 }
512
513 static void
514 process_switch(struct switch_ *sw, struct ofp_packet_in *opi)
515 {
516     size_t pkt_ofs, pkt_len;
517     struct buffer pkt;
518     struct flow flow;
519
520     uint16_t out_port;
521
522     /* Extract flow data from 'opi' into 'flow'. */
523     pkt_ofs = offsetof(struct ofp_packet_in, data);
524     pkt_len = ntohs(opi->header.length) - pkt_ofs;
525     pkt.data = opi->data;
526     pkt.size = pkt_len;
527     flow_extract(&pkt, ntohs(opi->in_port), &flow);
528
529     /* Learn the source. */
530     if (!mac_is_multicast(flow.dl_src)) {
531         struct mac_source *src;
532         struct list *bucket;
533         bool found;
534
535         bucket = mac_table_bucket(sw->datapath_id, flow.dl_src);
536         found = false;
537         LIST_FOR_EACH (src, struct mac_source, hash_list, bucket) {
538             if (src->datapath_id == sw->datapath_id
539                 && mac_equals(src->mac, flow.dl_src)) {
540                 found = true;
541                 break;
542             }
543         }
544
545         if (!found) {
546             /* Learn a new address. */
547
548             if (mac_count >= MAC_MAX) {
549                 /* Drop the least recently used mac source. */
550                 struct mac_source *lru;
551                 lru = CONTAINER_OF(lrus.next, struct mac_source, lru_list);
552                 list_remove(&lru->hash_list);
553                 list_remove(&lru->lru_list);
554                 free(lru);
555             } else {
556                 mac_count++;
557             }
558
559             /* Create new mac source */
560             src = xmalloc(sizeof *src);
561             src->datapath_id = sw->datapath_id;
562             memcpy(src->mac, flow.dl_src, ETH_ADDR_LEN);
563             src->port = -1;
564             list_push_front(bucket, &src->hash_list);
565             list_push_back(&lrus, &src->lru_list);
566         } else {
567             /* Make 'src' most-recently-used.  */
568             list_remove(&src->lru_list);
569             list_push_back(&lrus, &src->lru_list);
570         }
571
572         if (ntohs(flow.in_port) != src->port) {
573             src->port = ntohs(flow.in_port);
574             VLOG_DBG("learned that "MAC_FMT" is on datapath %"PRIx64" port %d",
575                      MAC_ARGS(src->mac), ntohll(src->datapath_id),
576                      src->port);
577         }
578     } else {
579         VLOG_DBG("multicast packet source "MAC_FMT, MAC_ARGS(flow.dl_src));
580     }
581
582     /* Figure out the destination. */
583     out_port = OFPP_FLOOD;
584     if (!mac_is_multicast(flow.dl_dst)) {
585         struct mac_source *dst;
586         struct list *bucket;
587
588         bucket = mac_table_bucket(sw->datapath_id, flow.dl_dst);
589         LIST_FOR_EACH (dst, struct mac_source, hash_list, bucket) {
590             if (dst->datapath_id == sw->datapath_id
591                 && mac_equals(dst->mac, flow.dl_dst)) {
592                 out_port = dst->port;
593                 break;
594             }
595         }
596     }
597
598     if (out_port != OFPP_FLOOD) {
599         /* The output port is known, so add a new flow. */
600         queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id), 
601                     out_port));
602
603         /* If the switch didn't buffer the packet, we need to send a copy. */
604         if (ntohl(opi->buffer_id) == UINT32_MAX) {
605             queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(flow.in_port),
606                                                     out_port));
607         }
608     } else {
609         /* We don't know that MAC.  Flood the packet. */
610         struct buffer *b;
611         if (ntohl(opi->buffer_id) == UINT32_MAX) {
612             b = make_unbuffered_packet_out(&pkt, ntohs(flow.in_port), out_port);
613         } else {
614             b = make_buffered_packet_out(ntohl(opi->buffer_id), 
615                         ntohs(flow.in_port), out_port);
616         }
617         queue_tx(sw, b);
618     }
619 }
620
621 static void
622 parse_options(int argc, char *argv[])
623 {
624     static struct option long_options[] = {
625         {"hub",         no_argument, 0, 'H'},
626         {"noflow",      no_argument, 0, 'n'},
627         {"verbose",     optional_argument, 0, 'v'},
628         {"help",        no_argument, 0, 'h'},
629         {"version",     no_argument, 0, 'V'},
630 #ifdef HAVE_OPENSSL
631         {"private-key", required_argument, 0, 'p'},
632         {"certificate", required_argument, 0, 'c'},
633         {"ca-cert",     required_argument, 0, 'C'},
634 #endif
635         {0, 0, 0, 0},
636     };
637     char *short_options = long_options_to_short_options(long_options);
638
639     for (;;) {
640         int indexptr;
641         int c;
642
643         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
644         if (c == -1) {
645             break;
646         }
647
648         switch (c) {
649         case 'H':
650             hub = true;
651             break;
652
653         case 'n':
654             noflow = true;
655             break;
656
657         case 'h':
658             usage();
659
660         case 'V':
661             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
662             exit(EXIT_SUCCESS);
663
664         case 'v':
665             vlog_set_verbosity(optarg);
666             break;
667
668 #ifdef HAVE_OPENSSL
669         case 'p':
670             vconn_ssl_set_private_key_file(optarg);
671             break;
672
673         case 'c':
674             vconn_ssl_set_certificate_file(optarg);
675             break;
676
677         case 'C':
678             vconn_ssl_set_ca_cert_file(optarg);
679             break;
680 #endif
681
682         case '?':
683             exit(EXIT_FAILURE);
684
685         default:
686             abort();
687         }
688     }
689     free(short_options);
690 }
691
692 static void
693 usage(void)
694 {
695     printf("%s: OpenFlow controller\n"
696            "usage: %s [OPTIONS] VCONN\n"
697            "where VCONN is one of the following:\n"
698            "  ptcp:[PORT]             listen to TCP PORT (default: %d)\n",
699            program_name, program_name, OFP_TCP_PORT);
700 #ifdef HAVE_NETLINK
701     printf("  nl:DP_IDX               via netlink to local datapath DP_IDX\n");
702 #endif
703 #ifdef HAVE_OPENSSL
704     printf("  pssl:[PORT]             listen for SSL on PORT (default: %d)\n"
705            "\nPKI configuration (required to use SSL):\n"
706            "  -p, --private-key=FILE  file with private key\n"
707            "  -c, --certificate=FILE  file with certificate for private key\n"
708            "  -C, --ca-cert=FILE      file with peer CA certificate\n",
709            OFP_SSL_PORT);
710 #endif
711     printf("\nOther options:\n"
712            "  -H, --hub               act as hub instead of learning switch\n"
713            "  -n, --noflow            pass traffic, but don't add flows\n"
714            "  -v, --verbose           set maximum verbosity level\n"
715            "  -h, --help              display this help message\n"
716            "  -V, --version           display version information\n");
717     exit(EXIT_SUCCESS);
718 }