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