Merge "citrix" branch into "master".
[cascardo/ovs.git] / lib / vconn.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "vconn-provider.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <netinet/in.h>
23 #include <poll.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include "coverage.h"
27 #include "dynamic-string.h"
28 #include "flow.h"
29 #include "ofp-print.h"
30 #include "ofpbuf.h"
31 #include "openflow/nicira-ext.h"
32 #include "openflow/openflow.h"
33 #include "packets.h"
34 #include "poll-loop.h"
35 #include "random.h"
36 #include "util.h"
37
38 #define THIS_MODULE VLM_vconn
39 #include "vlog.h"
40
41 /* State of an active vconn.*/
42 enum vconn_state {
43     /* This is the ordinary progression of states. */
44     VCS_CONNECTING,             /* Underlying vconn is not connected. */
45     VCS_SEND_HELLO,             /* Waiting to send OFPT_HELLO message. */
46     VCS_RECV_HELLO,             /* Waiting to receive OFPT_HELLO message. */
47     VCS_CONNECTED,              /* Connection established. */
48
49     /* These states are entered only when something goes wrong. */
50     VCS_SEND_ERROR,             /* Sending OFPT_ERROR message. */
51     VCS_DISCONNECTED            /* Connection failed or connection closed. */
52 };
53
54 static struct vconn_class *vconn_classes[] = {
55     &tcp_vconn_class,
56     &unix_vconn_class,
57 #ifdef HAVE_OPENSSL
58     &ssl_vconn_class,
59 #endif
60 };
61
62 static struct pvconn_class *pvconn_classes[] = {
63     &ptcp_pvconn_class,
64     &punix_pvconn_class,
65 #ifdef HAVE_OPENSSL
66     &pssl_pvconn_class,
67 #endif
68 };
69
70 /* Rate limit for individual OpenFlow messages going over the vconn, output at
71  * DBG level.  This is very high because, if these are enabled, it is because
72  * we really need to see them. */
73 static struct vlog_rate_limit ofmsg_rl = VLOG_RATE_LIMIT_INIT(600, 600);
74
75 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
76  * in the peer and so there's not much point in showing a lot of them. */
77 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
78
79 static int do_recv(struct vconn *, struct ofpbuf **);
80 static int do_send(struct vconn *, struct ofpbuf *);
81
82 /* Check the validity of the vconn class structures. */
83 static void
84 check_vconn_classes(void)
85 {
86 #ifndef NDEBUG
87     size_t i;
88
89     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
90         struct vconn_class *class = vconn_classes[i];
91         assert(class->name != NULL);
92         assert(class->open != NULL);
93         if (class->close || class->recv || class->send
94             || class->run || class->run_wait || class->wait) {
95             assert(class->close != NULL);
96             assert(class->recv != NULL);
97             assert(class->send != NULL);
98             assert(class->wait != NULL);
99         } else {
100             /* This class delegates to another one. */
101         }
102     }
103
104     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
105         struct pvconn_class *class = pvconn_classes[i];
106         assert(class->name != NULL);
107         assert(class->listen != NULL);
108         if (class->close || class->accept || class->wait) {
109             assert(class->close != NULL);
110             assert(class->accept != NULL);
111             assert(class->wait != NULL);
112         } else {
113             /* This class delegates to another one. */
114         }
115     }
116 #endif
117 }
118
119 /* Prints information on active (if 'active') and passive (if 'passive')
120  * connection methods supported by the vconn.  If 'bootstrap' is true, also
121  * advertises options to bootstrap the CA certificate. */
122 void
123 vconn_usage(bool active, bool passive, bool bootstrap OVS_UNUSED)
124 {
125     /* Really this should be implemented via callbacks into the vconn
126      * providers, but that seems too heavy-weight to bother with at the
127      * moment. */
128     
129     printf("\n");
130     if (active) {
131         printf("Active OpenFlow connection methods:\n");
132         printf("  tcp:IP[:PORT]         "
133                "PORT (default: %d) at remote IP\n", OFP_TCP_PORT);
134 #ifdef HAVE_OPENSSL
135         printf("  ssl:IP[:PORT]         "
136                "SSL PORT (default: %d) at remote IP\n", OFP_SSL_PORT);
137 #endif
138         printf("  unix:FILE               Unix domain socket named FILE\n");
139     }
140
141     if (passive) {
142         printf("Passive OpenFlow connection methods:\n");
143         printf("  ptcp:[PORT][:IP]        "
144                "listen to TCP PORT (default: %d) on IP\n",
145                OFP_TCP_PORT);
146 #ifdef HAVE_OPENSSL
147         printf("  pssl:[PORT][:IP]        "
148                "listen for SSL on PORT (default: %d) on IP\n",
149                OFP_SSL_PORT);
150 #endif
151         printf("  punix:FILE              "
152                "listen on Unix domain socket FILE\n");
153     }
154
155 #ifdef HAVE_OPENSSL
156     printf("PKI configuration (required to use SSL):\n"
157            "  -p, --private-key=FILE  file with private key\n"
158            "  -c, --certificate=FILE  file with certificate for private key\n"
159            "  -C, --ca-cert=FILE      file with peer CA certificate\n");
160     if (bootstrap) {
161         printf("  --bootstrap-ca-cert=FILE  file with peer CA certificate "
162                "to read or create\n");
163     }
164 #endif
165 }
166
167 /* Given 'name', a connection name in the form "TYPE:ARGS", stores the class
168  * named "TYPE" into '*classp' and returns 0.  Returns EAFNOSUPPORT and stores
169  * a null pointer into '*classp' if 'name' is in the wrong form or if no such
170  * class exists. */
171 static int
172 vconn_lookup_class(const char *name, struct vconn_class **classp)
173 {
174     size_t prefix_len;
175
176     prefix_len = strcspn(name, ":");
177     if (name[prefix_len] != '\0') {
178         size_t i;
179
180         for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
181             struct vconn_class *class = vconn_classes[i];
182             if (strlen(class->name) == prefix_len
183                 && !memcmp(class->name, name, prefix_len)) {
184                 *classp = class;
185                 return 0;
186             }
187         }
188     }
189
190     *classp = NULL;
191     return EAFNOSUPPORT;
192 }
193
194 /* Returns 0 if 'name' is a connection name in the form "TYPE:ARGS" and TYPE is
195  * a supported connection type, otherwise EAFNOSUPPORT.  */
196 int
197 vconn_verify_name(const char *name)
198 {
199     struct vconn_class *class;
200     return vconn_lookup_class(name, &class);
201 }
202
203 /* Attempts to connect to an OpenFlow device.  'name' is a connection name in
204  * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
205  * are vconn class-specific.
206  *
207  * The vconn will automatically negotiate an OpenFlow protocol version
208  * acceptable to both peers on the connection.  The version negotiated will be
209  * no lower than 'min_version' and no higher than OFP_VERSION.
210  *
211  * Returns 0 if successful, otherwise a positive errno value.  If successful,
212  * stores a pointer to the new connection in '*vconnp', otherwise a null
213  * pointer.  */
214 int
215 vconn_open(const char *name, int min_version, struct vconn **vconnp)
216 {
217     struct vconn_class *class;
218     struct vconn *vconn;
219     char *suffix_copy;
220     int error;
221
222     COVERAGE_INC(vconn_open);
223     check_vconn_classes();
224
225     /* Look up the class. */
226     error = vconn_lookup_class(name, &class);
227     if (!class) {
228         goto error;
229     }
230
231     /* Call class's "open" function. */
232     suffix_copy = xstrdup(strchr(name, ':') + 1);
233     error = class->open(name, suffix_copy, &vconn);
234     free(suffix_copy);
235     if (error) {
236         goto error;
237     }
238
239     /* Success. */
240     assert(vconn->state != VCS_CONNECTING || vconn->class->connect);
241     vconn->min_version = min_version;
242     *vconnp = vconn;
243     return 0;
244
245 error:
246     *vconnp = NULL;
247     return error;
248 }
249
250 /* Allows 'vconn' to perform maintenance activities, such as flushing output
251  * buffers. */
252 void
253 vconn_run(struct vconn *vconn)
254 {
255     if (vconn->class->run) {
256         (vconn->class->run)(vconn);
257     }
258 }
259
260 /* Arranges for the poll loop to wake up when 'vconn' needs to perform
261  * maintenance activities. */
262 void
263 vconn_run_wait(struct vconn *vconn)
264 {
265     if (vconn->class->run_wait) {
266         (vconn->class->run_wait)(vconn);
267     }
268 }
269
270 int
271 vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
272 {
273     struct vconn *vconn;
274     int error;
275
276     error = vconn_open(name, min_version, &vconn);
277     while (error == EAGAIN) {
278         vconn_run(vconn);
279         vconn_run_wait(vconn);
280         vconn_connect_wait(vconn);
281         poll_block();
282         error = vconn_connect(vconn);
283         assert(error != EINPROGRESS);
284     }
285     if (error) {
286         vconn_close(vconn);
287         *vconnp = NULL;
288     } else {
289         *vconnp = vconn;
290     }
291     return error;
292 }
293
294 /* Closes 'vconn'. */
295 void
296 vconn_close(struct vconn *vconn)
297 {
298     if (vconn != NULL) {
299         char *name = vconn->name;
300         (vconn->class->close)(vconn);
301         free(name);
302     }
303 }
304
305 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
306 const char *
307 vconn_get_name(const struct vconn *vconn)
308 {
309     return vconn->name;
310 }
311
312 /* Returns the IP address of the peer, or 0 if the peer is not connected over
313  * an IP-based protocol or if its IP address is not yet known. */
314 uint32_t
315 vconn_get_remote_ip(const struct vconn *vconn) 
316 {
317     return vconn->remote_ip;
318 }
319
320 /* Returns the transport port of the peer, or 0 if the connection does not 
321  * contain a port or if the port is not yet known. */
322 uint16_t
323 vconn_get_remote_port(const struct vconn *vconn) 
324 {
325     return vconn->remote_port;
326 }
327
328 /* Returns the IP address used to connect to the peer, or 0 if the 
329  * connection is not an IP-based protocol or if its IP address is not 
330  * yet known. */
331 uint32_t
332 vconn_get_local_ip(const struct vconn *vconn) 
333 {
334     return vconn->local_ip;
335 }
336
337 /* Returns the transport port used to connect to the peer, or 0 if the 
338  * connection does not contain a port or if the port is not yet known. */
339 uint16_t
340 vconn_get_local_port(const struct vconn *vconn) 
341 {
342     return vconn->local_port;
343 }
344
345 static void
346 vcs_connecting(struct vconn *vconn) 
347 {
348     int retval = (vconn->class->connect)(vconn);
349     assert(retval != EINPROGRESS);
350     if (!retval) {
351         vconn->state = VCS_SEND_HELLO;
352     } else if (retval != EAGAIN) {
353         vconn->state = VCS_DISCONNECTED;
354         vconn->error = retval;
355     }
356 }
357
358 static void
359 vcs_send_hello(struct vconn *vconn)
360 {
361     struct ofpbuf *b;
362     int retval;
363
364     make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
365     retval = do_send(vconn, b);
366     if (!retval) {
367         vconn->state = VCS_RECV_HELLO;
368     } else {
369         ofpbuf_delete(b);
370         if (retval != EAGAIN) {
371             vconn->state = VCS_DISCONNECTED;
372             vconn->error = retval;
373         }
374     }
375 }
376
377 static void
378 vcs_recv_hello(struct vconn *vconn)
379 {
380     struct ofpbuf *b;
381     int retval;
382
383     retval = do_recv(vconn, &b);
384     if (!retval) {
385         struct ofp_header *oh = b->data;
386
387         if (oh->type == OFPT_HELLO) {
388             if (b->size > sizeof *oh) {
389                 struct ds msg = DS_EMPTY_INITIALIZER;
390                 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
391                 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
392                 VLOG_WARN_RL(&bad_ofmsg_rl, "%s", ds_cstr(&msg));
393                 ds_destroy(&msg);
394             }
395
396             vconn->version = MIN(OFP_VERSION, oh->version);
397             if (vconn->version < vconn->min_version) {
398                 VLOG_WARN_RL(&bad_ofmsg_rl,
399                              "%s: version negotiation failed: we support "
400                              "versions 0x%02x to 0x%02x inclusive but peer "
401                              "supports no later than version 0x%02"PRIx8,
402                              vconn->name, vconn->min_version, OFP_VERSION,
403                              oh->version);
404                 vconn->state = VCS_SEND_ERROR;
405             } else {
406                 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
407                          "(we support versions 0x%02x to 0x%02x inclusive, "
408                          "peer no later than version 0x%02"PRIx8")",
409                          vconn->name, vconn->version, vconn->min_version,
410                          OFP_VERSION, oh->version);
411                 vconn->state = VCS_CONNECTED;
412             }
413             ofpbuf_delete(b);
414             return;
415         } else {
416             char *s = ofp_to_string(b->data, b->size, 1);
417             VLOG_WARN_RL(&bad_ofmsg_rl,
418                          "%s: received message while expecting hello: %s",
419                          vconn->name, s);
420             free(s);
421             retval = EPROTO;
422             ofpbuf_delete(b);
423         }
424     }
425
426     if (retval != EAGAIN) {
427         vconn->state = VCS_DISCONNECTED;
428         vconn->error = retval == EOF ? ECONNRESET : retval;
429     }
430 }
431
432 static void
433 vcs_send_error(struct vconn *vconn)
434 {
435     struct ofp_error_msg *error;
436     struct ofpbuf *b;
437     char s[128];
438     int retval;
439
440     snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
441              "you support no later than version 0x%02"PRIx8".",
442              vconn->min_version, OFP_VERSION, vconn->version);
443     error = make_openflow(sizeof *error, OFPT_ERROR, &b);
444     error->type = htons(OFPET_HELLO_FAILED);
445     error->code = htons(OFPHFC_INCOMPATIBLE);
446     ofpbuf_put(b, s, strlen(s));
447     update_openflow_length(b);
448     retval = do_send(vconn, b);
449     if (retval) {
450         ofpbuf_delete(b);
451     }
452     if (retval != EAGAIN) {
453         vconn->state = VCS_DISCONNECTED;
454         vconn->error = retval ? retval : EPROTO;
455     }
456 }
457
458 /* Tries to complete the connection on 'vconn', which must be an active
459  * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
460  * was successful or a positive errno value if it failed.  If the
461  * connection is still in progress, returns EAGAIN. */
462 int
463 vconn_connect(struct vconn *vconn)
464 {
465     enum vconn_state last_state;
466
467     assert(vconn->min_version >= 0);
468     do {
469         last_state = vconn->state;
470         switch (vconn->state) {
471         case VCS_CONNECTING:
472             vcs_connecting(vconn);
473             break;
474
475         case VCS_SEND_HELLO:
476             vcs_send_hello(vconn);
477             break;
478
479         case VCS_RECV_HELLO:
480             vcs_recv_hello(vconn);
481             break;
482
483         case VCS_CONNECTED:
484             return 0;
485
486         case VCS_SEND_ERROR:
487             vcs_send_error(vconn);
488             break;
489
490         case VCS_DISCONNECTED:
491             return vconn->error;
492
493         default:
494             NOT_REACHED();
495         }
496     } while (vconn->state != last_state);
497
498     return EAGAIN;
499 }
500
501 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
502  * vconn.  If successful, stores the received message into '*msgp' and returns
503  * 0.  The caller is responsible for destroying the message with
504  * ofpbuf_delete().  On failure, returns a positive errno value and stores a
505  * null pointer into '*msgp'.  On normal connection close, returns EOF.
506  *
507  * vconn_recv will not block waiting for a packet to arrive.  If no packets
508  * have been received, it returns EAGAIN immediately. */
509 int
510 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
511 {
512     int retval = vconn_connect(vconn);
513     if (!retval) {
514         retval = do_recv(vconn, msgp);
515     }
516     return retval;
517 }
518
519 static int
520 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
521 {
522     int retval = (vconn->class->recv)(vconn, msgp);
523     if (!retval) {
524         struct ofp_header *oh;
525
526         COVERAGE_INC(vconn_received);
527         if (VLOG_IS_DBG_ENABLED()) {
528             char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
529             VLOG_DBG_RL(&ofmsg_rl, "%s: received: %s", vconn->name, s);
530             free(s);
531         }
532
533         oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
534         if (oh->version != vconn->version
535             && oh->type != OFPT_HELLO
536             && oh->type != OFPT_ERROR
537             && oh->type != OFPT_ECHO_REQUEST
538             && oh->type != OFPT_ECHO_REPLY
539             && oh->type != OFPT_VENDOR)
540         {
541             if (vconn->version < 0) {
542                 VLOG_ERR_RL(&bad_ofmsg_rl,
543                             "%s: received OpenFlow message type %"PRIu8" "
544                             "before version negotiation complete",
545                             vconn->name, oh->type);
546             } else {
547                 VLOG_ERR_RL(&bad_ofmsg_rl,
548                             "%s: received OpenFlow version 0x%02"PRIx8" "
549                             "!= expected %02x",
550                             vconn->name, oh->version, vconn->version);
551             }
552             ofpbuf_delete(*msgp);
553             retval = EPROTO;
554         }
555     }
556     if (retval) {
557         *msgp = NULL;
558     }
559     return retval;
560 }
561
562 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
563  * vconn.  If successful, returns 0, in which case ownership of 'msg' is
564  * transferred to the vconn.  Success does not guarantee that 'msg' has been or
565  * ever will be delivered to the peer, only that it has been queued for
566  * transmission.
567  *
568  * Returns a positive errno value on failure, in which case the caller
569  * retains ownership of 'msg'.
570  *
571  * vconn_send will not block.  If 'msg' cannot be immediately accepted for
572  * transmission, it returns EAGAIN immediately. */
573 int
574 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
575 {
576     int retval = vconn_connect(vconn);
577     if (!retval) {
578         retval = do_send(vconn, msg);
579     }
580     return retval;
581 }
582
583 static int
584 do_send(struct vconn *vconn, struct ofpbuf *msg)
585 {
586     int retval;
587
588     assert(msg->size >= sizeof(struct ofp_header));
589     assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
590     if (!VLOG_IS_DBG_ENABLED()) {
591         COVERAGE_INC(vconn_sent);
592         retval = (vconn->class->send)(vconn, msg);
593     } else {
594         char *s = ofp_to_string(msg->data, msg->size, 1);
595         retval = (vconn->class->send)(vconn, msg);
596         if (retval != EAGAIN) {
597             VLOG_DBG_RL(&ofmsg_rl, "%s: sent (%s): %s",
598                         vconn->name, strerror(retval), s);
599         }
600         free(s);
601     }
602     return retval;
603 }
604
605 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
606 int
607 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
608 {
609     int retval;
610     while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
611         vconn_run(vconn);
612         vconn_run_wait(vconn);
613         vconn_send_wait(vconn);
614         poll_block();
615     }
616     return retval;
617 }
618
619 /* Same as vconn_recv, except that it waits until a message is received. */
620 int
621 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
622 {
623     int retval;
624     while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
625         vconn_run(vconn);
626         vconn_run_wait(vconn);
627         vconn_recv_wait(vconn);
628         poll_block();
629     }
630     return retval;
631 }
632
633 /* Waits until a message with a transaction ID matching 'xid' is recived on
634  * 'vconn'.  Returns 0 if successful, in which case the reply is stored in
635  * '*replyp' for the caller to examine and free.  Otherwise returns a positive
636  * errno value, or EOF, and sets '*replyp' to null.
637  *
638  * 'request' is always destroyed, regardless of the return value. */
639 int
640 vconn_recv_xid(struct vconn *vconn, uint32_t xid, struct ofpbuf **replyp)
641 {
642     for (;;) {
643         uint32_t recv_xid;
644         struct ofpbuf *reply;
645         int error;
646
647         error = vconn_recv_block(vconn, &reply);
648         if (error) {
649             *replyp = NULL;
650             return error;
651         }
652         recv_xid = ((struct ofp_header *) reply->data)->xid;
653         if (xid == recv_xid) {
654             *replyp = reply;
655             return 0;
656         }
657
658         VLOG_DBG_RL(&bad_ofmsg_rl, "%s: received reply with xid %08"PRIx32
659                     " != expected %08"PRIx32, vconn->name, recv_xid, xid);
660         ofpbuf_delete(reply);
661     }
662 }
663
664 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
665  * matching transaction ID.  Returns 0 if successful, in which case the reply
666  * is stored in '*replyp' for the caller to examine and free.  Otherwise
667  * returns a positive errno value, or EOF, and sets '*replyp' to null.
668  *
669  * 'request' is always destroyed, regardless of the return value. */
670 int
671 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
672                struct ofpbuf **replyp)
673 {
674     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
675     int error;
676
677     *replyp = NULL;
678     error = vconn_send_block(vconn, request);
679     if (error) {
680         ofpbuf_delete(request);
681     }
682     return error ? error : vconn_recv_xid(vconn, send_xid, replyp);
683 }
684
685 void
686 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
687 {
688     assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
689
690     switch (vconn->state) {
691     case VCS_CONNECTING:
692         wait = WAIT_CONNECT;
693         break;
694
695     case VCS_SEND_HELLO:
696     case VCS_SEND_ERROR:
697         wait = WAIT_SEND;
698         break;
699
700     case VCS_RECV_HELLO:
701         wait = WAIT_RECV;
702         break;
703
704     case VCS_CONNECTED:
705         break;
706
707     case VCS_DISCONNECTED:
708         poll_immediate_wake();
709         return;
710     }
711     (vconn->class->wait)(vconn, wait);
712 }
713
714 void
715 vconn_connect_wait(struct vconn *vconn)
716 {
717     vconn_wait(vconn, WAIT_CONNECT);
718 }
719
720 void
721 vconn_recv_wait(struct vconn *vconn)
722 {
723     vconn_wait(vconn, WAIT_RECV);
724 }
725
726 void
727 vconn_send_wait(struct vconn *vconn)
728 {
729     vconn_wait(vconn, WAIT_SEND);
730 }
731
732 /* Given 'name', a connection name in the form "TYPE:ARGS", stores the class
733  * named "TYPE" into '*classp' and returns 0.  Returns EAFNOSUPPORT and stores
734  * a null pointer into '*classp' if 'name' is in the wrong form or if no such
735  * class exists. */
736 static int
737 pvconn_lookup_class(const char *name, struct pvconn_class **classp)
738 {
739     size_t prefix_len;
740
741     prefix_len = strcspn(name, ":");
742     if (name[prefix_len] != '\0') {
743         size_t i;
744
745         for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
746             struct pvconn_class *class = pvconn_classes[i];
747             if (strlen(class->name) == prefix_len
748                 && !memcmp(class->name, name, prefix_len)) {
749                 *classp = class;
750                 return 0;
751             }
752         }
753     }
754
755     *classp = NULL;
756     return EAFNOSUPPORT;
757 }
758
759 /* Returns 0 if 'name' is a connection name in the form "TYPE:ARGS" and TYPE is
760  * a supported connection type, otherwise EAFNOSUPPORT.  */
761 int
762 pvconn_verify_name(const char *name)
763 {
764     struct pvconn_class *class;
765     return pvconn_lookup_class(name, &class);
766 }
767
768 /* Attempts to start listening for OpenFlow connections.  'name' is a
769  * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
770  * class's name and ARGS are vconn class-specific.
771  *
772  * Returns 0 if successful, otherwise a positive errno value.  If successful,
773  * stores a pointer to the new connection in '*pvconnp', otherwise a null
774  * pointer.  */
775 int
776 pvconn_open(const char *name, struct pvconn **pvconnp)
777 {
778     struct pvconn_class *class;
779     struct pvconn *pvconn;
780     char *suffix_copy;
781     int error;
782
783     check_vconn_classes();
784
785     /* Look up the class. */
786     error = pvconn_lookup_class(name, &class);
787     if (!class) {
788         goto error;
789     }
790
791     /* Call class's "open" function. */
792     suffix_copy = xstrdup(strchr(name, ':') + 1);
793     error = class->listen(name, suffix_copy, &pvconn);
794     free(suffix_copy);
795     if (error) {
796         goto error;
797     }
798
799     /* Success. */
800     *pvconnp = pvconn;
801     return 0;
802
803 error:
804     *pvconnp = NULL;
805     return error;
806 }
807
808 /* Returns the name that was used to open 'pvconn'.  The caller must not
809  * modify or free the name. */
810 const char *
811 pvconn_get_name(const struct pvconn *pvconn)
812 {
813     return pvconn->name;
814 }
815
816 /* Closes 'pvconn'. */
817 void
818 pvconn_close(struct pvconn *pvconn)
819 {
820     if (pvconn != NULL) {
821         char *name = pvconn->name;
822         (pvconn->class->close)(pvconn);
823         free(name);
824     }
825 }
826
827 /* Tries to accept a new connection on 'pvconn'.  If successful, stores the new
828  * connection in '*new_vconn' and returns 0.  Otherwise, returns a positive
829  * errno value.
830  *
831  * The new vconn will automatically negotiate an OpenFlow protocol version
832  * acceptable to both peers on the connection.  The version negotiated will be
833  * no lower than 'min_version' and no higher than OFP_VERSION.
834  *
835  * pvconn_accept() will not block waiting for a connection.  If no connection
836  * is ready to be accepted, it returns EAGAIN immediately. */
837 int
838 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
839 {
840     int retval = (pvconn->class->accept)(pvconn, new_vconn);
841     if (retval) {
842         *new_vconn = NULL;
843     } else {
844         assert((*new_vconn)->state != VCS_CONNECTING
845                || (*new_vconn)->class->connect);
846         (*new_vconn)->min_version = min_version;
847     }
848     return retval;
849 }
850
851 void
852 pvconn_wait(struct pvconn *pvconn)
853 {
854     (pvconn->class->wait)(pvconn);
855 }
856
857 /* XXX we should really use consecutive xids to avoid probabilistic
858  * failures. */
859 static inline uint32_t
860 alloc_xid(void)
861 {
862     return random_uint32();
863 }
864
865 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
866  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
867  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
868  * zeroed.
869  *
870  * The caller is responsible for freeing '*bufferp' when it is no longer
871  * needed.
872  *
873  * The OpenFlow header length is initially set to 'openflow_len'; if the
874  * message is later extended, the length should be updated with
875  * update_openflow_length() before sending.
876  *
877  * Returns the header. */
878 void *
879 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
880 {
881     *bufferp = ofpbuf_new(openflow_len);
882     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
883 }
884
885 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
886  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
887  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
888  * zeroed.
889  *
890  * The caller is responsible for freeing '*bufferp' when it is no longer
891  * needed.
892  *
893  * The OpenFlow header length is initially set to 'openflow_len'; if the
894  * message is later extended, the length should be updated with
895  * update_openflow_length() before sending.
896  *
897  * Returns the header. */
898 void *
899 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
900                   struct ofpbuf **bufferp)
901 {
902     *bufferp = ofpbuf_new(openflow_len);
903     return put_openflow_xid(openflow_len, type, xid, *bufferp);
904 }
905
906 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
907  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
908  * beyond the header, if any, are zeroed.
909  *
910  * The OpenFlow header length is initially set to 'openflow_len'; if the
911  * message is later extended, the length should be updated with
912  * update_openflow_length() before sending.
913  *
914  * Returns the header. */
915 void *
916 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
917 {
918     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
919 }
920
921 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
922  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
923  * the header, if any, are zeroed.
924  *
925  * The OpenFlow header length is initially set to 'openflow_len'; if the
926  * message is later extended, the length should be updated with
927  * update_openflow_length() before sending.
928  *
929  * Returns the header. */
930 void *
931 put_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
932                  struct ofpbuf *buffer)
933 {
934     struct ofp_header *oh;
935
936     assert(openflow_len >= sizeof *oh);
937     assert(openflow_len <= UINT16_MAX);
938
939     oh = ofpbuf_put_uninit(buffer, openflow_len);
940     oh->version = OFP_VERSION;
941     oh->type = type;
942     oh->length = htons(openflow_len);
943     oh->xid = xid;
944     memset(oh + 1, 0, openflow_len - sizeof *oh);
945     return oh;
946 }
947
948 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
949  * 'buffer->size'. */
950 void
951 update_openflow_length(struct ofpbuf *buffer) 
952 {
953     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
954     oh->length = htons(buffer->size); 
955 }
956
957 struct ofpbuf *
958 make_flow_mod(uint16_t command, const flow_t *flow, size_t actions_len)
959 {
960     struct ofp_flow_mod *ofm;
961     size_t size = sizeof *ofm + actions_len;
962     struct ofpbuf *out = ofpbuf_new(size);
963     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
964     ofm->header.version = OFP_VERSION;
965     ofm->header.type = OFPT_FLOW_MOD;
966     ofm->header.length = htons(size);
967     ofm->cookie = 0;
968     ofm->match.wildcards = htonl(0);
969     ofm->match.in_port = htons(flow->in_port == ODPP_LOCAL ? OFPP_LOCAL
970                                : flow->in_port);
971     memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
972     memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
973     ofm->match.dl_vlan = flow->dl_vlan;
974     ofm->match.dl_vlan_pcp = flow->dl_vlan_pcp;
975     ofm->match.dl_type = flow->dl_type;
976     ofm->match.nw_src = flow->nw_src;
977     ofm->match.nw_dst = flow->nw_dst;
978     ofm->match.nw_proto = flow->nw_proto;
979     ofm->match.nw_tos = flow->nw_tos;
980     ofm->match.tp_src = flow->tp_src;
981     ofm->match.tp_dst = flow->tp_dst;
982     ofm->command = htons(command);
983     return out;
984 }
985
986 struct ofpbuf *
987 make_add_flow(const flow_t *flow, uint32_t buffer_id,
988               uint16_t idle_timeout, size_t actions_len)
989 {
990     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, flow, actions_len);
991     struct ofp_flow_mod *ofm = out->data;
992     ofm->idle_timeout = htons(idle_timeout);
993     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
994     ofm->buffer_id = htonl(buffer_id);
995     return out;
996 }
997
998 struct ofpbuf *
999 make_del_flow(const flow_t *flow)
1000 {
1001     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, flow, 0);
1002     struct ofp_flow_mod *ofm = out->data;
1003     ofm->out_port = htons(OFPP_NONE);
1004     return out;
1005 }
1006
1007 struct ofpbuf *
1008 make_add_simple_flow(const flow_t *flow,
1009                      uint32_t buffer_id, uint16_t out_port,
1010                      uint16_t idle_timeout)
1011 {
1012     struct ofp_action_output *oao;
1013     struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout,
1014                                           sizeof *oao);
1015     oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1016     oao->type = htons(OFPAT_OUTPUT);
1017     oao->len = htons(sizeof *oao);
1018     oao->port = htons(out_port);
1019     return buffer;
1020 }
1021
1022 struct ofpbuf *
1023 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1024                const struct ofpbuf *payload, int max_send_len)
1025 {
1026     struct ofp_packet_in *opi;
1027     struct ofpbuf *buf;
1028     int send_len;
1029
1030     send_len = MIN(max_send_len, payload->size);
1031     buf = ofpbuf_new(sizeof *opi + send_len);
1032     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1033                            OFPT_PACKET_IN, 0, buf);
1034     opi->buffer_id = htonl(buffer_id);
1035     opi->total_len = htons(payload->size);
1036     opi->in_port = htons(in_port);
1037     opi->reason = reason;
1038     ofpbuf_put(buf, payload->data, send_len);
1039     update_openflow_length(buf);
1040
1041     return buf;
1042 }
1043
1044 struct ofpbuf *
1045 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1046                 uint16_t in_port,
1047                 const struct ofp_action_header *actions, size_t n_actions)
1048 {
1049     size_t actions_len = n_actions * sizeof *actions;
1050     struct ofp_packet_out *opo;
1051     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1052     struct ofpbuf *out = ofpbuf_new(size);
1053
1054     opo = ofpbuf_put_uninit(out, sizeof *opo);
1055     opo->header.version = OFP_VERSION;
1056     opo->header.type = OFPT_PACKET_OUT;
1057     opo->header.length = htons(size);
1058     opo->header.xid = htonl(0);
1059     opo->buffer_id = htonl(buffer_id);
1060     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1061     opo->actions_len = htons(actions_len);
1062     ofpbuf_put(out, actions, actions_len);
1063     if (packet) {
1064         ofpbuf_put(out, packet->data, packet->size);
1065     }
1066     return out;
1067 }
1068
1069 struct ofpbuf *
1070 make_unbuffered_packet_out(const struct ofpbuf *packet,
1071                            uint16_t in_port, uint16_t out_port)
1072 {
1073     struct ofp_action_output action;
1074     action.type = htons(OFPAT_OUTPUT);
1075     action.len = htons(sizeof action);
1076     action.port = htons(out_port);
1077     return make_packet_out(packet, UINT32_MAX, in_port,
1078                            (struct ofp_action_header *) &action, 1);
1079 }
1080
1081 struct ofpbuf *
1082 make_buffered_packet_out(uint32_t buffer_id,
1083                          uint16_t in_port, uint16_t out_port)
1084 {
1085     struct ofp_action_output action;
1086     action.type = htons(OFPAT_OUTPUT);
1087     action.len = htons(sizeof action);
1088     action.port = htons(out_port);
1089     return make_packet_out(NULL, buffer_id, in_port,
1090                            (struct ofp_action_header *) &action, 1);
1091 }
1092
1093 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1094 struct ofpbuf *
1095 make_echo_request(void)
1096 {
1097     struct ofp_header *rq;
1098     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1099     rq = ofpbuf_put_uninit(out, sizeof *rq);
1100     rq->version = OFP_VERSION;
1101     rq->type = OFPT_ECHO_REQUEST;
1102     rq->length = htons(sizeof *rq);
1103     rq->xid = 0;
1104     return out;
1105 }
1106
1107 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1108  * OFPT_ECHO_REQUEST message in 'rq'. */
1109 struct ofpbuf *
1110 make_echo_reply(const struct ofp_header *rq)
1111 {
1112     size_t size = ntohs(rq->length);
1113     struct ofpbuf *out = ofpbuf_new(size);
1114     struct ofp_header *reply = ofpbuf_put(out, rq, size);
1115     reply->type = OFPT_ECHO_REPLY;
1116     return out;
1117 }
1118
1119 static int
1120 check_message_type(uint8_t got_type, uint8_t want_type) 
1121 {
1122     if (got_type != want_type) {
1123         char *want_type_name = ofp_message_type_to_string(want_type);
1124         char *got_type_name = ofp_message_type_to_string(got_type);
1125         VLOG_WARN_RL(&bad_ofmsg_rl,
1126                      "received bad message type %s (expected %s)",
1127                      got_type_name, want_type_name);
1128         free(want_type_name);
1129         free(got_type_name);
1130         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
1131     }
1132     return 0;
1133 }
1134
1135 /* Checks that 'msg' has type 'type' and that it is exactly 'size' bytes long.
1136  * Returns 0 if the checks pass, otherwise an OpenFlow error code (produced
1137  * with ofp_mkerr()). */
1138 int
1139 check_ofp_message(const struct ofp_header *msg, uint8_t type, size_t size)
1140 {
1141     size_t got_size;
1142     int error;
1143
1144     error = check_message_type(msg->type, type);
1145     if (error) {
1146         return error;
1147     }
1148
1149     got_size = ntohs(msg->length);
1150     if (got_size != size) {
1151         char *type_name = ofp_message_type_to_string(type);
1152         VLOG_WARN_RL(&bad_ofmsg_rl,
1153                      "received %s message of length %zu (expected %zu)",
1154                      type_name, got_size, size);
1155         free(type_name);
1156         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1157     }
1158
1159     return 0;
1160 }
1161
1162 /* Checks that 'msg' has type 'type' and that 'msg' is 'size' plus a
1163  * nonnegative integer multiple of 'array_elt_size' bytes long.  Returns 0 if
1164  * the checks pass, otherwise an OpenFlow error code (produced with
1165  * ofp_mkerr()).
1166  *
1167  * If 'n_array_elts' is nonnull, then '*n_array_elts' is set to the number of
1168  * 'array_elt_size' blocks in 'msg' past the first 'min_size' bytes, when
1169  * successful. */
1170 int
1171 check_ofp_message_array(const struct ofp_header *msg, uint8_t type,
1172                         size_t min_size, size_t array_elt_size,
1173                         size_t *n_array_elts)
1174 {
1175     size_t got_size;
1176     int error;
1177
1178     assert(array_elt_size);
1179
1180     error = check_message_type(msg->type, type);
1181     if (error) {
1182         return error;
1183     }
1184
1185     got_size = ntohs(msg->length);
1186     if (got_size < min_size) {
1187         char *type_name = ofp_message_type_to_string(type);
1188         VLOG_WARN_RL(&bad_ofmsg_rl, "received %s message of length %zu "
1189                      "(expected at least %zu)",
1190                      type_name, got_size, min_size);
1191         free(type_name);
1192         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1193     }
1194     if ((got_size - min_size) % array_elt_size) {
1195         char *type_name = ofp_message_type_to_string(type);
1196         VLOG_WARN_RL(&bad_ofmsg_rl,
1197                      "received %s message of bad length %zu: the "
1198                      "excess over %zu (%zu) is not evenly divisible by %zu "
1199                      "(remainder is %zu)",
1200                      type_name, got_size, min_size, got_size - min_size,
1201                      array_elt_size, (got_size - min_size) % array_elt_size);
1202         free(type_name);
1203         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1204     }
1205     if (n_array_elts) {
1206         *n_array_elts = (got_size - min_size) / array_elt_size;
1207     }
1208     return 0;
1209 }
1210
1211 int
1212 check_ofp_packet_out(const struct ofp_header *oh, struct ofpbuf *data,
1213                      int *n_actionsp, int max_ports)
1214 {
1215     const struct ofp_packet_out *opo;
1216     unsigned int actions_len, n_actions;
1217     size_t extra;
1218     int error;
1219
1220     *n_actionsp = 0;
1221     error = check_ofp_message_array(oh, OFPT_PACKET_OUT,
1222                                     sizeof *opo, 1, &extra);
1223     if (error) {
1224         return error;
1225     }
1226     opo = (const struct ofp_packet_out *) oh;
1227
1228     actions_len = ntohs(opo->actions_len);
1229     if (actions_len > extra) {
1230         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %u bytes of actions "
1231                      "but message has room for only %zu bytes",
1232                      actions_len, extra);
1233         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1234     }
1235     if (actions_len % sizeof(union ofp_action)) {
1236         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %u bytes of actions, "
1237                      "which is not a multiple of %zu",
1238                      actions_len, sizeof(union ofp_action));
1239         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1240     }
1241
1242     n_actions = actions_len / sizeof(union ofp_action);
1243     error = validate_actions((const union ofp_action *) opo->actions,
1244                              n_actions, max_ports);
1245     if (error) {
1246         return error;
1247     }
1248
1249     data->data = (void *) &opo->actions[n_actions];
1250     data->size = extra - actions_len;
1251     *n_actionsp = n_actions;
1252     return 0;
1253 }
1254
1255 const struct ofp_flow_stats *
1256 flow_stats_first(struct flow_stats_iterator *iter,
1257                  const struct ofp_stats_reply *osr)
1258 {
1259     iter->pos = osr->body;
1260     iter->end = osr->body + (ntohs(osr->header.length)
1261                              - offsetof(struct ofp_stats_reply, body));
1262     return flow_stats_next(iter);
1263 }
1264
1265 const struct ofp_flow_stats *
1266 flow_stats_next(struct flow_stats_iterator *iter)
1267 {
1268     ptrdiff_t bytes_left = iter->end - iter->pos;
1269     const struct ofp_flow_stats *fs;
1270     size_t length;
1271
1272     if (bytes_left < sizeof *fs) {
1273         if (bytes_left != 0) {
1274             VLOG_WARN_RL(&bad_ofmsg_rl,
1275                          "%td leftover bytes in flow stats reply", bytes_left);
1276         }
1277         return NULL;
1278     }
1279
1280     fs = (const void *) iter->pos;
1281     length = ntohs(fs->length);
1282     if (length < sizeof *fs) {
1283         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
1284                      "min %zu", length, sizeof *fs);
1285         return NULL;
1286     } else if (length > bytes_left) {
1287         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
1288                      "bytes left", length, bytes_left);
1289         return NULL;
1290     } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
1291         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
1292                      "left over in final action", length,
1293                      (length - sizeof *fs) % sizeof fs->actions[0]);
1294         return NULL;
1295     }
1296     iter->pos += length;
1297     return fs;
1298 }
1299
1300 /* Alignment of ofp_actions. */
1301 #define ACTION_ALIGNMENT 8
1302
1303 static int
1304 check_action_exact_len(const union ofp_action *a, unsigned int len,
1305                        unsigned int required_len)
1306 {
1307     if (len != required_len) {
1308         VLOG_DBG_RL(&bad_ofmsg_rl,
1309                     "action %u has invalid length %"PRIu16" (must be %u)\n",
1310                     a->type, ntohs(a->header.len), required_len);
1311         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1312     }
1313     return 0;
1314 }
1315
1316 static int
1317 check_action_port(int port, int max_ports)
1318 {
1319     switch (port) {
1320     case OFPP_IN_PORT:
1321     case OFPP_TABLE:
1322     case OFPP_NORMAL:
1323     case OFPP_FLOOD:
1324     case OFPP_ALL:
1325     case OFPP_CONTROLLER:
1326     case OFPP_LOCAL:
1327         return 0;
1328
1329     default:
1330         if (port >= 0 && port < max_ports) {
1331             return 0;
1332         }
1333         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1334         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1335     }
1336 }
1337
1338 static int
1339 check_nicira_action(const union ofp_action *a, unsigned int len)
1340 {
1341     const struct nx_action_header *nah;
1342
1343     if (len < 16) {
1344         VLOG_DBG_RL(&bad_ofmsg_rl,
1345                     "Nicira vendor action only %u bytes", len);
1346         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1347     }
1348     nah = (const struct nx_action_header *) a;
1349
1350     switch (ntohs(nah->subtype)) {
1351     case NXAST_RESUBMIT:
1352         return check_action_exact_len(a, len, 16);
1353     default:
1354         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1355     }
1356 }
1357
1358 static int
1359 check_action(const union ofp_action *a, unsigned int len, int max_ports)
1360 {
1361     int error;
1362
1363     switch (ntohs(a->type)) {
1364     case OFPAT_OUTPUT:
1365         error = check_action_port(ntohs(a->output.port), max_ports);
1366         return error ? error : check_action_exact_len(a, len, 8);
1367
1368     case OFPAT_SET_VLAN_VID:
1369     case OFPAT_SET_VLAN_PCP:
1370     case OFPAT_STRIP_VLAN:
1371     case OFPAT_SET_NW_SRC:
1372     case OFPAT_SET_NW_DST:
1373     case OFPAT_SET_NW_TOS:
1374     case OFPAT_SET_TP_SRC:
1375     case OFPAT_SET_TP_DST:
1376         return check_action_exact_len(a, len, 8);
1377
1378     case OFPAT_SET_DL_SRC:
1379     case OFPAT_SET_DL_DST:
1380         return check_action_exact_len(a, len, 16);
1381
1382     case OFPAT_VENDOR:
1383         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
1384                 ? check_nicira_action(a, len)
1385                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
1386
1387     default:
1388         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16,
1389                 ntohs(a->type));
1390         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1391     }
1392 }
1393
1394 int
1395 validate_actions(const union ofp_action *actions, size_t n_actions,
1396                  int max_ports)
1397 {
1398     const union ofp_action *a;
1399
1400     for (a = actions; a < &actions[n_actions]; ) {
1401         unsigned int len = ntohs(a->header.len);
1402         unsigned int n_slots = len / ACTION_ALIGNMENT;
1403         unsigned int slots_left = &actions[n_actions] - a;
1404         int error;
1405
1406         if (n_slots > slots_left) {
1407             VLOG_DBG_RL(&bad_ofmsg_rl,
1408                         "action requires %u slots but only %u remain",
1409                         n_slots, slots_left);
1410             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1411         } else if (!len) {
1412             VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
1413             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1414         } else if (len % ACTION_ALIGNMENT) {
1415             VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
1416                         "of %d", len, ACTION_ALIGNMENT);
1417             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1418         }
1419
1420         error = check_action(a, len, max_ports);
1421         if (error) {
1422             return error;
1423         }
1424         a += n_slots;
1425     }
1426     return 0;
1427 }
1428
1429 /* The set of actions must either come from a trusted source or have been
1430  * previously validated with validate_actions(). */
1431 const union ofp_action *
1432 actions_first(struct actions_iterator *iter,
1433               const union ofp_action *oa, size_t n_actions)
1434 {
1435     iter->pos = oa;
1436     iter->end = oa + n_actions;
1437     return actions_next(iter);
1438 }
1439
1440 const union ofp_action *
1441 actions_next(struct actions_iterator *iter)
1442 {
1443     if (iter->pos < iter->end) {
1444         const union ofp_action *a = iter->pos;
1445         unsigned int len = ntohs(a->header.len);
1446         iter->pos += len / ACTION_ALIGNMENT;
1447         return a;
1448     } else {
1449         return NULL;
1450     }
1451 }
1452
1453 void
1454 normalize_match(struct ofp_match *m)
1455 {
1456     enum { OFPFW_NW = OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO };
1457     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
1458     uint32_t wc;
1459
1460     wc = ntohl(m->wildcards) & OFPFW_ALL;
1461     if (wc & OFPFW_DL_TYPE) {
1462         m->dl_type = 0;
1463
1464         /* Can't sensibly match on network or transport headers if the
1465          * data link type is unknown. */
1466         wc |= OFPFW_NW | OFPFW_TP;
1467         m->nw_src = m->nw_dst = m->nw_proto = 0;
1468         m->tp_src = m->tp_dst = 0;
1469     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
1470         if (wc & OFPFW_NW_PROTO) {
1471             m->nw_proto = 0;
1472
1473             /* Can't sensibly match on transport headers if the network
1474              * protocol is unknown. */
1475             wc |= OFPFW_TP;
1476             m->tp_src = m->tp_dst = 0;
1477         } else if (m->nw_proto == IPPROTO_TCP ||
1478                    m->nw_proto == IPPROTO_UDP ||
1479                    m->nw_proto == IPPROTO_ICMP) {
1480             if (wc & OFPFW_TP_SRC) {
1481                 m->tp_src = 0;
1482             }
1483             if (wc & OFPFW_TP_DST) {
1484                 m->tp_dst = 0;
1485             }
1486         } else {
1487             /* Transport layer fields will always be extracted as zeros, so we
1488              * can do an exact-match on those values.  */
1489             wc &= ~OFPFW_TP;
1490             m->tp_src = m->tp_dst = 0;
1491         }
1492         if (wc & OFPFW_NW_SRC_MASK) {
1493             m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
1494         }
1495         if (wc & OFPFW_NW_DST_MASK) {
1496             m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
1497         }
1498     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
1499         if (wc & OFPFW_NW_PROTO) {
1500             m->nw_proto = 0;
1501         }
1502         if (wc & OFPFW_NW_SRC_MASK) {
1503             m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
1504         }
1505         if (wc & OFPFW_NW_DST_MASK) {
1506             m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
1507         }
1508         m->tp_src = m->tp_dst = 0;
1509     } else {
1510         /* Network and transport layer fields will always be extracted as
1511          * zeros, so we can do an exact-match on those values. */
1512         wc &= ~(OFPFW_NW | OFPFW_TP);
1513         m->nw_proto = m->nw_src = m->nw_dst = 0;
1514         m->tp_src = m->tp_dst = 0;
1515     }
1516     if (wc & OFPFW_DL_SRC) {
1517         memset(m->dl_src, 0, sizeof m->dl_src);
1518     }
1519     if (wc & OFPFW_DL_DST) {
1520         memset(m->dl_dst, 0, sizeof m->dl_dst);
1521     }
1522     m->wildcards = htonl(wc);
1523 }
1524
1525 /* Initializes 'vconn' as a new vconn named 'name', implemented via 'class'.
1526  * The initial connection status, supplied as 'connect_status', is interpreted
1527  * as follows:
1528  *
1529  *      - 0: 'vconn' is connected.  Its 'send' and 'recv' functions may be
1530  *        called in the normal fashion.
1531  *
1532  *      - EAGAIN: 'vconn' is trying to complete a connection.  Its 'connect'
1533  *        function should be called to complete the connection.
1534  *
1535  *      - Other positive errno values indicate that the connection failed with
1536  *        the specified error.
1537  *
1538  * After calling this function, vconn_close() must be used to destroy 'vconn',
1539  * otherwise resources will be leaked.
1540  *
1541  * The caller retains ownership of 'name'. */
1542 void
1543 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
1544            const char *name)
1545 {
1546     vconn->class = class;
1547     vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
1548                     : !connect_status ? VCS_SEND_HELLO
1549                     : VCS_DISCONNECTED);
1550     vconn->error = connect_status;
1551     vconn->version = -1;
1552     vconn->min_version = -1;
1553     vconn->remote_ip = 0;
1554     vconn->remote_port = 0;
1555     vconn->local_ip = 0;
1556     vconn->local_port = 0;
1557     vconn->name = xstrdup(name);
1558     assert(vconn->state != VCS_CONNECTING || class->connect);
1559 }
1560
1561 void
1562 vconn_set_remote_ip(struct vconn *vconn, uint32_t ip)
1563 {
1564     vconn->remote_ip = ip;
1565 }
1566
1567 void
1568 vconn_set_remote_port(struct vconn *vconn, uint16_t port)
1569 {
1570     vconn->remote_port = port;
1571 }
1572
1573 void 
1574 vconn_set_local_ip(struct vconn *vconn, uint32_t ip)
1575 {
1576     vconn->local_ip = ip;
1577 }
1578
1579 void 
1580 vconn_set_local_port(struct vconn *vconn, uint16_t port)
1581 {
1582     vconn->local_port = port;
1583 }
1584
1585 void
1586 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
1587             const char *name)
1588 {
1589     pvconn->class = class;
1590     pvconn->name = xstrdup(name);
1591 }