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 /* Attempts to connect to an OpenFlow device. 'name' is a connection name in
168 * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
169 * are vconn class-specific.
171 * The vconn will automatically negotiate an OpenFlow protocol version
172 * acceptable to both peers on the connection. The version negotiated will be
173 * no lower than 'min_version' and no higher than OFP_VERSION.
175 * Returns 0 if successful, otherwise a positive errno value. If successful,
176 * stores a pointer to the new connection in '*vconnp', otherwise a null
179 vconn_open(const char *name, int min_version, struct vconn **vconnp)
184 COVERAGE_INC(vconn_open);
185 check_vconn_classes();
188 prefix_len = strcspn(name, ":");
189 if (prefix_len == strlen(name)) {
192 for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
193 struct vconn_class *class = vconn_classes[i];
194 if (strlen(class->name) == prefix_len
195 && !memcmp(class->name, name, prefix_len)) {
197 char *suffix_copy = xstrdup(name + prefix_len + 1);
198 int retval = class->open(name, suffix_copy, &vconn);
201 assert(vconn->state != VCS_CONNECTING
202 || vconn->class->connect);
203 vconn->min_version = min_version;
212 /* Allows 'vconn' to perform maintenance activities, such as flushing output
215 vconn_run(struct vconn *vconn)
217 if (vconn->class->run) {
218 (vconn->class->run)(vconn);
222 /* Arranges for the poll loop to wake up when 'vconn' needs to perform
223 * maintenance activities. */
225 vconn_run_wait(struct vconn *vconn)
227 if (vconn->class->run_wait) {
228 (vconn->class->run_wait)(vconn);
233 vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
238 error = vconn_open(name, min_version, &vconn);
239 while (error == EAGAIN) {
241 vconn_run_wait(vconn);
242 vconn_connect_wait(vconn);
244 error = vconn_connect(vconn);
245 assert(error != EINPROGRESS);
256 /* Closes 'vconn'. */
258 vconn_close(struct vconn *vconn)
261 char *name = vconn->name;
262 (vconn->class->close)(vconn);
267 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
269 vconn_get_name(const struct vconn *vconn)
274 /* Returns the IP address of the peer, or 0 if the peer is not connected over
275 * an IP-based protocol or if its IP address is not yet known. */
277 vconn_get_remote_ip(const struct vconn *vconn)
279 return vconn->remote_ip;
282 /* Returns the transport port of the peer, or 0 if the connection does not
283 * contain a port or if the port is not yet known. */
285 vconn_get_remote_port(const struct vconn *vconn)
287 return vconn->remote_port;
290 /* Returns the IP address used to connect to the peer, or 0 if the
291 * connection is not an IP-based protocol or if its IP address is not
294 vconn_get_local_ip(const struct vconn *vconn)
296 return vconn->local_ip;
299 /* Returns the transport port used to connect to the peer, or 0 if the
300 * connection does not contain a port or if the port is not yet known. */
302 vconn_get_local_port(const struct vconn *vconn)
304 return vconn->local_port;
308 vcs_connecting(struct vconn *vconn)
310 int retval = (vconn->class->connect)(vconn);
311 assert(retval != EINPROGRESS);
313 vconn->state = VCS_SEND_HELLO;
314 } else if (retval != EAGAIN) {
315 vconn->state = VCS_DISCONNECTED;
316 vconn->error = retval;
321 vcs_send_hello(struct vconn *vconn)
326 make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
327 retval = do_send(vconn, b);
329 vconn->state = VCS_RECV_HELLO;
332 if (retval != EAGAIN) {
333 vconn->state = VCS_DISCONNECTED;
334 vconn->error = retval;
340 vcs_recv_hello(struct vconn *vconn)
345 retval = do_recv(vconn, &b);
347 struct ofp_header *oh = b->data;
349 if (oh->type == OFPT_HELLO) {
350 if (b->size > sizeof *oh) {
351 struct ds msg = DS_EMPTY_INITIALIZER;
352 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
353 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
354 VLOG_WARN_RL(&bad_ofmsg_rl, "%s", ds_cstr(&msg));
358 vconn->version = MIN(OFP_VERSION, oh->version);
359 if (vconn->version < vconn->min_version) {
360 VLOG_WARN_RL(&bad_ofmsg_rl,
361 "%s: version negotiation failed: we support "
362 "versions 0x%02x to 0x%02x inclusive but peer "
363 "supports no later than version 0x%02"PRIx8,
364 vconn->name, vconn->min_version, OFP_VERSION,
366 vconn->state = VCS_SEND_ERROR;
368 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
369 "(we support versions 0x%02x to 0x%02x inclusive, "
370 "peer no later than version 0x%02"PRIx8")",
371 vconn->name, vconn->version, vconn->min_version,
372 OFP_VERSION, oh->version);
373 vconn->state = VCS_CONNECTED;
378 char *s = ofp_to_string(b->data, b->size, 1);
379 VLOG_WARN_RL(&bad_ofmsg_rl,
380 "%s: received message while expecting hello: %s",
388 if (retval != EAGAIN) {
389 vconn->state = VCS_DISCONNECTED;
390 vconn->error = retval == EOF ? ECONNRESET : retval;
395 vcs_send_error(struct vconn *vconn)
397 struct ofp_error_msg *error;
402 snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
403 "you support no later than version 0x%02"PRIx8".",
404 vconn->min_version, OFP_VERSION, vconn->version);
405 error = make_openflow(sizeof *error, OFPT_ERROR, &b);
406 error->type = htons(OFPET_HELLO_FAILED);
407 error->code = htons(OFPHFC_INCOMPATIBLE);
408 ofpbuf_put(b, s, strlen(s));
409 update_openflow_length(b);
410 retval = do_send(vconn, b);
414 if (retval != EAGAIN) {
415 vconn->state = VCS_DISCONNECTED;
416 vconn->error = retval ? retval : EPROTO;
420 /* Tries to complete the connection on 'vconn', which must be an active
421 * vconn. If 'vconn''s connection is complete, returns 0 if the connection
422 * was successful or a positive errno value if it failed. If the
423 * connection is still in progress, returns EAGAIN. */
425 vconn_connect(struct vconn *vconn)
427 enum vconn_state last_state;
429 assert(vconn->min_version >= 0);
431 last_state = vconn->state;
432 switch (vconn->state) {
434 vcs_connecting(vconn);
438 vcs_send_hello(vconn);
442 vcs_recv_hello(vconn);
449 vcs_send_error(vconn);
452 case VCS_DISCONNECTED:
458 } while (vconn->state != last_state);
463 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
464 * vconn. If successful, stores the received message into '*msgp' and returns
465 * 0. The caller is responsible for destroying the message with
466 * ofpbuf_delete(). On failure, returns a positive errno value and stores a
467 * null pointer into '*msgp'. On normal connection close, returns EOF.
469 * vconn_recv will not block waiting for a packet to arrive. If no packets
470 * have been received, it returns EAGAIN immediately. */
472 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
474 int retval = vconn_connect(vconn);
476 retval = do_recv(vconn, msgp);
482 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
484 int retval = (vconn->class->recv)(vconn, msgp);
486 struct ofp_header *oh;
488 COVERAGE_INC(vconn_received);
489 if (VLOG_IS_DBG_ENABLED()) {
490 char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
491 VLOG_DBG_RL(&ofmsg_rl, "%s: received: %s", vconn->name, s);
495 oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
496 if (oh->version != vconn->version
497 && oh->type != OFPT_HELLO
498 && oh->type != OFPT_ERROR
499 && oh->type != OFPT_ECHO_REQUEST
500 && oh->type != OFPT_ECHO_REPLY
501 && oh->type != OFPT_VENDOR)
503 if (vconn->version < 0) {
504 VLOG_ERR_RL(&bad_ofmsg_rl,
505 "%s: received OpenFlow message type %"PRIu8" "
506 "before version negotiation complete",
507 vconn->name, oh->type);
509 VLOG_ERR_RL(&bad_ofmsg_rl,
510 "%s: received OpenFlow version 0x%02"PRIx8" "
512 vconn->name, oh->version, vconn->version);
514 ofpbuf_delete(*msgp);
524 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
525 * vconn. If successful, returns 0, in which case ownership of 'msg' is
526 * transferred to the vconn. Success does not guarantee that 'msg' has been or
527 * ever will be delivered to the peer, only that it has been queued for
530 * Returns a positive errno value on failure, in which case the caller
531 * retains ownership of 'msg'.
533 * vconn_send will not block. If 'msg' cannot be immediately accepted for
534 * transmission, it returns EAGAIN immediately. */
536 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
538 int retval = vconn_connect(vconn);
540 retval = do_send(vconn, msg);
546 do_send(struct vconn *vconn, struct ofpbuf *msg)
550 assert(msg->size >= sizeof(struct ofp_header));
551 assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
552 if (!VLOG_IS_DBG_ENABLED()) {
553 COVERAGE_INC(vconn_sent);
554 retval = (vconn->class->send)(vconn, msg);
556 char *s = ofp_to_string(msg->data, msg->size, 1);
557 retval = (vconn->class->send)(vconn, msg);
558 if (retval != EAGAIN) {
559 VLOG_DBG_RL(&ofmsg_rl, "%s: sent (%s): %s",
560 vconn->name, strerror(retval), s);
567 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
569 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
572 while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
574 vconn_run_wait(vconn);
575 vconn_send_wait(vconn);
581 /* Same as vconn_recv, except that it waits until a message is received. */
583 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
586 while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
588 vconn_run_wait(vconn);
589 vconn_recv_wait(vconn);
595 /* Waits until a message with a transaction ID matching 'xid' is recived on
596 * 'vconn'. Returns 0 if successful, in which case the reply is stored in
597 * '*replyp' for the caller to examine and free. Otherwise returns a positive
598 * errno value, or EOF, and sets '*replyp' to null.
600 * 'request' is always destroyed, regardless of the return value. */
602 vconn_recv_xid(struct vconn *vconn, uint32_t xid, struct ofpbuf **replyp)
606 struct ofpbuf *reply;
609 error = vconn_recv_block(vconn, &reply);
614 recv_xid = ((struct ofp_header *) reply->data)->xid;
615 if (xid == recv_xid) {
620 VLOG_DBG_RL(&bad_ofmsg_rl, "%s: received reply with xid %08"PRIx32
621 " != expected %08"PRIx32, vconn->name, recv_xid, xid);
622 ofpbuf_delete(reply);
626 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
627 * matching transaction ID. Returns 0 if successful, in which case the reply
628 * is stored in '*replyp' for the caller to examine and free. Otherwise
629 * returns a positive errno value, or EOF, and sets '*replyp' to null.
631 * 'request' is always destroyed, regardless of the return value. */
633 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
634 struct ofpbuf **replyp)
636 uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
640 error = vconn_send_block(vconn, request);
642 ofpbuf_delete(request);
644 return error ? error : vconn_recv_xid(vconn, send_xid, replyp);
648 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
650 assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
652 switch (vconn->state) {
669 case VCS_DISCONNECTED:
670 poll_immediate_wake();
673 (vconn->class->wait)(vconn, wait);
677 vconn_connect_wait(struct vconn *vconn)
679 vconn_wait(vconn, WAIT_CONNECT);
683 vconn_recv_wait(struct vconn *vconn)
685 vconn_wait(vconn, WAIT_RECV);
689 vconn_send_wait(struct vconn *vconn)
691 vconn_wait(vconn, WAIT_SEND);
694 /* Attempts to start listening for OpenFlow connections. 'name' is a
695 * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
696 * class's name and ARGS are vconn class-specific.
698 * Returns 0 if successful, otherwise a positive errno value. If successful,
699 * stores a pointer to the new connection in '*pvconnp', otherwise a null
702 pvconn_open(const char *name, struct pvconn **pvconnp)
707 check_vconn_classes();
710 prefix_len = strcspn(name, ":");
711 if (prefix_len == strlen(name)) {
714 for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
715 struct pvconn_class *class = pvconn_classes[i];
716 if (strlen(class->name) == prefix_len
717 && !memcmp(class->name, name, prefix_len)) {
718 char *suffix_copy = xstrdup(name + prefix_len + 1);
719 int retval = class->listen(name, suffix_copy, pvconnp);
730 /* Returns the name that was used to open 'pvconn'. The caller must not
731 * modify or free the name. */
733 pvconn_get_name(const struct pvconn *pvconn)
738 /* Closes 'pvconn'. */
740 pvconn_close(struct pvconn *pvconn)
742 if (pvconn != NULL) {
743 char *name = pvconn->name;
744 (pvconn->class->close)(pvconn);
749 /* Tries to accept a new connection on 'pvconn'. If successful, stores the new
750 * connection in '*new_vconn' and returns 0. Otherwise, returns a positive
753 * The new vconn will automatically negotiate an OpenFlow protocol version
754 * acceptable to both peers on the connection. The version negotiated will be
755 * no lower than 'min_version' and no higher than OFP_VERSION.
757 * pvconn_accept() will not block waiting for a connection. If no connection
758 * is ready to be accepted, it returns EAGAIN immediately. */
760 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
762 int retval = (pvconn->class->accept)(pvconn, new_vconn);
766 assert((*new_vconn)->state != VCS_CONNECTING
767 || (*new_vconn)->class->connect);
768 (*new_vconn)->min_version = min_version;
774 pvconn_wait(struct pvconn *pvconn)
776 (pvconn->class->wait)(pvconn);
779 /* XXX we should really use consecutive xids to avoid probabilistic
781 static inline uint32_t
784 return random_uint32();
787 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
788 * 'openflow_len', starting with an OpenFlow header with the given 'type' and
789 * an arbitrary transaction id. Allocated bytes beyond the header, if any, are
792 * The caller is responsible for freeing '*bufferp' when it is no longer
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 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
803 *bufferp = ofpbuf_new(openflow_len);
804 return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
807 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
808 * 'openflow_len', starting with an OpenFlow header with the given 'type' and
809 * transaction id 'xid'. Allocated bytes beyond the header, if any, are
812 * The caller is responsible for freeing '*bufferp' when it is no longer
815 * The OpenFlow header length is initially set to 'openflow_len'; if the
816 * message is later extended, the length should be updated with
817 * update_openflow_length() before sending.
819 * Returns the header. */
821 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
822 struct ofpbuf **bufferp)
824 *bufferp = ofpbuf_new(openflow_len);
825 return put_openflow_xid(openflow_len, type, xid, *bufferp);
828 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
829 * with the given 'type' and an arbitrary transaction id. Allocated bytes
830 * beyond the header, if any, are zeroed.
832 * The OpenFlow header length is initially set to 'openflow_len'; if the
833 * message is later extended, the length should be updated with
834 * update_openflow_length() before sending.
836 * Returns the header. */
838 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
840 return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
843 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
844 * with the given 'type' and an transaction id 'xid'. Allocated bytes beyond
845 * the header, if any, are zeroed.
847 * The OpenFlow header length is initially set to 'openflow_len'; if the
848 * message is later extended, the length should be updated with
849 * update_openflow_length() before sending.
851 * Returns the header. */
853 put_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
854 struct ofpbuf *buffer)
856 struct ofp_header *oh;
858 assert(openflow_len >= sizeof *oh);
859 assert(openflow_len <= UINT16_MAX);
861 oh = ofpbuf_put_uninit(buffer, openflow_len);
862 oh->version = OFP_VERSION;
864 oh->length = htons(openflow_len);
866 memset(oh + 1, 0, openflow_len - sizeof *oh);
870 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
873 update_openflow_length(struct ofpbuf *buffer)
875 struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
876 oh->length = htons(buffer->size);
880 make_flow_mod(uint16_t command, const flow_t *flow, size_t actions_len)
882 struct ofp_flow_mod *ofm;
883 size_t size = sizeof *ofm + actions_len;
884 struct ofpbuf *out = ofpbuf_new(size);
885 ofm = ofpbuf_put_zeros(out, sizeof *ofm);
886 ofm->header.version = OFP_VERSION;
887 ofm->header.type = OFPT_FLOW_MOD;
888 ofm->header.length = htons(size);
889 ofm->match.wildcards = htonl(0);
890 ofm->match.in_port = htons(flow->in_port == ODPP_LOCAL ? OFPP_LOCAL
892 memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
893 memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
894 ofm->match.dl_vlan = flow->dl_vlan;
895 ofm->match.dl_type = flow->dl_type;
896 ofm->match.nw_src = flow->nw_src;
897 ofm->match.nw_dst = flow->nw_dst;
898 ofm->match.nw_proto = flow->nw_proto;
899 ofm->match.tp_src = flow->tp_src;
900 ofm->match.tp_dst = flow->tp_dst;
901 ofm->command = htons(command);
906 make_add_flow(const flow_t *flow, uint32_t buffer_id,
907 uint16_t idle_timeout, size_t actions_len)
909 struct ofpbuf *out = make_flow_mod(OFPFC_ADD, flow, actions_len);
910 struct ofp_flow_mod *ofm = out->data;
911 ofm->idle_timeout = htons(idle_timeout);
912 ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
913 ofm->buffer_id = htonl(buffer_id);
918 make_del_flow(const flow_t *flow)
920 struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, flow, 0);
921 struct ofp_flow_mod *ofm = out->data;
922 ofm->out_port = htons(OFPP_NONE);
927 make_add_simple_flow(const flow_t *flow,
928 uint32_t buffer_id, uint16_t out_port,
929 uint16_t idle_timeout)
931 struct ofp_action_output *oao;
932 struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout,
934 oao = ofpbuf_put_zeros(buffer, sizeof *oao);
935 oao->type = htons(OFPAT_OUTPUT);
936 oao->len = htons(sizeof *oao);
937 oao->port = htons(out_port);
942 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
943 const struct ofpbuf *payload, int max_send_len)
945 struct ofp_packet_in *opi;
949 send_len = MIN(max_send_len, payload->size);
950 buf = ofpbuf_new(sizeof *opi + send_len);
951 opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
952 OFPT_PACKET_IN, 0, buf);
953 opi->buffer_id = htonl(buffer_id);
954 opi->total_len = htons(payload->size);
955 opi->in_port = htons(in_port);
956 opi->reason = reason;
957 ofpbuf_put(buf, payload->data, send_len);
958 update_openflow_length(buf);
964 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
966 const struct ofp_action_header *actions, size_t n_actions)
968 size_t actions_len = n_actions * sizeof *actions;
969 struct ofp_packet_out *opo;
970 size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
971 struct ofpbuf *out = ofpbuf_new(size);
973 opo = ofpbuf_put_uninit(out, sizeof *opo);
974 opo->header.version = OFP_VERSION;
975 opo->header.type = OFPT_PACKET_OUT;
976 opo->header.length = htons(size);
977 opo->header.xid = htonl(0);
978 opo->buffer_id = htonl(buffer_id);
979 opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
980 opo->actions_len = htons(actions_len);
981 ofpbuf_put(out, actions, actions_len);
983 ofpbuf_put(out, packet->data, packet->size);
989 make_unbuffered_packet_out(const struct ofpbuf *packet,
990 uint16_t in_port, uint16_t out_port)
992 struct ofp_action_output action;
993 action.type = htons(OFPAT_OUTPUT);
994 action.len = htons(sizeof action);
995 action.port = htons(out_port);
996 return make_packet_out(packet, UINT32_MAX, in_port,
997 (struct ofp_action_header *) &action, 1);
1001 make_buffered_packet_out(uint32_t buffer_id,
1002 uint16_t in_port, uint16_t out_port)
1004 struct ofp_action_output action;
1005 action.type = htons(OFPAT_OUTPUT);
1006 action.len = htons(sizeof action);
1007 action.port = htons(out_port);
1008 return make_packet_out(NULL, buffer_id, in_port,
1009 (struct ofp_action_header *) &action, 1);
1012 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1014 make_echo_request(void)
1016 struct ofp_header *rq;
1017 struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1018 rq = ofpbuf_put_uninit(out, sizeof *rq);
1019 rq->version = OFP_VERSION;
1020 rq->type = OFPT_ECHO_REQUEST;
1021 rq->length = htons(sizeof *rq);
1026 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1027 * OFPT_ECHO_REQUEST message in 'rq'. */
1029 make_echo_reply(const struct ofp_header *rq)
1031 size_t size = ntohs(rq->length);
1032 struct ofpbuf *out = ofpbuf_new(size);
1033 struct ofp_header *reply = ofpbuf_put(out, rq, size);
1034 reply->type = OFPT_ECHO_REPLY;
1039 check_message_type(uint8_t got_type, uint8_t want_type)
1041 if (got_type != want_type) {
1042 char *want_type_name = ofp_message_type_to_string(want_type);
1043 char *got_type_name = ofp_message_type_to_string(got_type);
1044 VLOG_WARN_RL(&bad_ofmsg_rl,
1045 "received bad message type %s (expected %s)",
1046 got_type_name, want_type_name);
1047 free(want_type_name);
1048 free(got_type_name);
1049 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
1054 /* Checks that 'msg' has type 'type' and that it is exactly 'size' bytes long.
1055 * Returns 0 if the checks pass, otherwise an OpenFlow error code (produced
1056 * with ofp_mkerr()). */
1058 check_ofp_message(const struct ofp_header *msg, uint8_t type, size_t size)
1063 error = check_message_type(msg->type, type);
1068 got_size = ntohs(msg->length);
1069 if (got_size != size) {
1070 char *type_name = ofp_message_type_to_string(type);
1071 VLOG_WARN_RL(&bad_ofmsg_rl,
1072 "received %s message of length %zu (expected %zu)",
1073 type_name, got_size, size);
1075 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1081 /* Checks that 'msg' has type 'type' and that 'msg' is 'size' plus a
1082 * nonnegative integer multiple of 'array_elt_size' bytes long. Returns 0 if
1083 * the checks pass, otherwise an OpenFlow error code (produced with
1086 * If 'n_array_elts' is nonnull, then '*n_array_elts' is set to the number of
1087 * 'array_elt_size' blocks in 'msg' past the first 'min_size' bytes, when
1090 check_ofp_message_array(const struct ofp_header *msg, uint8_t type,
1091 size_t min_size, size_t array_elt_size,
1092 size_t *n_array_elts)
1097 assert(array_elt_size);
1099 error = check_message_type(msg->type, type);
1104 got_size = ntohs(msg->length);
1105 if (got_size < min_size) {
1106 char *type_name = ofp_message_type_to_string(type);
1107 VLOG_WARN_RL(&bad_ofmsg_rl, "received %s message of length %zu "
1108 "(expected at least %zu)",
1109 type_name, got_size, min_size);
1111 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1113 if ((got_size - min_size) % array_elt_size) {
1114 char *type_name = ofp_message_type_to_string(type);
1115 VLOG_WARN_RL(&bad_ofmsg_rl,
1116 "received %s message of bad length %zu: the "
1117 "excess over %zu (%zu) is not evenly divisible by %zu "
1118 "(remainder is %zu)",
1119 type_name, got_size, min_size, got_size - min_size,
1120 array_elt_size, (got_size - min_size) % array_elt_size);
1122 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1125 *n_array_elts = (got_size - min_size) / array_elt_size;
1131 check_ofp_packet_out(const struct ofp_header *oh, struct ofpbuf *data,
1132 int *n_actionsp, int max_ports)
1134 const struct ofp_packet_out *opo;
1135 unsigned int actions_len, n_actions;
1140 error = check_ofp_message_array(oh, OFPT_PACKET_OUT,
1141 sizeof *opo, 1, &extra);
1145 opo = (const struct ofp_packet_out *) oh;
1147 actions_len = ntohs(opo->actions_len);
1148 if (actions_len > extra) {
1149 VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %u bytes of actions "
1150 "but message has room for only %zu bytes",
1151 actions_len, extra);
1152 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1154 if (actions_len % sizeof(union ofp_action)) {
1155 VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %u bytes of actions, "
1156 "which is not a multiple of %zu",
1157 actions_len, sizeof(union ofp_action));
1158 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1161 n_actions = actions_len / sizeof(union ofp_action);
1162 error = validate_actions((const union ofp_action *) opo->actions,
1163 n_actions, max_ports);
1168 data->data = (void *) &opo->actions[n_actions];
1169 data->size = extra - actions_len;
1170 *n_actionsp = n_actions;
1174 const struct ofp_flow_stats *
1175 flow_stats_first(struct flow_stats_iterator *iter,
1176 const struct ofp_stats_reply *osr)
1178 iter->pos = osr->body;
1179 iter->end = osr->body + (ntohs(osr->header.length)
1180 - offsetof(struct ofp_stats_reply, body));
1181 return flow_stats_next(iter);
1184 const struct ofp_flow_stats *
1185 flow_stats_next(struct flow_stats_iterator *iter)
1187 ptrdiff_t bytes_left = iter->end - iter->pos;
1188 const struct ofp_flow_stats *fs;
1191 if (bytes_left < sizeof *fs) {
1192 if (bytes_left != 0) {
1193 VLOG_WARN_RL(&bad_ofmsg_rl,
1194 "%td leftover bytes in flow stats reply", bytes_left);
1199 fs = (const void *) iter->pos;
1200 length = ntohs(fs->length);
1201 if (length < sizeof *fs) {
1202 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
1203 "min %zu", length, sizeof *fs);
1205 } else if (length > bytes_left) {
1206 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
1207 "bytes left", length, bytes_left);
1209 } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
1210 VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
1211 "left over in final action", length,
1212 (length - sizeof *fs) % sizeof fs->actions[0]);
1215 iter->pos += length;
1219 /* Alignment of ofp_actions. */
1220 #define ACTION_ALIGNMENT 8
1223 check_action_exact_len(const union ofp_action *a, unsigned int len,
1224 unsigned int required_len)
1226 if (len != required_len) {
1227 VLOG_DBG_RL(&bad_ofmsg_rl,
1228 "action %u has invalid length %"PRIu16" (must be %u)\n",
1229 a->type, ntohs(a->header.len), required_len);
1230 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1236 check_action_port(int port, int max_ports)
1244 case OFPP_CONTROLLER:
1249 if (port >= 0 && port < max_ports) {
1252 VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1253 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1258 check_nicira_action(const union ofp_action *a, unsigned int len)
1260 const struct nx_action_header *nah;
1263 VLOG_DBG_RL(&bad_ofmsg_rl,
1264 "Nicira vendor action only %u bytes", len);
1265 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1267 nah = (const struct nx_action_header *) a;
1269 switch (ntohs(nah->subtype)) {
1270 case NXAST_RESUBMIT:
1271 return check_action_exact_len(a, len, 16);
1273 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1278 check_action(const union ofp_action *a, unsigned int len, int max_ports)
1282 switch (ntohs(a->type)) {
1284 error = check_action_port(ntohs(a->output.port), max_ports);
1288 return check_action_exact_len(a, len, 8);
1290 case OFPAT_SET_VLAN_VID:
1291 case OFPAT_SET_VLAN_PCP:
1292 case OFPAT_STRIP_VLAN:
1293 case OFPAT_SET_NW_SRC:
1294 case OFPAT_SET_NW_DST:
1295 case OFPAT_SET_TP_SRC:
1296 case OFPAT_SET_TP_DST:
1297 return check_action_exact_len(a, len, 8);
1299 case OFPAT_SET_DL_SRC:
1300 case OFPAT_SET_DL_DST:
1301 return check_action_exact_len(a, len, 16);
1304 if (a->vendor.vendor == htonl(NX_VENDOR_ID)) {
1305 return check_nicira_action(a, len);
1307 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR);
1312 VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16,
1314 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1318 VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
1319 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1321 if (len % ACTION_ALIGNMENT) {
1322 VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple of %d",
1323 len, ACTION_ALIGNMENT);
1324 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1330 validate_actions(const union ofp_action *actions, size_t n_actions,
1333 const union ofp_action *a;
1335 for (a = actions; a < &actions[n_actions]; ) {
1336 unsigned int len = ntohs(a->header.len);
1337 unsigned int n_slots = len / ACTION_ALIGNMENT;
1338 unsigned int slots_left = &actions[n_actions] - a;
1341 if (n_slots > slots_left) {
1342 VLOG_DBG_RL(&bad_ofmsg_rl,
1343 "action requires %u slots but only %u remain",
1344 n_slots, slots_left);
1345 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1347 error = check_action(a, len, max_ports);
1356 /* The set of actions must either come from a trusted source or have been
1357 * previously validated with validate_actions(). */
1358 const union ofp_action *
1359 actions_first(struct actions_iterator *iter,
1360 const union ofp_action *oa, size_t n_actions)
1363 iter->end = oa + n_actions;
1364 return actions_next(iter);
1367 const union ofp_action *
1368 actions_next(struct actions_iterator *iter)
1370 if (iter->pos < iter->end) {
1371 const union ofp_action *a = iter->pos;
1372 unsigned int len = ntohs(a->header.len);
1373 iter->pos += len / ACTION_ALIGNMENT;
1381 normalize_match(struct ofp_match *m)
1383 enum { OFPFW_NW = OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO };
1384 enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
1387 wc = ntohl(m->wildcards) & OFPFW_ALL;
1388 if (wc & OFPFW_DL_TYPE) {
1391 /* Can't sensibly match on network or transport headers if the
1392 * data link type is unknown. */
1393 wc |= OFPFW_NW | OFPFW_TP;
1394 m->nw_src = m->nw_dst = m->nw_proto = 0;
1395 m->tp_src = m->tp_dst = 0;
1396 } else if (m->dl_type == htons(ETH_TYPE_IP)) {
1397 if (wc & OFPFW_NW_PROTO) {
1400 /* Can't sensibly match on transport headers if the network
1401 * protocol is unknown. */
1403 m->tp_src = m->tp_dst = 0;
1404 } else if (m->nw_proto == IPPROTO_TCP ||
1405 m->nw_proto == IPPROTO_UDP ||
1406 m->nw_proto == IPPROTO_ICMP) {
1407 if (wc & OFPFW_TP_SRC) {
1410 if (wc & OFPFW_TP_DST) {
1414 /* Transport layer fields will always be extracted as zeros, so we
1415 * can do an exact-match on those values. */
1417 m->tp_src = m->tp_dst = 0;
1419 if (wc & OFPFW_NW_SRC_MASK) {
1420 m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
1422 if (wc & OFPFW_NW_DST_MASK) {
1423 m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
1426 /* Network and transport layer fields will always be extracted as
1427 * zeros, so we can do an exact-match on those values. */
1428 wc &= ~(OFPFW_NW | OFPFW_TP);
1429 m->nw_proto = m->nw_src = m->nw_dst = 0;
1430 m->tp_src = m->tp_dst = 0;
1432 if (wc & OFPFW_DL_SRC) {
1433 memset(m->dl_src, 0, sizeof m->dl_src);
1435 if (wc & OFPFW_DL_DST) {
1436 memset(m->dl_dst, 0, sizeof m->dl_dst);
1438 m->wildcards = htonl(wc);
1441 /* Initializes 'vconn' as a new vconn named 'name', implemented via 'class'.
1442 * The initial connection status, supplied as 'connect_status', is interpreted
1445 * - 0: 'vconn' is connected. Its 'send' and 'recv' functions may be
1446 * called in the normal fashion.
1448 * - EAGAIN: 'vconn' is trying to complete a connection. Its 'connect'
1449 * function should be called to complete the connection.
1451 * - Other positive errno values indicate that the connection failed with
1452 * the specified error.
1454 * After calling this function, vconn_close() must be used to destroy 'vconn',
1455 * otherwise resources will be leaked.
1457 * The caller retains ownership of 'name'. */
1459 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
1462 vconn->class = class;
1463 vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
1464 : !connect_status ? VCS_SEND_HELLO
1465 : VCS_DISCONNECTED);
1466 vconn->error = connect_status;
1467 vconn->version = -1;
1468 vconn->min_version = -1;
1469 vconn->remote_ip = 0;
1470 vconn->remote_port = 0;
1471 vconn->local_ip = 0;
1472 vconn->local_port = 0;
1473 vconn->name = xstrdup(name);
1474 assert(vconn->state != VCS_CONNECTING || class->connect);
1478 vconn_set_remote_ip(struct vconn *vconn, uint32_t ip)
1480 vconn->remote_ip = ip;
1484 vconn_set_remote_port(struct vconn *vconn, uint16_t port)
1486 vconn->remote_port = port;
1490 vconn_set_local_ip(struct vconn *vconn, uint32_t ip)
1492 vconn->local_ip = ip;
1496 vconn_set_local_port(struct vconn *vconn, uint16_t port)
1498 vconn->local_port = port;
1502 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
1505 pvconn->class = class;
1506 pvconn->name = xstrdup(name);