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