2 * Copyright (c) 2008, 2009 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 || class->wait) {
94 assert(class->close != NULL);
95 assert(class->recv != NULL);
96 assert(class->send != NULL);
97 assert(class->wait != NULL);
99 /* This class delegates to another one. */
103 for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
104 struct pvconn_class *class = pvconn_classes[i];
105 assert(class->name != NULL);
106 assert(class->listen != NULL);
107 if (class->close || class->accept || class->wait) {
108 assert(class->close != NULL);
109 assert(class->accept != NULL);
110 assert(class->wait != NULL);
112 /* This class delegates to another one. */
118 /* Prints information on active (if 'active') and passive (if 'passive')
119 * connection methods supported by the vconn. If 'bootstrap' is true, also
120 * advertises options to bootstrap the CA certificate. */
122 vconn_usage(bool active, bool passive, bool bootstrap UNUSED)
124 /* Really this should be implemented via callbacks into the vconn
125 * providers, but that seems too heavy-weight to bother with at the
130 printf("Active OpenFlow connection methods:\n");
131 printf(" tcp:HOST[:PORT] "
132 "PORT (default: %d) on remote TCP HOST\n", OFP_TCP_PORT);
134 printf(" ssl:HOST[:PORT] "
135 "SSL PORT (default: %d) on remote HOST\n", OFP_SSL_PORT);
137 printf(" unix:FILE Unix domain socket named FILE\n");
141 printf("Passive OpenFlow connection methods:\n");
142 printf(" ptcp:[PORT][:IP] "
143 "listen to TCP PORT (default: %d) on IP\n",
146 printf(" pssl:[PORT][:IP] "
147 "listen for SSL on PORT (default: %d) on IP\n",
150 printf(" punix:FILE "
151 "listen on Unix domain socket FILE\n");
155 printf("PKI configuration (required to use SSL):\n"
156 " -p, --private-key=FILE file with private key\n"
157 " -c, --certificate=FILE file with certificate for private key\n"
158 " -C, --ca-cert=FILE file with peer CA certificate\n");
160 printf(" --bootstrap-ca-cert=FILE file with peer CA certificate "
161 "to read or create\n");
166 /* Attempts to connect to an OpenFlow device. 'name' is a connection name in
167 * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
168 * are vconn class-specific.
170 * The vconn will automatically negotiate an OpenFlow protocol version
171 * acceptable to both peers on the connection. The version negotiated will be
172 * no lower than 'min_version' and no higher than OFP_VERSION.
174 * Returns 0 if successful, otherwise a positive errno value. If successful,
175 * stores a pointer to the new connection in '*vconnp', otherwise a null
178 vconn_open(const char *name, int min_version, struct vconn **vconnp)
183 COVERAGE_INC(vconn_open);
184 check_vconn_classes();
187 prefix_len = strcspn(name, ":");
188 if (prefix_len == strlen(name)) {
191 for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
192 struct vconn_class *class = vconn_classes[i];
193 if (strlen(class->name) == prefix_len
194 && !memcmp(class->name, name, prefix_len)) {
196 char *suffix_copy = xstrdup(name + prefix_len + 1);
197 int retval = class->open(name, suffix_copy, &vconn);
200 assert(vconn->state != VCS_CONNECTING
201 || vconn->class->connect);
202 vconn->min_version = min_version;
212 vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
217 error = vconn_open(name, min_version, &vconn);
218 while (error == EAGAIN) {
219 vconn_connect_wait(vconn);
221 error = vconn_connect(vconn);
222 assert(error != EINPROGRESS);
233 /* Closes 'vconn'. */
235 vconn_close(struct vconn *vconn)
238 char *name = vconn->name;
239 (vconn->class->close)(vconn);
244 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
246 vconn_get_name(const struct vconn *vconn)
251 /* Returns the IP address of the peer, or 0 if the peer is not connected over
252 * an IP-based protocol or if its IP address is not yet known. */
254 vconn_get_ip(const struct vconn *vconn)
260 vcs_connecting(struct vconn *vconn)
262 int retval = (vconn->class->connect)(vconn);
263 assert(retval != EINPROGRESS);
265 vconn->state = VCS_SEND_HELLO;
266 } else if (retval != EAGAIN) {
267 vconn->state = VCS_DISCONNECTED;
268 vconn->error = retval;
273 vcs_send_hello(struct vconn *vconn)
278 make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
279 retval = do_send(vconn, b);
281 vconn->state = VCS_RECV_HELLO;
284 if (retval != EAGAIN) {
285 vconn->state = VCS_DISCONNECTED;
286 vconn->error = retval;
292 vcs_recv_hello(struct vconn *vconn)
297 retval = do_recv(vconn, &b);
299 struct ofp_header *oh = b->data;
301 if (oh->type == OFPT_HELLO) {
302 if (b->size > sizeof *oh) {
303 struct ds msg = DS_EMPTY_INITIALIZER;
304 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
305 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
306 VLOG_WARN_RL(&bad_ofmsg_rl, "%s", ds_cstr(&msg));
310 vconn->version = MIN(OFP_VERSION, oh->version);
311 if (vconn->version < vconn->min_version) {
312 VLOG_WARN_RL(&bad_ofmsg_rl,
313 "%s: version negotiation failed: we support "
314 "versions 0x%02x to 0x%02x inclusive but peer "
315 "supports no later than version 0x%02"PRIx8,
316 vconn->name, vconn->min_version, OFP_VERSION,
318 vconn->state = VCS_SEND_ERROR;
320 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
321 "(we support versions 0x%02x to 0x%02x inclusive, "
322 "peer no later than version 0x%02"PRIx8")",
323 vconn->name, vconn->version, vconn->min_version,
324 OFP_VERSION, oh->version);
325 vconn->state = VCS_CONNECTED;
330 char *s = ofp_to_string(b->data, b->size, 1);
331 VLOG_WARN_RL(&bad_ofmsg_rl,
332 "%s: received message while expecting hello: %s",
340 if (retval != EAGAIN) {
341 vconn->state = VCS_DISCONNECTED;
342 vconn->error = retval == EOF ? ECONNRESET : retval;
347 vcs_send_error(struct vconn *vconn)
349 struct ofp_error_msg *error;
354 snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
355 "you support no later than version 0x%02"PRIx8".",
356 vconn->min_version, OFP_VERSION, vconn->version);
357 error = make_openflow(sizeof *error, OFPT_ERROR, &b);
358 error->type = htons(OFPET_HELLO_FAILED);
359 error->code = htons(OFPHFC_INCOMPATIBLE);
360 ofpbuf_put(b, s, strlen(s));
361 update_openflow_length(b);
362 retval = do_send(vconn, b);
366 if (retval != EAGAIN) {
367 vconn->state = VCS_DISCONNECTED;
368 vconn->error = retval ? retval : EPROTO;
372 /* Tries to complete the connection on 'vconn', which must be an active
373 * vconn. If 'vconn''s connection is complete, returns 0 if the connection
374 * was successful or a positive errno value if it failed. If the
375 * connection is still in progress, returns EAGAIN. */
377 vconn_connect(struct vconn *vconn)
379 enum vconn_state last_state;
381 assert(vconn->min_version >= 0);
383 last_state = vconn->state;
384 switch (vconn->state) {
386 vcs_connecting(vconn);
390 vcs_send_hello(vconn);
394 vcs_recv_hello(vconn);
401 vcs_send_error(vconn);
404 case VCS_DISCONNECTED:
410 } while (vconn->state != last_state);
415 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
416 * vconn. If successful, stores the received message into '*msgp' and returns
417 * 0. The caller is responsible for destroying the message with
418 * ofpbuf_delete(). On failure, returns a positive errno value and stores a
419 * null pointer into '*msgp'. On normal connection close, returns EOF.
421 * vconn_recv will not block waiting for a packet to arrive. If no packets
422 * have been received, it returns EAGAIN immediately. */
424 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
426 int retval = vconn_connect(vconn);
428 retval = do_recv(vconn, msgp);
434 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
436 int retval = (vconn->class->recv)(vconn, msgp);
438 struct ofp_header *oh;
440 COVERAGE_INC(vconn_received);
441 if (VLOG_IS_DBG_ENABLED()) {
442 char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
443 VLOG_DBG_RL(&ofmsg_rl, "%s: received: %s", vconn->name, s);
447 oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
448 if (oh->version != vconn->version
449 && oh->type != OFPT_HELLO
450 && oh->type != OFPT_ERROR
451 && oh->type != OFPT_ECHO_REQUEST
452 && oh->type != OFPT_ECHO_REPLY
453 && oh->type != OFPT_VENDOR)
455 if (vconn->version < 0) {
456 VLOG_ERR_RL(&bad_ofmsg_rl,
457 "%s: received OpenFlow message type %"PRIu8" "
458 "before version negotiation complete",
459 vconn->name, oh->type);
461 VLOG_ERR_RL(&bad_ofmsg_rl,
462 "%s: received OpenFlow version 0x%02"PRIx8" "
464 vconn->name, oh->version, vconn->version);
466 ofpbuf_delete(*msgp);
476 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
477 * vconn. If successful, returns 0, in which case ownership of 'msg' is
478 * transferred to the vconn. Success does not guarantee that 'msg' has been or
479 * ever will be delivered to the peer, only that it has been queued for
482 * Returns a positive errno value on failure, in which case the caller
483 * retains ownership of 'msg'.
485 * vconn_send will not block. If 'msg' cannot be immediately accepted for
486 * transmission, it returns EAGAIN immediately. */
488 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
490 int retval = vconn_connect(vconn);
492 retval = do_send(vconn, msg);
498 do_send(struct vconn *vconn, struct ofpbuf *msg)
502 assert(msg->size >= sizeof(struct ofp_header));
503 assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
504 if (!VLOG_IS_DBG_ENABLED()) {
505 COVERAGE_INC(vconn_sent);
506 retval = (vconn->class->send)(vconn, msg);
508 char *s = ofp_to_string(msg->data, msg->size, 1);
509 retval = (vconn->class->send)(vconn, msg);
510 if (retval != EAGAIN) {
511 VLOG_DBG_RL(&ofmsg_rl, "%s: sent (%s): %s",
512 vconn->name, strerror(retval), s);
519 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
521 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
524 while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
525 vconn_send_wait(vconn);
531 /* Same as vconn_recv, except that it waits until a message is received. */
533 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
536 while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
537 vconn_recv_wait(vconn);
543 /* Waits until a message with a transaction ID matching 'xid' is recived on
544 * 'vconn'. Returns 0 if successful, in which case the reply is stored in
545 * '*replyp' for the caller to examine and free. Otherwise returns a positive
546 * errno value, or EOF, and sets '*replyp' to null.
548 * 'request' is always destroyed, regardless of the return value. */
550 vconn_recv_xid(struct vconn *vconn, uint32_t xid, struct ofpbuf **replyp)
554 struct ofpbuf *reply;
557 error = vconn_recv_block(vconn, &reply);
562 recv_xid = ((struct ofp_header *) reply->data)->xid;
563 if (xid == recv_xid) {
568 VLOG_DBG_RL(&bad_ofmsg_rl, "%s: received reply with xid %08"PRIx32
569 " != expected %08"PRIx32, vconn->name, recv_xid, xid);
570 ofpbuf_delete(reply);
574 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
575 * matching transaction ID. Returns 0 if successful, in which case the reply
576 * is stored in '*replyp' for the caller to examine and free. Otherwise
577 * returns a positive errno value, or EOF, and sets '*replyp' to null.
579 * 'request' is always destroyed, regardless of the return value. */
581 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
582 struct ofpbuf **replyp)
584 uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
588 error = vconn_send_block(vconn, request);
590 ofpbuf_delete(request);
592 return error ? error : vconn_recv_xid(vconn, send_xid, replyp);
596 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
598 assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
600 switch (vconn->state) {
617 case VCS_DISCONNECTED:
618 poll_immediate_wake();
621 (vconn->class->wait)(vconn, wait);
625 vconn_connect_wait(struct vconn *vconn)
627 vconn_wait(vconn, WAIT_CONNECT);
631 vconn_recv_wait(struct vconn *vconn)
633 vconn_wait(vconn, WAIT_RECV);
637 vconn_send_wait(struct vconn *vconn)
639 vconn_wait(vconn, WAIT_SEND);
642 /* Attempts to start listening for OpenFlow connections. 'name' is a
643 * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
644 * class's name and ARGS are vconn class-specific.
646 * Returns 0 if successful, otherwise a positive errno value. If successful,
647 * stores a pointer to the new connection in '*pvconnp', otherwise a null
650 pvconn_open(const char *name, struct pvconn **pvconnp)
655 check_vconn_classes();
658 prefix_len = strcspn(name, ":");
659 if (prefix_len == strlen(name)) {
662 for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
663 struct pvconn_class *class = pvconn_classes[i];
664 if (strlen(class->name) == prefix_len
665 && !memcmp(class->name, name, prefix_len)) {
666 char *suffix_copy = xstrdup(name + prefix_len + 1);
667 int retval = class->listen(name, suffix_copy, pvconnp);
678 /* Returns the name that was used to open 'pvconn'. The caller must not
679 * modify or free the name. */
681 pvconn_get_name(const struct pvconn *pvconn)
686 /* Closes 'pvconn'. */
688 pvconn_close(struct pvconn *pvconn)
690 if (pvconn != NULL) {
691 char *name = pvconn->name;
692 (pvconn->class->close)(pvconn);
697 /* Tries to accept a new connection on 'pvconn'. If successful, stores the new
698 * connection in '*new_vconn' and returns 0. Otherwise, returns a positive
701 * The new vconn will automatically negotiate an OpenFlow protocol version
702 * acceptable to both peers on the connection. The version negotiated will be
703 * no lower than 'min_version' and no higher than OFP_VERSION.
705 * pvconn_accept() will not block waiting for a connection. If no connection
706 * is ready to be accepted, it returns EAGAIN immediately. */
708 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
710 int retval = (pvconn->class->accept)(pvconn, new_vconn);
714 assert((*new_vconn)->state != VCS_CONNECTING
715 || (*new_vconn)->class->connect);
716 (*new_vconn)->min_version = min_version;
722 pvconn_wait(struct pvconn *pvconn)
724 (pvconn->class->wait)(pvconn);
727 /* XXX we should really use consecutive xids to avoid probabilistic
729 static inline uint32_t
732 return random_uint32();
735 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
736 * 'openflow_len', starting with an OpenFlow header with the given 'type' and
737 * an arbitrary transaction id. Allocated bytes beyond the header, if any, are
740 * The caller is responsible for freeing '*bufferp' when it is no longer
743 * The OpenFlow header length is initially set to 'openflow_len'; if the
744 * message is later extended, the length should be updated with
745 * update_openflow_length() before sending.
747 * Returns the header. */
749 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
751 *bufferp = ofpbuf_new(openflow_len);
752 return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
755 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
756 * 'openflow_len', starting with an OpenFlow header with the given 'type' and
757 * transaction id 'xid'. Allocated bytes beyond the header, if any, are
760 * The caller is responsible for freeing '*bufferp' when it is no longer
763 * The OpenFlow header length is initially set to 'openflow_len'; if the
764 * message is later extended, the length should be updated with
765 * update_openflow_length() before sending.
767 * Returns the header. */
769 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
770 struct ofpbuf **bufferp)
772 *bufferp = ofpbuf_new(openflow_len);
773 return put_openflow_xid(openflow_len, type, xid, *bufferp);
776 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
777 * with the given 'type' and an arbitrary transaction id. Allocated bytes
778 * beyond the header, if any, are zeroed.
780 * The OpenFlow header length is initially set to 'openflow_len'; if the
781 * message is later extended, the length should be updated with
782 * update_openflow_length() before sending.
784 * Returns the header. */
786 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
788 return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
791 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
792 * with the given 'type' and an transaction id 'xid'. Allocated bytes beyond
793 * the header, if any, are zeroed.
795 * The OpenFlow header length is initially set to 'openflow_len'; if the
796 * message is later extended, the length should be updated with
797 * update_openflow_length() before sending.
799 * Returns the header. */
801 put_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
802 struct ofpbuf *buffer)
804 struct ofp_header *oh;
806 assert(openflow_len >= sizeof *oh);
807 assert(openflow_len <= UINT16_MAX);
809 oh = ofpbuf_put_uninit(buffer, openflow_len);
810 oh->version = OFP_VERSION;
812 oh->length = htons(openflow_len);
814 memset(oh + 1, 0, openflow_len - sizeof *oh);
818 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
821 update_openflow_length(struct ofpbuf *buffer)
823 struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
824 oh->length = htons(buffer->size);
828 make_flow_mod(uint16_t command, const flow_t *flow, size_t actions_len)
830 struct ofp_flow_mod *ofm;
831 size_t size = sizeof *ofm + actions_len;
832 struct ofpbuf *out = ofpbuf_new(size);
833 ofm = ofpbuf_put_zeros(out, sizeof *ofm);
834 ofm->header.version = OFP_VERSION;
835 ofm->header.type = OFPT_FLOW_MOD;
836 ofm->header.length = htons(size);
837 ofm->match.wildcards = htonl(0);
838 ofm->match.in_port = htons(flow->in_port == ODPP_LOCAL ? OFPP_LOCAL
840 memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
841 memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
842 ofm->match.dl_vlan = flow->dl_vlan;
843 ofm->match.dl_type = flow->dl_type;
844 ofm->match.nw_src = flow->nw_src;
845 ofm->match.nw_dst = flow->nw_dst;
846 ofm->match.nw_proto = flow->nw_proto;
847 ofm->match.tp_src = flow->tp_src;
848 ofm->match.tp_dst = flow->tp_dst;
849 ofm->command = htons(command);
854 make_add_flow(const flow_t *flow, uint32_t buffer_id,
855 uint16_t idle_timeout, size_t actions_len)
857 struct ofpbuf *out = make_flow_mod(OFPFC_ADD, flow, actions_len);
858 struct ofp_flow_mod *ofm = out->data;
859 ofm->idle_timeout = htons(idle_timeout);
860 ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
861 ofm->buffer_id = htonl(buffer_id);
866 make_del_flow(const flow_t *flow)
868 struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, flow, 0);
869 struct ofp_flow_mod *ofm = out->data;
870 ofm->out_port = htons(OFPP_NONE);
875 make_add_simple_flow(const flow_t *flow,
876 uint32_t buffer_id, uint16_t out_port,
877 uint16_t idle_timeout)
879 struct ofp_action_output *oao;
880 struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout,
882 oao = ofpbuf_put_zeros(buffer, sizeof *oao);
883 oao->type = htons(OFPAT_OUTPUT);
884 oao->len = htons(sizeof *oao);
885 oao->port = htons(out_port);
890 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
892 const struct ofp_action_header *actions, size_t n_actions)
894 size_t actions_len = n_actions * sizeof *actions;
895 struct ofp_packet_out *opo;
896 size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
897 struct ofpbuf *out = ofpbuf_new(size);
899 opo = ofpbuf_put_uninit(out, sizeof *opo);
900 opo->header.version = OFP_VERSION;
901 opo->header.type = OFPT_PACKET_OUT;
902 opo->header.length = htons(size);
903 opo->header.xid = htonl(0);
904 opo->buffer_id = htonl(buffer_id);
905 opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
906 opo->actions_len = htons(actions_len);
907 ofpbuf_put(out, actions, actions_len);
909 ofpbuf_put(out, packet->data, packet->size);
915 make_unbuffered_packet_out(const struct ofpbuf *packet,
916 uint16_t in_port, uint16_t out_port)
918 struct ofp_action_output action;
919 action.type = htons(OFPAT_OUTPUT);
920 action.len = htons(sizeof action);
921 action.port = htons(out_port);
922 return make_packet_out(packet, UINT32_MAX, in_port,
923 (struct ofp_action_header *) &action, 1);
927 make_buffered_packet_out(uint32_t buffer_id,
928 uint16_t in_port, uint16_t out_port)
930 struct ofp_action_output action;
931 action.type = htons(OFPAT_OUTPUT);
932 action.len = htons(sizeof action);
933 action.port = htons(out_port);
934 return make_packet_out(NULL, buffer_id, in_port,
935 (struct ofp_action_header *) &action, 1);
938 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
940 make_echo_request(void)
942 struct ofp_header *rq;
943 struct ofpbuf *out = ofpbuf_new(sizeof *rq);
944 rq = ofpbuf_put_uninit(out, sizeof *rq);
945 rq->version = OFP_VERSION;
946 rq->type = OFPT_ECHO_REQUEST;
947 rq->length = htons(sizeof *rq);
952 /* Creates and returns an OFPT_ECHO_REPLY message matching the
953 * OFPT_ECHO_REQUEST message in 'rq'. */
955 make_echo_reply(const struct ofp_header *rq)
957 size_t size = ntohs(rq->length);
958 struct ofpbuf *out = ofpbuf_new(size);
959 struct ofp_header *reply = ofpbuf_put(out, rq, size);
960 reply->type = OFPT_ECHO_REPLY;
965 check_message_type(uint8_t got_type, uint8_t want_type)
967 if (got_type != want_type) {
968 char *want_type_name = ofp_message_type_to_string(want_type);
969 char *got_type_name = ofp_message_type_to_string(got_type);
970 VLOG_WARN_RL(&bad_ofmsg_rl,
971 "received bad message type %s (expected %s)",
972 got_type_name, want_type_name);
973 free(want_type_name);
975 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
980 /* Checks that 'msg' has type 'type' and that it is exactly 'size' bytes long.
981 * Returns 0 if the checks pass, otherwise an OpenFlow error code (produced
982 * with ofp_mkerr()). */
984 check_ofp_message(const struct ofp_header *msg, uint8_t type, size_t size)
989 error = check_message_type(msg->type, type);
994 got_size = ntohs(msg->length);
995 if (got_size != size) {
996 char *type_name = ofp_message_type_to_string(type);
997 VLOG_WARN_RL(&bad_ofmsg_rl,
998 "received %s message of length %"PRIu16" (expected %zu)",
999 type_name, got_size, size);
1001 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1007 /* Checks that 'msg' has type 'type' and that 'msg' is 'size' plus a
1008 * nonnegative integer multiple of 'array_elt_size' bytes long. Returns 0 if
1009 * the checks pass, otherwise an OpenFlow error code (produced with
1012 * If 'n_array_elts' is nonnull, then '*n_array_elts' is set to the number of
1013 * 'array_elt_size' blocks in 'msg' past the first 'min_size' bytes, when
1016 check_ofp_message_array(const struct ofp_header *msg, uint8_t type,
1017 size_t min_size, size_t array_elt_size,
1018 size_t *n_array_elts)
1023 assert(array_elt_size);
1025 error = check_message_type(msg->type, type);
1030 got_size = ntohs(msg->length);
1031 if (got_size < min_size) {
1032 char *type_name = ofp_message_type_to_string(type);
1033 VLOG_WARN_RL(&bad_ofmsg_rl, "received %s message of length %"PRIu16" "
1034 "(expected at least %zu)",
1035 type_name, got_size, min_size);
1037 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1039 if ((got_size - min_size) % array_elt_size) {
1040 char *type_name = ofp_message_type_to_string(type);
1041 VLOG_WARN_RL(&bad_ofmsg_rl,
1042 "received %s message of bad length %"PRIu16": the "
1043 "excess over %zu (%zu) is not evenly divisible by %zu "
1044 "(remainder is %zu)",
1045 type_name, got_size, min_size, got_size - min_size,
1046 array_elt_size, (got_size - min_size) % array_elt_size);
1048 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1051 *n_array_elts = (got_size - min_size) / array_elt_size;
1057 check_ofp_packet_out(const struct ofp_header *oh, struct ofpbuf *data,
1058 int *n_actionsp, int max_ports)
1060 const struct ofp_packet_out *opo;
1061 unsigned int actions_len, n_actions;
1066 error = check_ofp_message_array(oh, OFPT_PACKET_OUT,
1067 sizeof *opo, 1, &extra);
1071 opo = (const struct ofp_packet_out *) oh;
1073 actions_len = ntohs(opo->actions_len);
1074 if (actions_len > extra) {
1075 VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %zu bytes of actions "
1076 "but message has room for only %zu bytes",
1077 actions_len, extra);
1078 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1080 if (actions_len % sizeof(union ofp_action)) {
1081 VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %zu bytes of actions, "
1082 "which is not a multiple of %zu",
1083 actions_len, sizeof(union ofp_action));
1084 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1087 n_actions = actions_len / sizeof(union ofp_action);
1088 error = validate_actions((const union ofp_action *) opo->actions,
1089 n_actions, max_ports);
1094 data->data = (void *) &opo->actions[n_actions];
1095 data->size = extra - actions_len;
1096 *n_actionsp = n_actions;
1100 const struct ofp_flow_stats *
1101 flow_stats_first(struct flow_stats_iterator *iter,
1102 const struct ofp_stats_reply *osr)
1104 iter->pos = osr->body;
1105 iter->end = osr->body + (ntohs(osr->header.length)
1106 - offsetof(struct ofp_stats_reply, body));
1107 return flow_stats_next(iter);
1110 const struct ofp_flow_stats *
1111 flow_stats_next(struct flow_stats_iterator *iter)
1113 ptrdiff_t bytes_left = iter->end - iter->pos;
1114 const struct ofp_flow_stats *fs;
1117 if (bytes_left < sizeof *fs) {
1118 if (bytes_left != 0) {
1119 VLOG_WARN_RL(&bad_ofmsg_rl,
1120 "%td leftover bytes in flow stats reply", bytes_left);
1125 fs = (const void *) iter->pos;
1126 length = ntohs(fs->length);
1127 if (length < sizeof *fs) {
1128 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
1129 "min %zu", length, sizeof *fs);
1131 } else if (length > bytes_left) {
1132 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
1133 "bytes left", length, bytes_left);
1135 } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
1136 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
1137 "left over in final action", length,
1138 (length - sizeof *fs) % sizeof fs->actions[0]);
1141 iter->pos += length;
1145 /* Alignment of ofp_actions. */
1146 #define ACTION_ALIGNMENT 8
1149 check_action_exact_len(const union ofp_action *a, unsigned int len,
1150 unsigned int required_len)
1152 if (len != required_len) {
1153 VLOG_DBG_RL(&bad_ofmsg_rl,
1154 "action %u has invalid length %"PRIu16" (must be %u)\n",
1155 a->type, ntohs(a->header.len), required_len);
1156 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1162 check_action_port(int port, int max_ports)
1170 case OFPP_CONTROLLER:
1175 if (port >= 0 && port < max_ports) {
1178 VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1179 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1184 check_nicira_action(const union ofp_action *a, unsigned int len)
1186 const struct nx_action_header *nah;
1189 VLOG_DBG_RL(&bad_ofmsg_rl,
1190 "Nicira vendor action only %u bytes", len);
1191 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1193 nah = (const struct nx_action_header *) a;
1195 switch (ntohs(nah->subtype)) {
1196 case NXAST_RESUBMIT:
1197 return check_action_exact_len(a, len, 16);
1199 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1204 check_action(const union ofp_action *a, unsigned int len, int max_ports)
1210 error = check_action_port(ntohs(a->output.port), max_ports);
1214 return check_action_exact_len(a, len, 8);
1216 case OFPAT_SET_VLAN_VID:
1217 case OFPAT_SET_VLAN_PCP:
1218 case OFPAT_STRIP_VLAN:
1219 case OFPAT_SET_NW_SRC:
1220 case OFPAT_SET_NW_DST:
1221 case OFPAT_SET_TP_SRC:
1222 case OFPAT_SET_TP_DST:
1223 return check_action_exact_len(a, len, 8);
1225 case OFPAT_SET_DL_SRC:
1226 case OFPAT_SET_DL_DST:
1227 return check_action_exact_len(a, len, 16);
1230 if (a->vendor.vendor == htonl(NX_VENDOR_ID)) {
1231 return check_nicira_action(a, len);
1233 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR);
1238 VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16, a->type);
1239 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1243 VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
1244 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1246 if (len % ACTION_ALIGNMENT) {
1247 VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple of %d",
1248 len, ACTION_ALIGNMENT);
1249 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1255 validate_actions(const union ofp_action *actions, size_t n_actions,
1258 const union ofp_action *a;
1260 for (a = actions; a < &actions[n_actions]; ) {
1261 unsigned int len = ntohs(a->header.len);
1262 unsigned int n_slots = len / ACTION_ALIGNMENT;
1263 unsigned int slots_left = &actions[n_actions] - a;
1266 if (n_slots > slots_left) {
1267 VLOG_DBG_RL(&bad_ofmsg_rl,
1268 "action requires %u slots but only %td remain",
1269 n_slots, slots_left);
1270 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1272 error = check_action(a, len, max_ports);
1281 /* The set of actions must either come from a trusted source or have been
1282 * previously validated with validate_actions(). */
1283 const union ofp_action *
1284 actions_first(struct actions_iterator *iter,
1285 const union ofp_action *oa, size_t n_actions)
1288 iter->end = oa + n_actions;
1289 return actions_next(iter);
1292 const union ofp_action *
1293 actions_next(struct actions_iterator *iter)
1295 if (iter->pos < iter->end) {
1296 const union ofp_action *a = iter->pos;
1297 unsigned int len = ntohs(a->header.len);
1298 iter->pos += len / ACTION_ALIGNMENT;
1306 normalize_match(struct ofp_match *m)
1308 enum { OFPFW_NW = OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO };
1309 enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
1312 wc = ntohl(m->wildcards) & OFPFW_ALL;
1313 if (wc & OFPFW_DL_TYPE) {
1316 /* Can't sensibly m on network or transport headers if the
1317 * data link type is unknown. */
1318 wc |= OFPFW_NW | OFPFW_TP;
1319 m->nw_src = m->nw_dst = m->nw_proto = 0;
1320 m->tp_src = m->tp_dst = 0;
1321 } else if (m->dl_type == htons(ETH_TYPE_IP)) {
1322 if (wc & OFPFW_NW_PROTO) {
1325 /* Can't sensibly m on transport headers if the network
1326 * protocol is unknown. */
1328 m->tp_src = m->tp_dst = 0;
1329 } else if (m->nw_proto == IPPROTO_TCP ||
1330 m->nw_proto == IPPROTO_UDP ||
1331 m->nw_proto == IPPROTO_ICMP) {
1332 if (wc & OFPFW_TP_SRC) {
1335 if (wc & OFPFW_TP_DST) {
1339 /* Transport layer fields will always be extracted as zeros, so we
1340 * can do an exact-m on those values. */
1342 m->tp_src = m->tp_dst = 0;
1344 if (wc & OFPFW_NW_SRC_MASK) {
1345 m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
1347 if (wc & OFPFW_NW_DST_MASK) {
1348 m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
1351 /* Network and transport layer fields will always be extracted as
1352 * zeros, so we can do an exact-m on those values. */
1353 wc &= ~(OFPFW_NW | OFPFW_TP);
1354 m->nw_proto = m->nw_src = m->nw_dst = 0;
1355 m->tp_src = m->tp_dst = 0;
1357 if (wc & OFPFW_DL_SRC) {
1358 memset(m->dl_src, 0, sizeof m->dl_src);
1360 if (wc & OFPFW_DL_DST) {
1361 memset(m->dl_dst, 0, sizeof m->dl_dst);
1363 m->wildcards = htonl(wc);
1367 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
1368 uint32_t ip, const char *name, bool reconnectable)
1370 vconn->class = class;
1371 vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
1372 : !connect_status ? VCS_SEND_HELLO
1373 : VCS_DISCONNECTED);
1374 vconn->error = connect_status;
1375 vconn->version = -1;
1376 vconn->min_version = -1;
1378 vconn->name = xstrdup(name);
1379 vconn->reconnectable = reconnectable;
1383 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
1386 pvconn->class = class;
1387 pvconn->name = xstrdup(name);