Factor out parsing vconn-ssl options.
[sliver-openvswitch.git] / controller / controller.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 <assert.h>
35 #include <errno.h>
36 #include <getopt.h>
37 #include <inttypes.h>
38 #include <netinet/in.h>
39 #include <poll.h>
40 #include <stdlib.h>
41 #include <string.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 "hash.h"
50 #include "list.h"
51 #include "ofp-print.h"
52 #include "openflow.h"
53 #include "packets.h"
54 #include "poll-loop.h"
55 #include "queue.h"
56 #include "time.h"
57 #include "util.h"
58 #include "vconn-ssl.h"
59 #include "vconn.h"
60 #include "vlog-socket.h"
61 #include "xtoxll.h"
62
63 #include "vlog.h"
64 #define THIS_MODULE VLM_controller
65
66 #define MAX_SWITCHES 16
67 #define MAX_TXQ 128
68
69 struct switch_ {
70     char *name;
71     struct vconn *vconn;
72
73     uint64_t datapath_id;
74     time_t last_features_request;
75
76     struct queue txq;
77 };
78
79 /* -H, --hub: Use dumb hub instead of learning switch? */
80 static bool hub = false;
81
82 /* -n, --noflow: Pass traffic, but don't setup flows in switch */
83 static bool noflow = false;
84
85 static void parse_options(int argc, char *argv[]);
86 static void usage(void) NO_RETURN;
87
88 static struct switch_ *connect_switch(const char *name);
89 static struct switch_ *new_switch(const char *name, struct vconn *);
90 static void close_switch(struct switch_ *);
91
92 static void queue_tx(struct switch_ *, struct buffer *);
93
94 static void send_features_request(struct switch_ *);
95
96 static int do_switch_recv(struct switch_ *this);
97 static int do_switch_send(struct switch_ *this);
98
99 static void process_packet(struct switch_ *, struct buffer *);
100 static void process_hub(struct switch_ *, struct ofp_packet_in *);
101 static void process_noflow(struct switch_ *, struct ofp_packet_in *);
102
103 static void switch_init(void);
104 static void process_switch(struct switch_ *, struct ofp_packet_in *);
105
106 int
107 main(int argc, char *argv[])
108 {
109     struct switch_ *switches[MAX_SWITCHES];
110     int n_switches;
111     int retval;
112     int i;
113
114     set_program_name(argv[0]);
115     register_fault_handlers();
116     vlog_init();
117     parse_options(argc, argv);
118
119     if (!hub && !noflow) {
120         switch_init();
121     }
122
123     if (argc - optind < 1) {
124         fatal(0, "at least one vconn argument required; use --help for usage");
125     }
126
127     retval = vlog_server_listen(NULL, NULL);
128     if (retval) {
129         fatal(retval, "Could not listen for vlog connections");
130     }
131
132     n_switches = 0;
133     for (i = 0; i < argc - optind; i++) {
134         struct switch_ *this = connect_switch(argv[optind + i]);
135         if (this) {
136             if (n_switches >= MAX_SWITCHES) {
137                 fatal(0, "max %d switch connections", n_switches);
138             }
139             switches[n_switches++] = this;
140         }
141     }
142     if (n_switches == 0) {
143         fatal(0, "could not connect to any switches");
144     }
145
146     while (n_switches > 0) {
147         /* Do some work.  Limit the number of iterations so that callbacks
148          * registered with the poll loop don't starve. */
149         int iteration;
150         int i;
151         for (iteration = 0; iteration < 50; iteration++) {
152             bool progress = false;
153             for (i = 0; i < n_switches; ) {
154                 struct switch_ *this = switches[i];
155                 int retval;
156
157                 if (vconn_is_passive(this->vconn)) {
158                     retval = 0;
159                     while (n_switches < MAX_SWITCHES) {
160                         struct vconn *new_vconn;
161                         retval = vconn_accept(this->vconn, &new_vconn);
162                         if (retval) {
163                             break;
164                         }
165                         printf("accept!\n");
166                         switches[n_switches++] = new_switch("tcp", new_vconn);
167                     }
168                 } else {
169                     retval = do_switch_recv(this);
170                     if (!retval || retval == EAGAIN) {
171                         do {
172                             retval = do_switch_send(this);
173                             if (!retval) {
174                                 progress = true;
175                             }
176                         } while (!retval);
177                     }
178                 }
179
180                 if (retval && retval != EAGAIN) {
181                     close_switch(this);
182                     switches[i] = switches[--n_switches];
183                 } else {
184                     i++;
185                 }
186             }
187             if (!progress) {
188                 break;
189             }
190         }
191
192         /* Wait for something to happen. */
193         for (i = 0; i < n_switches; i++) {
194             struct switch_ *this = switches[i];
195             if (vconn_is_passive(this->vconn)) {
196                 if (n_switches < MAX_SWITCHES) {
197                     vconn_accept_wait(this->vconn);
198                 }
199             } else {
200                 vconn_recv_wait(this->vconn);
201                 if (this->txq.n) {
202                     vconn_send_wait(this->vconn);
203                 }
204             }
205         }
206         poll_block();
207     }
208
209     return 0;
210 }
211
212 static int
213 do_switch_recv(struct switch_ *this) 
214 {
215     struct buffer *msg;
216     int retval;
217
218     retval = vconn_recv(this->vconn, &msg);
219     if (!retval) {
220         process_packet(this, msg);
221         buffer_delete(msg);
222     }
223     return retval;
224 }
225
226 static int
227 do_switch_send(struct switch_ *this) 
228 {
229     int retval = 0;
230     if (this->txq.n) {
231         struct buffer *next = this->txq.head->next;
232         retval = vconn_send(this->vconn, this->txq.head);
233         if (retval) {
234             return retval;
235         }
236         queue_advance_head(&this->txq, next);
237         return 0;
238     }
239     return EAGAIN;
240 }
241
242 struct switch_ *
243 connect_switch(const char *name) 
244 {
245     struct vconn *vconn;
246     int retval;
247
248     retval = vconn_open(name, &vconn);
249     if (retval) {
250         VLOG_ERR("%s: connect: %s", name, strerror(retval));
251         return NULL;
252     }
253
254     return new_switch(name, vconn);
255 }
256
257 static struct switch_ *
258 new_switch(const char *name, struct vconn *vconn) 
259 {
260     struct switch_ *this = xmalloc(sizeof *this);
261     memset(this, 0, sizeof *this);
262     this->name = xstrdup(name);
263     this->vconn = vconn;
264     queue_init(&this->txq);
265     this->last_features_request = 0;
266     if (!vconn_is_passive(vconn)) {
267         send_features_request(this);
268     }
269     return this;
270 }
271
272 static void
273 close_switch(struct switch_ *this) 
274 {
275     if (this) {
276         printf("dropped!\n");
277         free(this->name);
278         vconn_close(this->vconn);
279         queue_destroy(&this->txq);
280         free(this);
281     }
282 }
283
284 static void
285 send_features_request(struct switch_ *this)
286 {
287     time_t now = time(0);
288     if (now >= this->last_features_request + 1) {
289         struct buffer *b;
290         struct ofp_header *ofr;
291         struct ofp_switch_config *osc;
292
293         /* Send OFPT_SET_CONFIG. */
294         b = buffer_new(0);
295         osc = buffer_put_uninit(b, sizeof *osc);
296         memset(osc, 0, sizeof *osc);
297         osc->header.type = OFPT_SET_CONFIG;
298         osc->header.version = OFP_VERSION;
299         osc->header.length = htons(sizeof *osc);
300         osc->flags = htons(OFPC_SEND_FLOW_EXP);
301         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
302         queue_tx(this, b);
303
304         /* Send OFPT_FEATURES_REQUEST. */
305         b = buffer_new(0);
306         ofr = buffer_put_uninit(b, sizeof *ofr);
307         memset(ofr, 0, sizeof *ofr);
308         ofr->type = OFPT_FEATURES_REQUEST;
309         ofr->version = OFP_VERSION;
310         ofr->length = htons(sizeof *ofr);
311         queue_tx(this, b);
312
313         this->last_features_request = now;
314     }
315 }
316
317 static void
318 queue_tx(struct switch_ *this, struct buffer *b) 
319 {
320     queue_push_tail(&this->txq, b);
321 }
322
323 static void
324 process_packet(struct switch_ *sw, struct buffer *msg) 
325 {
326     static const size_t min_size[UINT8_MAX + 1] = {
327         [0 ... UINT8_MAX] = sizeof (struct ofp_header),
328         [OFPT_FEATURES_REPLY] = sizeof (struct ofp_switch_features),
329         [OFPT_PACKET_IN] = offsetof (struct ofp_packet_in, data),
330     };
331     struct ofp_header *oh;
332
333     oh = msg->data;
334     if (msg->size < min_size[oh->type]) {
335         VLOG_WARN("%s: too short (%zu bytes) for type %"PRIu8" (min %zu)",
336                   sw->name, msg->size, oh->type, min_size[oh->type]);
337         return;
338     }
339
340     if (oh->type == OFPT_FEATURES_REPLY) {
341         struct ofp_switch_features *osf = msg->data;
342         sw->datapath_id = osf->datapath_id;
343     } else if (sw->datapath_id == 0) {
344         send_features_request(sw);
345     } else if (oh->type == OFPT_PACKET_IN) {
346         struct ofp_packet_in *opi = msg->data;
347         if (sw->txq.n >= MAX_TXQ) {
348             /* FIXME: ratelimit. */
349             VLOG_WARN("%s: tx queue overflow", sw->name);
350         } else if (noflow) {
351             process_noflow(sw, opi);
352         } else if (hub) {
353             process_hub(sw, opi);
354         } else {
355             process_switch(sw, opi);
356         }
357     } else {
358         ofp_print(stdout, msg->data, msg->size, 2); 
359     }
360 }
361
362 static void
363 process_hub(struct switch_ *sw, struct ofp_packet_in *opi)
364 {
365     size_t pkt_ofs, pkt_len;
366     struct buffer pkt;
367     struct flow flow;
368
369     /* Extract flow data from 'opi' into 'flow'. */
370     pkt_ofs = offsetof(struct ofp_packet_in, data);
371     pkt_len = ntohs(opi->header.length) - pkt_ofs;
372     pkt.data = opi->data;
373     pkt.size = pkt_len;
374     flow_extract(&pkt, ntohs(opi->in_port), &flow);
375
376     /* Add new flow. */
377     queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
378                                       OFPP_FLOOD));
379
380     /* If the switch didn't buffer the packet, we need to send a copy. */
381     if (ntohl(opi->buffer_id) == UINT32_MAX) {
382         queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(flow.in_port),
383                                                 OFPP_FLOOD));
384     }
385 }
386
387 static void
388 process_noflow(struct switch_ *sw, struct ofp_packet_in *opi)
389 {
390     /* If the switch didn't buffer the packet, we need to send a copy. */
391     if (ntohl(opi->buffer_id) == UINT32_MAX) {
392         size_t pkt_ofs, pkt_len;
393         struct buffer pkt;
394
395         /* Extract flow data from 'opi' into 'flow'. */
396         pkt_ofs = offsetof(struct ofp_packet_in, data);
397         pkt_len = ntohs(opi->header.length) - pkt_ofs;
398         pkt.data = opi->data;
399         pkt.size = pkt_len;
400
401         queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(opi->in_port),
402                     OFPP_FLOOD));
403     } else {
404         queue_tx(sw, make_buffered_packet_out(ntohl(opi->buffer_id), 
405                     ntohs(opi->in_port), OFPP_FLOOD));
406     }
407 }
408
409
410 #define MAC_HASH_BITS 10
411 #define MAC_HASH_MASK (MAC_HASH_SIZE - 1)
412 #define MAC_HASH_SIZE (1u << MAC_HASH_BITS)
413
414 #define MAC_MAX 1024
415
416 struct mac_source {
417     struct list hash_list;
418     struct list lru_list;
419     uint64_t datapath_id;
420     uint8_t mac[ETH_ADDR_LEN];
421     uint16_t port;
422 };
423
424 static struct list mac_table[MAC_HASH_SIZE];
425 static struct list lrus;
426 static size_t mac_count;
427
428 static void
429 switch_init(void)
430 {
431     int i;
432
433     list_init(&lrus);
434     for (i = 0; i < MAC_HASH_SIZE; i++) {
435         list_init(&mac_table[i]);
436     }
437 }
438
439 static struct list *
440 mac_table_bucket(uint64_t datapath_id, const uint8_t mac[ETH_ADDR_LEN]) 
441 {
442     uint32_t hash;
443     hash = hash_fnv(&datapath_id, sizeof datapath_id, HASH_FNV_BASIS);
444     hash = hash_fnv(mac, ETH_ADDR_LEN, hash);
445     return &mac_table[hash & MAC_HASH_BITS];
446 }
447
448 static void
449 process_switch(struct switch_ *sw, struct ofp_packet_in *opi)
450 {
451     size_t pkt_ofs, pkt_len;
452     struct buffer pkt;
453     struct flow flow;
454
455     uint16_t out_port;
456
457     /* Extract flow data from 'opi' into 'flow'. */
458     pkt_ofs = offsetof(struct ofp_packet_in, data);
459     pkt_len = ntohs(opi->header.length) - pkt_ofs;
460     pkt.data = opi->data;
461     pkt.size = pkt_len;
462     flow_extract(&pkt, ntohs(opi->in_port), &flow);
463
464     /* Learn the source. */
465     if (!eth_addr_is_multicast(flow.dl_src)) {
466         struct mac_source *src;
467         struct list *bucket;
468         bool found;
469
470         bucket = mac_table_bucket(sw->datapath_id, flow.dl_src);
471         found = false;
472         LIST_FOR_EACH (src, struct mac_source, hash_list, bucket) {
473             if (src->datapath_id == sw->datapath_id
474                 && eth_addr_equals(src->mac, flow.dl_src)) {
475                 found = true;
476                 break;
477             }
478         }
479
480         if (!found) {
481             /* Learn a new address. */
482
483             if (mac_count >= MAC_MAX) {
484                 /* Drop the least recently used mac source. */
485                 struct mac_source *lru;
486                 lru = CONTAINER_OF(lrus.next, struct mac_source, lru_list);
487                 list_remove(&lru->hash_list);
488                 list_remove(&lru->lru_list);
489                 free(lru);
490             } else {
491                 mac_count++;
492             }
493
494             /* Create new mac source */
495             src = xmalloc(sizeof *src);
496             src->datapath_id = sw->datapath_id;
497             memcpy(src->mac, flow.dl_src, ETH_ADDR_LEN);
498             src->port = -1;
499             list_push_front(bucket, &src->hash_list);
500             list_push_back(&lrus, &src->lru_list);
501         } else {
502             /* Make 'src' most-recently-used.  */
503             list_remove(&src->lru_list);
504             list_push_back(&lrus, &src->lru_list);
505         }
506
507         if (ntohs(flow.in_port) != src->port) {
508             src->port = ntohs(flow.in_port);
509             VLOG_DBG("learned that "ETH_ADDR_FMT" is on datapath %"
510                      PRIx64" port %d",
511                      ETH_ADDR_ARGS(src->mac), ntohll(src->datapath_id),
512                      src->port);
513         }
514     } else {
515         VLOG_DBG("multicast packet source "ETH_ADDR_FMT,
516                  ETH_ADDR_ARGS(flow.dl_src));
517     }
518
519     /* Figure out the destination. */
520     out_port = OFPP_FLOOD;
521     if (!eth_addr_is_multicast(flow.dl_dst)) {
522         struct mac_source *dst;
523         struct list *bucket;
524
525         bucket = mac_table_bucket(sw->datapath_id, flow.dl_dst);
526         LIST_FOR_EACH (dst, struct mac_source, hash_list, bucket) {
527             if (dst->datapath_id == sw->datapath_id
528                 && eth_addr_equals(dst->mac, flow.dl_dst)) {
529                 out_port = dst->port;
530                 break;
531             }
532         }
533     }
534
535     if (out_port != OFPP_FLOOD) {
536         /* The output port is known, so add a new flow. */
537         queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id), 
538                     out_port));
539
540         /* If the switch didn't buffer the packet, we need to send a copy. */
541         if (ntohl(opi->buffer_id) == UINT32_MAX) {
542             queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(flow.in_port),
543                                                     out_port));
544         }
545     } else {
546         /* We don't know that MAC.  Flood the packet. */
547         struct buffer *b;
548         if (ntohl(opi->buffer_id) == UINT32_MAX) {
549             b = make_unbuffered_packet_out(&pkt, ntohs(flow.in_port), out_port);
550         } else {
551             b = make_buffered_packet_out(ntohl(opi->buffer_id), 
552                         ntohs(flow.in_port), out_port);
553         }
554         queue_tx(sw, b);
555     }
556 }
557
558 static void
559 parse_options(int argc, char *argv[])
560 {
561     static struct option long_options[] = {
562         {"hub",         no_argument, 0, 'H'},
563         {"noflow",      no_argument, 0, 'n'},
564         {"verbose",     optional_argument, 0, 'v'},
565         {"help",        no_argument, 0, 'h'},
566         {"version",     no_argument, 0, 'V'},
567         VCONN_SSL_LONG_OPTIONS
568         {0, 0, 0, 0},
569     };
570     char *short_options = long_options_to_short_options(long_options);
571
572     for (;;) {
573         int indexptr;
574         int c;
575
576         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
577         if (c == -1) {
578             break;
579         }
580
581         switch (c) {
582         case 'H':
583             hub = true;
584             break;
585
586         case 'n':
587             noflow = true;
588             break;
589
590         case 'h':
591             usage();
592
593         case 'V':
594             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
595             exit(EXIT_SUCCESS);
596
597         case 'v':
598             vlog_set_verbosity(optarg);
599             break;
600
601         VCONN_SSL_OPTION_HANDLERS
602
603         case '?':
604             exit(EXIT_FAILURE);
605
606         default:
607             abort();
608         }
609     }
610     free(short_options);
611 }
612
613 static void
614 usage(void)
615 {
616     printf("%s: OpenFlow controller\n"
617            "usage: %s [OPTIONS] METHOD\n"
618            "where METHOD is any OpenFlow connection method.\n",
619            program_name, program_name);
620     vconn_usage(true, true);
621     printf("\nOther options:\n"
622            "  -H, --hub               act as hub instead of learning switch\n"
623            "  -n, --noflow            pass traffic, but don't add flows\n"
624            "  -v, --verbose           set maximum verbosity level\n"
625            "  -h, --help              display this help message\n"
626            "  -V, --version           display version information\n");
627     exit(EXIT_SUCCESS);
628 }