2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "vconn-provider.h"
22 #include <netinet/in.h>
27 #include "dynamic-string.h"
29 #include "ofp-print.h"
31 #include "openflow/nicira-ext.h"
32 #include "openflow/openflow.h"
34 #include "poll-loop.h"
38 #define THIS_MODULE VLM_vconn
41 /* State of an active vconn.*/
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. */
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. */
54 static struct vconn_class *vconn_classes[] = {
62 static struct pvconn_class *pvconn_classes[] = {
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);
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);
79 static int do_recv(struct vconn *, struct ofpbuf **);
80 static int do_send(struct vconn *, struct ofpbuf *);
82 /* Check the validity of the vconn class structures. */
84 check_vconn_classes(void)
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);
100 /* This class delegates to another one. */
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);
113 /* This class delegates to another one. */
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. */
123 vconn_usage(bool active, bool passive, bool bootstrap OVS_UNUSED)
125 /* Really this should be implemented via callbacks into the vconn
126 * providers, but that seems too heavy-weight to bother with at the
131 printf("Active OpenFlow connection methods:\n");
132 printf(" tcp:IP[:PORT] "
133 "PORT (default: %d) at remote IP\n", OFP_TCP_PORT);
135 printf(" ssl:IP[:PORT] "
136 "SSL PORT (default: %d) at remote IP\n", OFP_SSL_PORT);
138 printf(" unix:FILE Unix domain socket named FILE\n");
142 printf("Passive OpenFlow connection methods:\n");
143 printf(" ptcp:[PORT][:IP] "
144 "listen to TCP PORT (default: %d) on IP\n",
147 printf(" pssl:[PORT][:IP] "
148 "listen for SSL on PORT (default: %d) on IP\n",
151 printf(" punix:FILE "
152 "listen on Unix domain socket FILE\n");
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");
161 printf(" --bootstrap-ca-cert=FILE file with peer CA certificate "
162 "to read or create\n");
167 /* Given 'name', a connection name in the form "TYPE:ARGS", stores the class
168 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
169 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
172 vconn_lookup_class(const char *name, struct vconn_class **classp)
176 prefix_len = strcspn(name, ":");
177 if (name[prefix_len] != '\0') {
180 for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
181 struct vconn_class *class = vconn_classes[i];
182 if (strlen(class->name) == prefix_len
183 && !memcmp(class->name, name, prefix_len)) {
194 /* Returns 0 if 'name' is a connection name in the form "TYPE:ARGS" and TYPE is
195 * a supported connection type, otherwise EAFNOSUPPORT. */
197 vconn_verify_name(const char *name)
199 struct vconn_class *class;
200 return vconn_lookup_class(name, &class);
203 /* Attempts to connect to an OpenFlow device. 'name' is a connection name in
204 * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
205 * are vconn class-specific.
207 * The vconn will automatically negotiate an OpenFlow protocol version
208 * acceptable to both peers on the connection. The version negotiated will be
209 * no lower than 'min_version' and no higher than OFP_VERSION.
211 * Returns 0 if successful, otherwise a positive errno value. If successful,
212 * stores a pointer to the new connection in '*vconnp', otherwise a null
215 vconn_open(const char *name, int min_version, struct vconn **vconnp)
217 struct vconn_class *class;
222 COVERAGE_INC(vconn_open);
223 check_vconn_classes();
225 /* Look up the class. */
226 error = vconn_lookup_class(name, &class);
231 /* Call class's "open" function. */
232 suffix_copy = xstrdup(strchr(name, ':') + 1);
233 error = class->open(name, suffix_copy, &vconn);
240 assert(vconn->state != VCS_CONNECTING || vconn->class->connect);
241 vconn->min_version = min_version;
250 /* Allows 'vconn' to perform maintenance activities, such as flushing output
253 vconn_run(struct vconn *vconn)
255 if (vconn->class->run) {
256 (vconn->class->run)(vconn);
260 /* Arranges for the poll loop to wake up when 'vconn' needs to perform
261 * maintenance activities. */
263 vconn_run_wait(struct vconn *vconn)
265 if (vconn->class->run_wait) {
266 (vconn->class->run_wait)(vconn);
271 vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
276 error = vconn_open(name, min_version, &vconn);
277 while (error == EAGAIN) {
279 vconn_run_wait(vconn);
280 vconn_connect_wait(vconn);
282 error = vconn_connect(vconn);
283 assert(error != EINPROGRESS);
294 /* Closes 'vconn'. */
296 vconn_close(struct vconn *vconn)
299 char *name = vconn->name;
300 (vconn->class->close)(vconn);
305 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
307 vconn_get_name(const struct vconn *vconn)
312 /* Returns the IP address of the peer, or 0 if the peer is not connected over
313 * an IP-based protocol or if its IP address is not yet known. */
315 vconn_get_remote_ip(const struct vconn *vconn)
317 return vconn->remote_ip;
320 /* Returns the transport port of the peer, or 0 if the connection does not
321 * contain a port or if the port is not yet known. */
323 vconn_get_remote_port(const struct vconn *vconn)
325 return vconn->remote_port;
328 /* Returns the IP address used to connect to the peer, or 0 if the
329 * connection is not an IP-based protocol or if its IP address is not
332 vconn_get_local_ip(const struct vconn *vconn)
334 return vconn->local_ip;
337 /* Returns the transport port used to connect to the peer, or 0 if the
338 * connection does not contain a port or if the port is not yet known. */
340 vconn_get_local_port(const struct vconn *vconn)
342 return vconn->local_port;
346 vcs_connecting(struct vconn *vconn)
348 int retval = (vconn->class->connect)(vconn);
349 assert(retval != EINPROGRESS);
351 vconn->state = VCS_SEND_HELLO;
352 } else if (retval != EAGAIN) {
353 vconn->state = VCS_DISCONNECTED;
354 vconn->error = retval;
359 vcs_send_hello(struct vconn *vconn)
364 make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
365 retval = do_send(vconn, b);
367 vconn->state = VCS_RECV_HELLO;
370 if (retval != EAGAIN) {
371 vconn->state = VCS_DISCONNECTED;
372 vconn->error = retval;
378 vcs_recv_hello(struct vconn *vconn)
383 retval = do_recv(vconn, &b);
385 struct ofp_header *oh = b->data;
387 if (oh->type == OFPT_HELLO) {
388 if (b->size > sizeof *oh) {
389 struct ds msg = DS_EMPTY_INITIALIZER;
390 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
391 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
392 VLOG_WARN_RL(&bad_ofmsg_rl, "%s", ds_cstr(&msg));
396 vconn->version = MIN(OFP_VERSION, oh->version);
397 if (vconn->version < vconn->min_version) {
398 VLOG_WARN_RL(&bad_ofmsg_rl,
399 "%s: version negotiation failed: we support "
400 "versions 0x%02x to 0x%02x inclusive but peer "
401 "supports no later than version 0x%02"PRIx8,
402 vconn->name, vconn->min_version, OFP_VERSION,
404 vconn->state = VCS_SEND_ERROR;
406 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
407 "(we support versions 0x%02x to 0x%02x inclusive, "
408 "peer no later than version 0x%02"PRIx8")",
409 vconn->name, vconn->version, vconn->min_version,
410 OFP_VERSION, oh->version);
411 vconn->state = VCS_CONNECTED;
416 char *s = ofp_to_string(b->data, b->size, 1);
417 VLOG_WARN_RL(&bad_ofmsg_rl,
418 "%s: received message while expecting hello: %s",
426 if (retval != EAGAIN) {
427 vconn->state = VCS_DISCONNECTED;
428 vconn->error = retval == EOF ? ECONNRESET : retval;
433 vcs_send_error(struct vconn *vconn)
435 struct ofp_error_msg *error;
440 snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
441 "you support no later than version 0x%02"PRIx8".",
442 vconn->min_version, OFP_VERSION, vconn->version);
443 error = make_openflow(sizeof *error, OFPT_ERROR, &b);
444 error->type = htons(OFPET_HELLO_FAILED);
445 error->code = htons(OFPHFC_INCOMPATIBLE);
446 ofpbuf_put(b, s, strlen(s));
447 update_openflow_length(b);
448 retval = do_send(vconn, b);
452 if (retval != EAGAIN) {
453 vconn->state = VCS_DISCONNECTED;
454 vconn->error = retval ? retval : EPROTO;
458 /* Tries to complete the connection on 'vconn', which must be an active
459 * vconn. If 'vconn''s connection is complete, returns 0 if the connection
460 * was successful or a positive errno value if it failed. If the
461 * connection is still in progress, returns EAGAIN. */
463 vconn_connect(struct vconn *vconn)
465 enum vconn_state last_state;
467 assert(vconn->min_version >= 0);
469 last_state = vconn->state;
470 switch (vconn->state) {
472 vcs_connecting(vconn);
476 vcs_send_hello(vconn);
480 vcs_recv_hello(vconn);
487 vcs_send_error(vconn);
490 case VCS_DISCONNECTED:
496 } while (vconn->state != last_state);
501 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
502 * vconn. If successful, stores the received message into '*msgp' and returns
503 * 0. The caller is responsible for destroying the message with
504 * ofpbuf_delete(). On failure, returns a positive errno value and stores a
505 * null pointer into '*msgp'. On normal connection close, returns EOF.
507 * vconn_recv will not block waiting for a packet to arrive. If no packets
508 * have been received, it returns EAGAIN immediately. */
510 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
512 int retval = vconn_connect(vconn);
514 retval = do_recv(vconn, msgp);
520 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
522 int retval = (vconn->class->recv)(vconn, msgp);
524 struct ofp_header *oh;
526 COVERAGE_INC(vconn_received);
527 if (VLOG_IS_DBG_ENABLED()) {
528 char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
529 VLOG_DBG_RL(&ofmsg_rl, "%s: received: %s", vconn->name, s);
533 oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
534 if (oh->version != vconn->version
535 && oh->type != OFPT_HELLO
536 && oh->type != OFPT_ERROR
537 && oh->type != OFPT_ECHO_REQUEST
538 && oh->type != OFPT_ECHO_REPLY
539 && oh->type != OFPT_VENDOR)
541 if (vconn->version < 0) {
542 VLOG_ERR_RL(&bad_ofmsg_rl,
543 "%s: received OpenFlow message type %"PRIu8" "
544 "before version negotiation complete",
545 vconn->name, oh->type);
547 VLOG_ERR_RL(&bad_ofmsg_rl,
548 "%s: received OpenFlow version 0x%02"PRIx8" "
550 vconn->name, oh->version, vconn->version);
552 ofpbuf_delete(*msgp);
562 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
563 * vconn. If successful, returns 0, in which case ownership of 'msg' is
564 * transferred to the vconn. Success does not guarantee that 'msg' has been or
565 * ever will be delivered to the peer, only that it has been queued for
568 * Returns a positive errno value on failure, in which case the caller
569 * retains ownership of 'msg'.
571 * vconn_send will not block. If 'msg' cannot be immediately accepted for
572 * transmission, it returns EAGAIN immediately. */
574 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
576 int retval = vconn_connect(vconn);
578 retval = do_send(vconn, msg);
584 do_send(struct vconn *vconn, struct ofpbuf *msg)
588 assert(msg->size >= sizeof(struct ofp_header));
589 assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
590 if (!VLOG_IS_DBG_ENABLED()) {
591 COVERAGE_INC(vconn_sent);
592 retval = (vconn->class->send)(vconn, msg);
594 char *s = ofp_to_string(msg->data, msg->size, 1);
595 retval = (vconn->class->send)(vconn, msg);
596 if (retval != EAGAIN) {
597 VLOG_DBG_RL(&ofmsg_rl, "%s: sent (%s): %s",
598 vconn->name, strerror(retval), s);
605 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
607 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
610 while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
612 vconn_run_wait(vconn);
613 vconn_send_wait(vconn);
619 /* Same as vconn_recv, except that it waits until a message is received. */
621 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
624 while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
626 vconn_run_wait(vconn);
627 vconn_recv_wait(vconn);
633 /* Waits until a message with a transaction ID matching 'xid' is recived on
634 * 'vconn'. Returns 0 if successful, in which case the reply is stored in
635 * '*replyp' for the caller to examine and free. Otherwise returns a positive
636 * errno value, or EOF, and sets '*replyp' to null.
638 * 'request' is always destroyed, regardless of the return value. */
640 vconn_recv_xid(struct vconn *vconn, uint32_t xid, struct ofpbuf **replyp)
644 struct ofpbuf *reply;
647 error = vconn_recv_block(vconn, &reply);
652 recv_xid = ((struct ofp_header *) reply->data)->xid;
653 if (xid == recv_xid) {
658 VLOG_DBG_RL(&bad_ofmsg_rl, "%s: received reply with xid %08"PRIx32
659 " != expected %08"PRIx32, vconn->name, recv_xid, xid);
660 ofpbuf_delete(reply);
664 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
665 * matching transaction ID. Returns 0 if successful, in which case the reply
666 * is stored in '*replyp' for the caller to examine and free. Otherwise
667 * returns a positive errno value, or EOF, and sets '*replyp' to null.
669 * 'request' is always destroyed, regardless of the return value. */
671 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
672 struct ofpbuf **replyp)
674 uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
678 error = vconn_send_block(vconn, request);
680 ofpbuf_delete(request);
682 return error ? error : vconn_recv_xid(vconn, send_xid, replyp);
686 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
688 assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
690 switch (vconn->state) {
707 case VCS_DISCONNECTED:
708 poll_immediate_wake();
711 (vconn->class->wait)(vconn, wait);
715 vconn_connect_wait(struct vconn *vconn)
717 vconn_wait(vconn, WAIT_CONNECT);
721 vconn_recv_wait(struct vconn *vconn)
723 vconn_wait(vconn, WAIT_RECV);
727 vconn_send_wait(struct vconn *vconn)
729 vconn_wait(vconn, WAIT_SEND);
732 /* Given 'name', a connection name in the form "TYPE:ARGS", stores the class
733 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
734 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
737 pvconn_lookup_class(const char *name, struct pvconn_class **classp)
741 prefix_len = strcspn(name, ":");
742 if (name[prefix_len] != '\0') {
745 for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
746 struct pvconn_class *class = pvconn_classes[i];
747 if (strlen(class->name) == prefix_len
748 && !memcmp(class->name, name, prefix_len)) {
759 /* Returns 0 if 'name' is a connection name in the form "TYPE:ARGS" and TYPE is
760 * a supported connection type, otherwise EAFNOSUPPORT. */
762 pvconn_verify_name(const char *name)
764 struct pvconn_class *class;
765 return pvconn_lookup_class(name, &class);
768 /* Attempts to start listening for OpenFlow connections. 'name' is a
769 * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
770 * class's name and ARGS are vconn class-specific.
772 * Returns 0 if successful, otherwise a positive errno value. If successful,
773 * stores a pointer to the new connection in '*pvconnp', otherwise a null
776 pvconn_open(const char *name, struct pvconn **pvconnp)
778 struct pvconn_class *class;
779 struct pvconn *pvconn;
783 check_vconn_classes();
785 /* Look up the class. */
786 error = pvconn_lookup_class(name, &class);
791 /* Call class's "open" function. */
792 suffix_copy = xstrdup(strchr(name, ':') + 1);
793 error = class->listen(name, suffix_copy, &pvconn);
808 /* Returns the name that was used to open 'pvconn'. The caller must not
809 * modify or free the name. */
811 pvconn_get_name(const struct pvconn *pvconn)
816 /* Closes 'pvconn'. */
818 pvconn_close(struct pvconn *pvconn)
820 if (pvconn != NULL) {
821 char *name = pvconn->name;
822 (pvconn->class->close)(pvconn);
827 /* Tries to accept a new connection on 'pvconn'. If successful, stores the new
828 * connection in '*new_vconn' and returns 0. Otherwise, returns a positive
831 * The new vconn will automatically negotiate an OpenFlow protocol version
832 * acceptable to both peers on the connection. The version negotiated will be
833 * no lower than 'min_version' and no higher than OFP_VERSION.
835 * pvconn_accept() will not block waiting for a connection. If no connection
836 * is ready to be accepted, it returns EAGAIN immediately. */
838 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
840 int retval = (pvconn->class->accept)(pvconn, new_vconn);
844 assert((*new_vconn)->state != VCS_CONNECTING
845 || (*new_vconn)->class->connect);
846 (*new_vconn)->min_version = min_version;
852 pvconn_wait(struct pvconn *pvconn)
854 (pvconn->class->wait)(pvconn);
857 /* XXX we should really use consecutive xids to avoid probabilistic
859 static inline uint32_t
862 return random_uint32();
865 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
866 * 'openflow_len', starting with an OpenFlow header with the given 'type' and
867 * an arbitrary transaction id. Allocated bytes beyond the header, if any, are
870 * The caller is responsible for freeing '*bufferp' when it is no longer
873 * The OpenFlow header length is initially set to 'openflow_len'; if the
874 * message is later extended, the length should be updated with
875 * update_openflow_length() before sending.
877 * Returns the header. */
879 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
881 *bufferp = ofpbuf_new(openflow_len);
882 return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
885 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
886 * 'openflow_len', starting with an OpenFlow header with the given 'type' and
887 * transaction id 'xid'. Allocated bytes beyond the header, if any, are
890 * The caller is responsible for freeing '*bufferp' when it is no longer
893 * The OpenFlow header length is initially set to 'openflow_len'; if the
894 * message is later extended, the length should be updated with
895 * update_openflow_length() before sending.
897 * Returns the header. */
899 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
900 struct ofpbuf **bufferp)
902 *bufferp = ofpbuf_new(openflow_len);
903 return put_openflow_xid(openflow_len, type, xid, *bufferp);
906 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
907 * with the given 'type' and an arbitrary transaction id. Allocated bytes
908 * beyond the header, if any, are zeroed.
910 * The OpenFlow header length is initially set to 'openflow_len'; if the
911 * message is later extended, the length should be updated with
912 * update_openflow_length() before sending.
914 * Returns the header. */
916 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
918 return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
921 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
922 * with the given 'type' and an transaction id 'xid'. Allocated bytes beyond
923 * the header, if any, are zeroed.
925 * The OpenFlow header length is initially set to 'openflow_len'; if the
926 * message is later extended, the length should be updated with
927 * update_openflow_length() before sending.
929 * Returns the header. */
931 put_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
932 struct ofpbuf *buffer)
934 struct ofp_header *oh;
936 assert(openflow_len >= sizeof *oh);
937 assert(openflow_len <= UINT16_MAX);
939 oh = ofpbuf_put_uninit(buffer, openflow_len);
940 oh->version = OFP_VERSION;
942 oh->length = htons(openflow_len);
944 memset(oh + 1, 0, openflow_len - sizeof *oh);
948 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
951 update_openflow_length(struct ofpbuf *buffer)
953 struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
954 oh->length = htons(buffer->size);
958 make_flow_mod(uint16_t command, const flow_t *flow, size_t actions_len)
960 struct ofp_flow_mod *ofm;
961 size_t size = sizeof *ofm + actions_len;
962 struct ofpbuf *out = ofpbuf_new(size);
963 ofm = ofpbuf_put_zeros(out, sizeof *ofm);
964 ofm->header.version = OFP_VERSION;
965 ofm->header.type = OFPT_FLOW_MOD;
966 ofm->header.length = htons(size);
968 ofm->match.wildcards = htonl(0);
969 ofm->match.in_port = htons(flow->in_port == ODPP_LOCAL ? OFPP_LOCAL
971 memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
972 memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
973 ofm->match.dl_vlan = flow->dl_vlan;
974 ofm->match.dl_vlan_pcp = flow->dl_vlan_pcp;
975 ofm->match.dl_type = flow->dl_type;
976 ofm->match.nw_src = flow->nw_src;
977 ofm->match.nw_dst = flow->nw_dst;
978 ofm->match.nw_proto = flow->nw_proto;
979 ofm->match.nw_tos = flow->nw_tos;
980 ofm->match.tp_src = flow->tp_src;
981 ofm->match.tp_dst = flow->tp_dst;
982 ofm->command = htons(command);
987 make_add_flow(const flow_t *flow, uint32_t buffer_id,
988 uint16_t idle_timeout, size_t actions_len)
990 struct ofpbuf *out = make_flow_mod(OFPFC_ADD, flow, actions_len);
991 struct ofp_flow_mod *ofm = out->data;
992 ofm->idle_timeout = htons(idle_timeout);
993 ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
994 ofm->buffer_id = htonl(buffer_id);
999 make_del_flow(const flow_t *flow)
1001 struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, flow, 0);
1002 struct ofp_flow_mod *ofm = out->data;
1003 ofm->out_port = htons(OFPP_NONE);
1008 make_add_simple_flow(const flow_t *flow,
1009 uint32_t buffer_id, uint16_t out_port,
1010 uint16_t idle_timeout)
1012 struct ofp_action_output *oao;
1013 struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout,
1015 oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1016 oao->type = htons(OFPAT_OUTPUT);
1017 oao->len = htons(sizeof *oao);
1018 oao->port = htons(out_port);
1023 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1024 const struct ofpbuf *payload, int max_send_len)
1026 struct ofp_packet_in *opi;
1030 send_len = MIN(max_send_len, payload->size);
1031 buf = ofpbuf_new(sizeof *opi + send_len);
1032 opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1033 OFPT_PACKET_IN, 0, buf);
1034 opi->buffer_id = htonl(buffer_id);
1035 opi->total_len = htons(payload->size);
1036 opi->in_port = htons(in_port);
1037 opi->reason = reason;
1038 ofpbuf_put(buf, payload->data, send_len);
1039 update_openflow_length(buf);
1045 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1047 const struct ofp_action_header *actions, size_t n_actions)
1049 size_t actions_len = n_actions * sizeof *actions;
1050 struct ofp_packet_out *opo;
1051 size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1052 struct ofpbuf *out = ofpbuf_new(size);
1054 opo = ofpbuf_put_uninit(out, sizeof *opo);
1055 opo->header.version = OFP_VERSION;
1056 opo->header.type = OFPT_PACKET_OUT;
1057 opo->header.length = htons(size);
1058 opo->header.xid = htonl(0);
1059 opo->buffer_id = htonl(buffer_id);
1060 opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1061 opo->actions_len = htons(actions_len);
1062 ofpbuf_put(out, actions, actions_len);
1064 ofpbuf_put(out, packet->data, packet->size);
1070 make_unbuffered_packet_out(const struct ofpbuf *packet,
1071 uint16_t in_port, uint16_t out_port)
1073 struct ofp_action_output action;
1074 action.type = htons(OFPAT_OUTPUT);
1075 action.len = htons(sizeof action);
1076 action.port = htons(out_port);
1077 return make_packet_out(packet, UINT32_MAX, in_port,
1078 (struct ofp_action_header *) &action, 1);
1082 make_buffered_packet_out(uint32_t buffer_id,
1083 uint16_t in_port, uint16_t out_port)
1085 struct ofp_action_output action;
1086 action.type = htons(OFPAT_OUTPUT);
1087 action.len = htons(sizeof action);
1088 action.port = htons(out_port);
1089 return make_packet_out(NULL, buffer_id, in_port,
1090 (struct ofp_action_header *) &action, 1);
1093 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1095 make_echo_request(void)
1097 struct ofp_header *rq;
1098 struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1099 rq = ofpbuf_put_uninit(out, sizeof *rq);
1100 rq->version = OFP_VERSION;
1101 rq->type = OFPT_ECHO_REQUEST;
1102 rq->length = htons(sizeof *rq);
1107 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1108 * OFPT_ECHO_REQUEST message in 'rq'. */
1110 make_echo_reply(const struct ofp_header *rq)
1112 size_t size = ntohs(rq->length);
1113 struct ofpbuf *out = ofpbuf_new(size);
1114 struct ofp_header *reply = ofpbuf_put(out, rq, size);
1115 reply->type = OFPT_ECHO_REPLY;
1120 check_message_type(uint8_t got_type, uint8_t want_type)
1122 if (got_type != want_type) {
1123 char *want_type_name = ofp_message_type_to_string(want_type);
1124 char *got_type_name = ofp_message_type_to_string(got_type);
1125 VLOG_WARN_RL(&bad_ofmsg_rl,
1126 "received bad message type %s (expected %s)",
1127 got_type_name, want_type_name);
1128 free(want_type_name);
1129 free(got_type_name);
1130 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
1135 /* Checks that 'msg' has type 'type' and that it is exactly 'size' bytes long.
1136 * Returns 0 if the checks pass, otherwise an OpenFlow error code (produced
1137 * with ofp_mkerr()). */
1139 check_ofp_message(const struct ofp_header *msg, uint8_t type, size_t size)
1144 error = check_message_type(msg->type, type);
1149 got_size = ntohs(msg->length);
1150 if (got_size != size) {
1151 char *type_name = ofp_message_type_to_string(type);
1152 VLOG_WARN_RL(&bad_ofmsg_rl,
1153 "received %s message of length %zu (expected %zu)",
1154 type_name, got_size, size);
1156 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1162 /* Checks that 'msg' has type 'type' and that 'msg' is 'size' plus a
1163 * nonnegative integer multiple of 'array_elt_size' bytes long. Returns 0 if
1164 * the checks pass, otherwise an OpenFlow error code (produced with
1167 * If 'n_array_elts' is nonnull, then '*n_array_elts' is set to the number of
1168 * 'array_elt_size' blocks in 'msg' past the first 'min_size' bytes, when
1171 check_ofp_message_array(const struct ofp_header *msg, uint8_t type,
1172 size_t min_size, size_t array_elt_size,
1173 size_t *n_array_elts)
1178 assert(array_elt_size);
1180 error = check_message_type(msg->type, type);
1185 got_size = ntohs(msg->length);
1186 if (got_size < min_size) {
1187 char *type_name = ofp_message_type_to_string(type);
1188 VLOG_WARN_RL(&bad_ofmsg_rl, "received %s message of length %zu "
1189 "(expected at least %zu)",
1190 type_name, got_size, min_size);
1192 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1194 if ((got_size - min_size) % array_elt_size) {
1195 char *type_name = ofp_message_type_to_string(type);
1196 VLOG_WARN_RL(&bad_ofmsg_rl,
1197 "received %s message of bad length %zu: the "
1198 "excess over %zu (%zu) is not evenly divisible by %zu "
1199 "(remainder is %zu)",
1200 type_name, got_size, min_size, got_size - min_size,
1201 array_elt_size, (got_size - min_size) % array_elt_size);
1203 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1206 *n_array_elts = (got_size - min_size) / array_elt_size;
1212 check_ofp_packet_out(const struct ofp_header *oh, struct ofpbuf *data,
1213 int *n_actionsp, int max_ports)
1215 const struct ofp_packet_out *opo;
1216 unsigned int actions_len, n_actions;
1221 error = check_ofp_message_array(oh, OFPT_PACKET_OUT,
1222 sizeof *opo, 1, &extra);
1226 opo = (const struct ofp_packet_out *) oh;
1228 actions_len = ntohs(opo->actions_len);
1229 if (actions_len > extra) {
1230 VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %u bytes of actions "
1231 "but message has room for only %zu bytes",
1232 actions_len, extra);
1233 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1235 if (actions_len % sizeof(union ofp_action)) {
1236 VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %u bytes of actions, "
1237 "which is not a multiple of %zu",
1238 actions_len, sizeof(union ofp_action));
1239 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1242 n_actions = actions_len / sizeof(union ofp_action);
1243 error = validate_actions((const union ofp_action *) opo->actions,
1244 n_actions, max_ports);
1249 data->data = (void *) &opo->actions[n_actions];
1250 data->size = extra - actions_len;
1251 *n_actionsp = n_actions;
1255 const struct ofp_flow_stats *
1256 flow_stats_first(struct flow_stats_iterator *iter,
1257 const struct ofp_stats_reply *osr)
1259 iter->pos = osr->body;
1260 iter->end = osr->body + (ntohs(osr->header.length)
1261 - offsetof(struct ofp_stats_reply, body));
1262 return flow_stats_next(iter);
1265 const struct ofp_flow_stats *
1266 flow_stats_next(struct flow_stats_iterator *iter)
1268 ptrdiff_t bytes_left = iter->end - iter->pos;
1269 const struct ofp_flow_stats *fs;
1272 if (bytes_left < sizeof *fs) {
1273 if (bytes_left != 0) {
1274 VLOG_WARN_RL(&bad_ofmsg_rl,
1275 "%td leftover bytes in flow stats reply", bytes_left);
1280 fs = (const void *) iter->pos;
1281 length = ntohs(fs->length);
1282 if (length < sizeof *fs) {
1283 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
1284 "min %zu", length, sizeof *fs);
1286 } else if (length > bytes_left) {
1287 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
1288 "bytes left", length, bytes_left);
1290 } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
1291 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
1292 "left over in final action", length,
1293 (length - sizeof *fs) % sizeof fs->actions[0]);
1296 iter->pos += length;
1300 /* Alignment of ofp_actions. */
1301 #define ACTION_ALIGNMENT 8
1304 check_action_exact_len(const union ofp_action *a, unsigned int len,
1305 unsigned int required_len)
1307 if (len != required_len) {
1308 VLOG_DBG_RL(&bad_ofmsg_rl,
1309 "action %u has invalid length %"PRIu16" (must be %u)\n",
1310 a->type, ntohs(a->header.len), required_len);
1311 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1317 check_action_port(int port, int max_ports)
1325 case OFPP_CONTROLLER:
1330 if (port >= 0 && port < max_ports) {
1333 VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1334 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1339 check_nicira_action(const union ofp_action *a, unsigned int len)
1341 const struct nx_action_header *nah;
1344 VLOG_DBG_RL(&bad_ofmsg_rl,
1345 "Nicira vendor action only %u bytes", len);
1346 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1348 nah = (const struct nx_action_header *) a;
1350 switch (ntohs(nah->subtype)) {
1351 case NXAST_RESUBMIT:
1352 return check_action_exact_len(a, len, 16);
1354 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1359 check_action(const union ofp_action *a, unsigned int len, int max_ports)
1363 switch (ntohs(a->type)) {
1365 error = check_action_port(ntohs(a->output.port), max_ports);
1366 return error ? error : check_action_exact_len(a, len, 8);
1368 case OFPAT_SET_VLAN_VID:
1369 case OFPAT_SET_VLAN_PCP:
1370 case OFPAT_STRIP_VLAN:
1371 case OFPAT_SET_NW_SRC:
1372 case OFPAT_SET_NW_DST:
1373 case OFPAT_SET_NW_TOS:
1374 case OFPAT_SET_TP_SRC:
1375 case OFPAT_SET_TP_DST:
1376 return check_action_exact_len(a, len, 8);
1378 case OFPAT_SET_DL_SRC:
1379 case OFPAT_SET_DL_DST:
1380 return check_action_exact_len(a, len, 16);
1383 return (a->vendor.vendor == htonl(NX_VENDOR_ID)
1384 ? check_nicira_action(a, len)
1385 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
1388 VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16,
1390 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1395 validate_actions(const union ofp_action *actions, size_t n_actions,
1398 const union ofp_action *a;
1400 for (a = actions; a < &actions[n_actions]; ) {
1401 unsigned int len = ntohs(a->header.len);
1402 unsigned int n_slots = len / ACTION_ALIGNMENT;
1403 unsigned int slots_left = &actions[n_actions] - a;
1406 if (n_slots > slots_left) {
1407 VLOG_DBG_RL(&bad_ofmsg_rl,
1408 "action requires %u slots but only %u remain",
1409 n_slots, slots_left);
1410 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1412 VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
1413 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1414 } else if (len % ACTION_ALIGNMENT) {
1415 VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
1416 "of %d", len, ACTION_ALIGNMENT);
1417 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1420 error = check_action(a, len, max_ports);
1429 /* The set of actions must either come from a trusted source or have been
1430 * previously validated with validate_actions(). */
1431 const union ofp_action *
1432 actions_first(struct actions_iterator *iter,
1433 const union ofp_action *oa, size_t n_actions)
1436 iter->end = oa + n_actions;
1437 return actions_next(iter);
1440 const union ofp_action *
1441 actions_next(struct actions_iterator *iter)
1443 if (iter->pos < iter->end) {
1444 const union ofp_action *a = iter->pos;
1445 unsigned int len = ntohs(a->header.len);
1446 iter->pos += len / ACTION_ALIGNMENT;
1454 normalize_match(struct ofp_match *m)
1456 enum { OFPFW_NW = OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO };
1457 enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
1460 wc = ntohl(m->wildcards) & OFPFW_ALL;
1461 if (wc & OFPFW_DL_TYPE) {
1464 /* Can't sensibly match on network or transport headers if the
1465 * data link type is unknown. */
1466 wc |= OFPFW_NW | OFPFW_TP;
1467 m->nw_src = m->nw_dst = m->nw_proto = 0;
1468 m->tp_src = m->tp_dst = 0;
1469 } else if (m->dl_type == htons(ETH_TYPE_IP)) {
1470 if (wc & OFPFW_NW_PROTO) {
1473 /* Can't sensibly match on transport headers if the network
1474 * protocol is unknown. */
1476 m->tp_src = m->tp_dst = 0;
1477 } else if (m->nw_proto == IPPROTO_TCP ||
1478 m->nw_proto == IPPROTO_UDP ||
1479 m->nw_proto == IPPROTO_ICMP) {
1480 if (wc & OFPFW_TP_SRC) {
1483 if (wc & OFPFW_TP_DST) {
1487 /* Transport layer fields will always be extracted as zeros, so we
1488 * can do an exact-match on those values. */
1490 m->tp_src = m->tp_dst = 0;
1492 if (wc & OFPFW_NW_SRC_MASK) {
1493 m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
1495 if (wc & OFPFW_NW_DST_MASK) {
1496 m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
1498 } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
1499 if (wc & OFPFW_NW_PROTO) {
1502 if (wc & OFPFW_NW_SRC_MASK) {
1503 m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
1505 if (wc & OFPFW_NW_DST_MASK) {
1506 m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
1508 m->tp_src = m->tp_dst = 0;
1510 /* Network and transport layer fields will always be extracted as
1511 * zeros, so we can do an exact-match on those values. */
1512 wc &= ~(OFPFW_NW | OFPFW_TP);
1513 m->nw_proto = m->nw_src = m->nw_dst = 0;
1514 m->tp_src = m->tp_dst = 0;
1516 if (wc & OFPFW_DL_SRC) {
1517 memset(m->dl_src, 0, sizeof m->dl_src);
1519 if (wc & OFPFW_DL_DST) {
1520 memset(m->dl_dst, 0, sizeof m->dl_dst);
1522 m->wildcards = htonl(wc);
1525 /* Initializes 'vconn' as a new vconn named 'name', implemented via 'class'.
1526 * The initial connection status, supplied as 'connect_status', is interpreted
1529 * - 0: 'vconn' is connected. Its 'send' and 'recv' functions may be
1530 * called in the normal fashion.
1532 * - EAGAIN: 'vconn' is trying to complete a connection. Its 'connect'
1533 * function should be called to complete the connection.
1535 * - Other positive errno values indicate that the connection failed with
1536 * the specified error.
1538 * After calling this function, vconn_close() must be used to destroy 'vconn',
1539 * otherwise resources will be leaked.
1541 * The caller retains ownership of 'name'. */
1543 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
1546 vconn->class = class;
1547 vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
1548 : !connect_status ? VCS_SEND_HELLO
1549 : VCS_DISCONNECTED);
1550 vconn->error = connect_status;
1551 vconn->version = -1;
1552 vconn->min_version = -1;
1553 vconn->remote_ip = 0;
1554 vconn->remote_port = 0;
1555 vconn->local_ip = 0;
1556 vconn->local_port = 0;
1557 vconn->name = xstrdup(name);
1558 assert(vconn->state != VCS_CONNECTING || class->connect);
1562 vconn_set_remote_ip(struct vconn *vconn, uint32_t ip)
1564 vconn->remote_ip = ip;
1568 vconn_set_remote_port(struct vconn *vconn, uint16_t port)
1570 vconn->remote_port = port;
1574 vconn_set_local_ip(struct vconn *vconn, uint32_t ip)
1576 vconn->local_ip = ip;
1580 vconn_set_local_port(struct vconn *vconn, uint16_t port)
1582 vconn->local_port = port;
1586 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
1589 pvconn->class = class;
1590 pvconn->name = xstrdup(name);