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