1c3b699ce06d19df68bffb1ab7065cf02915252b
[sliver-openvswitch.git] / lib / vconn.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include "vconn-provider.h"
36 #include <assert.h>
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <poll.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include "dynamic-string.h"
44 #include "flow.h"
45 #include "ofp-print.h"
46 #include "ofpbuf.h"
47 #include "openflow.h"
48 #include "poll-loop.h"
49 #include "random.h"
50 #include "util.h"
51
52 #define THIS_MODULE VLM_vconn
53 #include "vlog.h"
54
55 /* State of an active vconn.*/
56 enum vconn_state {
57     /* This is the ordinary progression of states. */
58     VCS_CONNECTING,             /* Underlying vconn is not connected. */
59     VCS_SEND_HELLO,             /* Waiting to send OFPT_HELLO message. */
60     VCS_RECV_HELLO,             /* Waiting to receive OFPT_HELLO message. */
61     VCS_CONNECTED,              /* Connection established. */
62
63     /* These states are entered only when something goes wrong. */
64     VCS_SEND_ERROR,             /* Sending OFPT_ERROR message. */
65     VCS_DISCONNECTED            /* Connection failed or connection closed. */
66 };
67
68 static struct vconn_class *vconn_classes[] = {
69     &tcp_vconn_class,
70     &unix_vconn_class,
71 #ifdef HAVE_NETLINK
72     &netlink_vconn_class,
73 #endif
74 #ifdef HAVE_OPENSSL
75     &ssl_vconn_class,
76 #endif
77 };
78
79 static struct pvconn_class *pvconn_classes[] = {
80     &ptcp_pvconn_class,
81     &punix_pvconn_class,
82 #ifdef HAVE_OPENSSL
83     &pssl_pvconn_class,
84 #endif
85 };
86
87 /* High rate limit because most of the rate-limiting here is individual
88  * OpenFlow messages going over the vconn.  If those are enabled then we
89  * really need to see them. */
90 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(600, 600);
91
92 static int do_recv(struct vconn *, struct ofpbuf **);
93 static int do_send(struct vconn *, struct ofpbuf *);
94
95 /* Check the validity of the vconn class structures. */
96 static void
97 check_vconn_classes(void)
98 {
99 #ifndef NDEBUG
100     size_t i;
101
102     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
103         struct vconn_class *class = vconn_classes[i];
104         assert(class->name != NULL);
105         assert(class->open != NULL);
106         if (class->close || class->recv || class->send || class->wait) {
107             assert(class->close != NULL);
108             assert(class->recv != NULL);
109             assert(class->send != NULL);
110             assert(class->wait != NULL);
111         } else {
112             /* This class delegates to another one. */
113         }
114     }
115
116     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
117         struct pvconn_class *class = pvconn_classes[i];
118         assert(class->name != NULL);
119         assert(class->listen != NULL);
120         if (class->close || class->accept || class->wait) {
121             assert(class->close != NULL);
122             assert(class->accept != NULL);
123             assert(class->wait != NULL);
124         } else {
125             /* This class delegates to another one. */
126         }
127     }
128 #endif
129 }
130
131 /* Prints information on active (if 'active') and passive (if 'passive')
132  * connection methods supported by the vconn. */
133 void
134 vconn_usage(bool active, bool passive)
135 {
136     /* Really this should be implemented via callbacks into the vconn
137      * providers, but that seems too heavy-weight to bother with at the
138      * moment. */
139     
140     printf("\n");
141     if (active) {
142         printf("Active OpenFlow connection methods:\n");
143 #ifdef HAVE_NETLINK
144         printf("  nl:DP_IDX               "
145                "local datapath DP_IDX\n");
146 #endif
147         printf("  tcp:HOST[:PORT]         "
148                "PORT (default: %d) on remote TCP HOST\n", OFP_TCP_PORT);
149 #ifdef HAVE_OPENSSL
150         printf("  ssl:HOST[:PORT]         "
151                "SSL PORT (default: %d) on remote HOST\n", OFP_SSL_PORT);
152 #endif
153         printf("  unix:FILE               Unix domain socket named FILE\n");
154     }
155
156     if (passive) {
157         printf("Passive OpenFlow connection methods:\n");
158         printf("  ptcp:[PORT]             "
159                "listen to TCP PORT (default: %d)\n",
160                OFP_TCP_PORT);
161 #ifdef HAVE_OPENSSL
162         printf("  pssl:[PORT]             "
163                "listen for SSL on PORT (default: %d)\n",
164                OFP_SSL_PORT);
165 #endif
166         printf("  punix:FILE              "
167                "listen on Unix domain socket FILE\n");
168     }
169
170 #ifdef HAVE_OPENSSL
171     printf("PKI configuration (required to use SSL):\n"
172            "  -p, --private-key=FILE  file with private key\n"
173            "  -c, --certificate=FILE  file with certificate for private key\n"
174            "  -C, --ca-cert=FILE      file with peer CA certificate\n");
175 #endif
176 }
177
178 /* Attempts to connect to an OpenFlow device.  'name' is a connection name in
179  * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
180  * are vconn class-specific.
181  *
182  * The vconn will automatically negotiate an OpenFlow protocol version
183  * acceptable to both peers on the connection.  The version negotiated will be
184  * no lower than 'min_version' and no higher than OFP_VERSION.
185  *
186  * Returns 0 if successful, otherwise a positive errno value.  If successful,
187  * stores a pointer to the new connection in '*vconnp', otherwise a null
188  * pointer.  */
189 int
190 vconn_open(const char *name, int min_version, struct vconn **vconnp)
191 {
192     size_t prefix_len;
193     size_t i;
194
195     check_vconn_classes();
196
197     *vconnp = NULL;
198     prefix_len = strcspn(name, ":");
199     if (prefix_len == strlen(name)) {
200         return EAFNOSUPPORT;
201     }
202     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
203         struct vconn_class *class = vconn_classes[i];
204         if (strlen(class->name) == prefix_len
205             && !memcmp(class->name, name, prefix_len)) {
206             struct vconn *vconn;
207             char *suffix_copy = xstrdup(name + prefix_len + 1);
208             int retval = class->open(name, suffix_copy, &vconn);
209             free(suffix_copy);
210             if (!retval) {
211                 assert(vconn->state != VCS_CONNECTING
212                        || vconn->class->connect);
213                 vconn->min_version = min_version;
214                 *vconnp = vconn;
215             }
216             return retval;
217         }
218     }
219     return EAFNOSUPPORT;
220 }
221
222 int
223 vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
224 {
225     struct vconn *vconn;
226     int error;
227
228     error = vconn_open(name, min_version, &vconn);
229     while (error == EAGAIN) {
230         vconn_connect_wait(vconn);
231         poll_block();
232         error = vconn_connect(vconn);
233         assert(error != EINPROGRESS);
234     }
235     if (error) {
236         vconn_close(vconn);
237         *vconnp = NULL;
238     } else {
239         *vconnp = vconn;
240     }
241     return error;
242 }
243
244 /* Closes 'vconn'. */
245 void
246 vconn_close(struct vconn *vconn)
247 {
248     if (vconn != NULL) {
249         char *name = vconn->name;
250         (vconn->class->close)(vconn);
251         free(name);
252     }
253 }
254
255 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
256 const char *
257 vconn_get_name(const struct vconn *vconn)
258 {
259     return vconn->name;
260 }
261
262 /* Returns the IP address of the peer, or 0 if the peer is not connected over
263  * an IP-based protocol or if its IP address is not yet known. */
264 uint32_t
265 vconn_get_ip(const struct vconn *vconn) 
266 {
267     return vconn->ip;
268 }
269
270 static void
271 vcs_connecting(struct vconn *vconn) 
272 {
273     int retval = (vconn->class->connect)(vconn);
274     assert(retval != EINPROGRESS);
275     if (!retval) {
276         vconn->state = VCS_SEND_HELLO;
277     } else if (retval != EAGAIN) {
278         vconn->state = VCS_DISCONNECTED;
279         vconn->error = retval;
280     }
281 }
282
283 static void
284 vcs_send_hello(struct vconn *vconn)
285 {
286     struct ofpbuf *b;
287     int retval;
288
289     make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
290     retval = do_send(vconn, b);
291     if (!retval) {
292         vconn->state = VCS_RECV_HELLO;
293     } else {
294         ofpbuf_delete(b);
295         if (retval != EAGAIN) {
296             vconn->state = VCS_DISCONNECTED;
297             vconn->error = retval;
298         }
299     }
300 }
301
302 static void
303 vcs_recv_hello(struct vconn *vconn)
304 {
305     struct ofpbuf *b;
306     int retval;
307
308     retval = do_recv(vconn, &b);
309     if (!retval) {
310         struct ofp_header *oh = b->data;
311
312         if (oh->type == OFPT_HELLO) {
313             if (b->size > sizeof *oh) {
314                 struct ds msg = DS_EMPTY_INITIALIZER;
315                 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
316                 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
317                 VLOG_WARN_RL(&rl, ds_cstr(&msg));
318                 ds_destroy(&msg);
319             }
320
321             vconn->version = MIN(OFP_VERSION, oh->version);
322             if (vconn->version < vconn->min_version) {
323                 VLOG_WARN_RL(&rl, "%s: version negotiation failed: we support "
324                              "versions 0x%02x to 0x%02x inclusive but peer "
325                              "supports no later than version 0x%02"PRIx8,
326                              vconn->name, vconn->min_version, OFP_VERSION,
327                              oh->version);
328                 vconn->state = VCS_SEND_ERROR;
329             } else {
330                 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
331                          "(we support versions 0x%02x to 0x%02x inclusive, "
332                          "peer no later than version 0x%02"PRIx8")",
333                          vconn->name, vconn->version, vconn->min_version,
334                          OFP_VERSION, oh->version);
335                 vconn->state = VCS_CONNECTED;
336             }
337             ofpbuf_delete(b);
338             return;
339         } else {
340             char *s = ofp_to_string(b->data, b->size, 1);
341             VLOG_WARN_RL(&rl, "%s: received message while expecting hello: %s",
342                          vconn->name, s);
343             free(s);
344             retval = EPROTO;
345             ofpbuf_delete(b);
346         }
347     }
348
349     if (retval != EAGAIN) {
350         vconn->state = VCS_DISCONNECTED;
351         vconn->error = retval;
352     }
353 }
354
355 static void
356 vcs_send_error(struct vconn *vconn)
357 {
358     struct ofp_error_msg *error;
359     struct ofpbuf *b;
360     char s[128];
361     int retval;
362
363     snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
364              "you support no later than version 0x%02"PRIx8".",
365              vconn->min_version, OFP_VERSION, vconn->version);
366     error = make_openflow(sizeof *error, OFPT_ERROR, &b);
367     error->type = htons(OFPET_HELLO_FAILED);
368     error->code = htons(OFPHFC_INCOMPATIBLE);
369     ofpbuf_put(b, s, strlen(s));
370     retval = do_send(vconn, b);
371     if (retval) {
372         ofpbuf_delete(b);
373     }
374     if (retval != EAGAIN) {
375         vconn->state = VCS_DISCONNECTED;
376         vconn->error = retval ? retval : EPROTO;
377     }
378 }
379
380 /* Tries to complete the connection on 'vconn', which must be an active
381  * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
382  * was successful or a positive errno value if it failed.  If the
383  * connection is still in progress, returns EAGAIN. */
384 int
385 vconn_connect(struct vconn *vconn)
386 {
387     enum vconn_state last_state;
388
389     assert(vconn->min_version >= 0);
390     do {
391         last_state = vconn->state;
392         switch (vconn->state) {
393         case VCS_CONNECTING:
394             vcs_connecting(vconn);
395             break;
396
397         case VCS_SEND_HELLO:
398             vcs_send_hello(vconn);
399             break;
400
401         case VCS_RECV_HELLO:
402             vcs_recv_hello(vconn);
403             break;
404
405         case VCS_CONNECTED:
406             return 0;
407
408         case VCS_SEND_ERROR:
409             vcs_send_error(vconn);
410             break;
411
412         case VCS_DISCONNECTED:
413             return vconn->error;
414
415         default:
416             NOT_REACHED();
417         }
418     } while (vconn->state != last_state);
419
420     return EAGAIN;
421 }
422
423 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
424  * vconn.  If successful, stores the received message into '*msgp' and returns
425  * 0.  The caller is responsible for destroying the message with
426  * ofpbuf_delete().  On failure, returns a positive errno value and stores a
427  * null pointer into '*msgp'.  On normal connection close, returns EOF.
428  *
429  * vconn_recv will not block waiting for a packet to arrive.  If no packets
430  * have been received, it returns EAGAIN immediately. */
431 int
432 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
433 {
434     int retval = vconn_connect(vconn);
435     if (!retval) {
436         retval = do_recv(vconn, msgp);
437     }
438     return retval;
439 }
440
441 static int
442 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
443 {
444     int retval;
445
446     retval = (vconn->class->recv)(vconn, msgp);
447     if (!retval) {
448         struct ofp_header *oh;
449
450         if (VLOG_IS_DBG_ENABLED()) {
451             char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
452             VLOG_DBG_RL(&rl, "%s: received: %s", vconn->name, s);
453             free(s);
454         }
455
456         oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
457         if (oh->version != vconn->version
458             && oh->type != OFPT_HELLO
459             && oh->type != OFPT_ERROR
460             && oh->type != OFPT_ECHO_REQUEST
461             && oh->type != OFPT_ECHO_REPLY
462             && oh->type != OFPT_VENDOR)
463         {
464             if (vconn->version < 0) {
465                 VLOG_ERR_RL(&rl, "%s: received OpenFlow version %02"PRIx8" "
466                             "before version negotiation complete",
467                             vconn->name, oh->version);
468             } else {
469                 VLOG_ERR_RL(&rl, "%s: received OpenFlow version %02"PRIx8" "
470                             "!= expected %02x",
471                             vconn->name, oh->version, vconn->version);
472             }
473             ofpbuf_delete(*msgp);
474             retval = EPROTO;
475         }
476     }
477     if (retval) {
478         *msgp = NULL;
479     }
480     return retval;
481 }
482
483 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
484  * vconn.  If successful, returns 0, in which case ownership of 'msg' is
485  * transferred to the vconn.  Success does not guarantee that 'msg' has been or
486  * ever will be delivered to the peer, only that it has been queued for
487  * transmission.
488  *
489  * Returns a positive errno value on failure, in which case the caller
490  * retains ownership of 'msg'.
491  *
492  * vconn_send will not block.  If 'msg' cannot be immediately accepted for
493  * transmission, it returns EAGAIN immediately. */
494 int
495 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
496 {
497     int retval = vconn_connect(vconn);
498     if (!retval) {
499         retval = do_send(vconn, msg);
500     }
501     return retval;
502 }
503
504 static int
505 do_send(struct vconn *vconn, struct ofpbuf *msg)
506 {
507     int retval;
508
509     assert(msg->size >= sizeof(struct ofp_header));
510     assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
511     if (!VLOG_IS_DBG_ENABLED()) {
512         retval = (vconn->class->send)(vconn, msg);
513     } else {
514         char *s = ofp_to_string(msg->data, msg->size, 1);
515         retval = (vconn->class->send)(vconn, msg);
516         if (retval != EAGAIN) {
517             VLOG_DBG_RL(&rl, "%s: sent (%s): %s",
518                         vconn->name, strerror(retval), s);
519         }
520         free(s);
521     }
522     return retval;
523 }
524
525 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
526 int
527 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
528 {
529     int retval;
530     while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
531         vconn_send_wait(vconn);
532         poll_block();
533     }
534     return retval;
535 }
536
537 /* Same as vconn_recv, except that it waits until a message is received. */
538 int
539 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
540 {
541     int retval;
542     while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
543         vconn_recv_wait(vconn);
544         poll_block();
545     }
546     return retval;
547 }
548
549 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
550  * matching transaction ID.  Returns 0 if successful, in which case the reply
551  * is stored in '*replyp' for the caller to examine and free.  Otherwise
552  * returns a positive errno value, or EOF, and sets '*replyp' to null.
553  *
554  * 'request' is always destroyed, regardless of the return value. */
555 int
556 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
557                struct ofpbuf **replyp)
558 {
559     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
560     int error;
561
562     *replyp = NULL;
563     error = vconn_send_block(vconn, request);
564     if (error) {
565         ofpbuf_delete(request);
566         return error;
567     }
568     for (;;) {
569         uint32_t recv_xid;
570         struct ofpbuf *reply;
571
572         error = vconn_recv_block(vconn, &reply);
573         if (error) {
574             return error;
575         }
576         recv_xid = ((struct ofp_header *) reply->data)->xid;
577         if (send_xid == recv_xid) {
578             *replyp = reply;
579             return 0;
580         }
581
582         VLOG_DBG_RL(&rl, "%s: received reply with xid %08"PRIx32" != expected "
583                     "%08"PRIx32, vconn->name, recv_xid, send_xid);
584         ofpbuf_delete(reply);
585     }
586 }
587
588 void
589 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
590 {
591     assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
592
593     switch (vconn->state) {
594     case VCS_CONNECTING:
595         wait = WAIT_CONNECT;
596         break;
597
598     case VCS_SEND_HELLO:
599     case VCS_SEND_ERROR:
600         wait = WAIT_SEND;
601         break;
602
603     case VCS_RECV_HELLO:
604         wait = WAIT_RECV;
605         break;
606
607     case VCS_CONNECTED:
608         break;
609
610     case VCS_DISCONNECTED:
611         poll_immediate_wake();
612         return;
613     }
614     (vconn->class->wait)(vconn, wait);
615 }
616
617 void
618 vconn_connect_wait(struct vconn *vconn)
619 {
620     vconn_wait(vconn, WAIT_CONNECT);
621 }
622
623 void
624 vconn_recv_wait(struct vconn *vconn)
625 {
626     vconn_wait(vconn, WAIT_RECV);
627 }
628
629 void
630 vconn_send_wait(struct vconn *vconn)
631 {
632     vconn_wait(vconn, WAIT_SEND);
633 }
634
635 /* Attempts to start listening for OpenFlow connections.  'name' is a
636  * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
637  * class's name and ARGS are vconn class-specific.
638  *
639  * Returns 0 if successful, otherwise a positive errno value.  If successful,
640  * stores a pointer to the new connection in '*pvconnp', otherwise a null
641  * pointer.  */
642 int
643 pvconn_open(const char *name, struct pvconn **pvconnp)
644 {
645     size_t prefix_len;
646     size_t i;
647
648     check_vconn_classes();
649
650     *pvconnp = NULL;
651     prefix_len = strcspn(name, ":");
652     if (prefix_len == strlen(name)) {
653         return EAFNOSUPPORT;
654     }
655     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
656         struct pvconn_class *class = pvconn_classes[i];
657         if (strlen(class->name) == prefix_len
658             && !memcmp(class->name, name, prefix_len)) {
659             char *suffix_copy = xstrdup(name + prefix_len + 1);
660             int retval = class->listen(name, suffix_copy, pvconnp);
661             free(suffix_copy);
662             if (retval) {
663                 *pvconnp = NULL;
664             }
665             return retval;
666         }
667     }
668     return EAFNOSUPPORT;
669 }
670
671 /* Closes 'pvconn'. */
672 void
673 pvconn_close(struct pvconn *pvconn)
674 {
675     if (pvconn != NULL) {
676         char *name = pvconn->name;
677         (pvconn->class->close)(pvconn);
678         free(name);
679     }
680 }
681
682 /* Tries to accept a new connection on 'pvconn'.  If successful, stores the new
683  * connection in '*new_vconn' and returns 0.  Otherwise, returns a positive
684  * errno value.
685  *
686  * The new vconn will automatically negotiate an OpenFlow protocol version
687  * acceptable to both peers on the connection.  The version negotiated will be
688  * no lower than 'min_version' and no higher than OFP_VERSION.
689  *
690  * pvconn_accept() will not block waiting for a connection.  If no connection
691  * is ready to be accepted, it returns EAGAIN immediately. */
692 int
693 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
694 {
695     int retval = (pvconn->class->accept)(pvconn, new_vconn);
696     if (retval) {
697         *new_vconn = NULL;
698     } else {
699         assert((*new_vconn)->state != VCS_CONNECTING
700                || (*new_vconn)->class->connect);
701         (*new_vconn)->min_version = min_version;
702     }
703     return retval;
704 }
705
706 void
707 pvconn_wait(struct pvconn *pvconn)
708 {
709     (pvconn->class->wait)(pvconn);
710 }
711
712 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
713  * containing an OpenFlow header with the given 'type' and a random transaction
714  * id.  Stores the new buffer in '*bufferp'.  The caller must free the buffer
715  * when it is no longer needed. */
716 void *
717 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp) 
718 {
719     return make_openflow_xid(openflow_len, type, random_uint32(), bufferp);
720 }
721
722 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
723  * containing an OpenFlow header with the given 'type' and transaction id
724  * 'xid'.  Stores the new buffer in '*bufferp'.  The caller must free the
725  * buffer when it is no longer needed. */
726 void *
727 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
728                   struct ofpbuf **bufferp)
729 {
730     struct ofpbuf *buffer;
731     struct ofp_header *oh;
732
733     assert(openflow_len >= sizeof *oh);
734     assert(openflow_len <= UINT16_MAX);
735     buffer = *bufferp = ofpbuf_new(openflow_len);
736     oh = ofpbuf_put_uninit(buffer, openflow_len);
737     memset(oh, 0, openflow_len);
738     oh->version = OFP_VERSION;
739     oh->type = type;
740     oh->length = htons(openflow_len);
741     oh->xid = xid;
742     return oh;
743 }
744
745 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
746  * 'buffer->size'. */
747 void
748 update_openflow_length(struct ofpbuf *buffer) 
749 {
750     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
751     oh->length = htons(buffer->size); 
752 }
753
754 struct ofpbuf *
755 make_add_flow(const struct flow *flow, uint32_t buffer_id,
756               uint16_t idle_timeout, size_t n_actions)
757 {
758     struct ofp_flow_mod *ofm;
759     size_t size = sizeof *ofm + n_actions * sizeof ofm->actions[0];
760     struct ofpbuf *out = ofpbuf_new(size);
761     ofm = ofpbuf_put_uninit(out, size);
762     memset(ofm, 0, size);
763     ofm->header.version = OFP_VERSION;
764     ofm->header.type = OFPT_FLOW_MOD;
765     ofm->header.length = htons(size);
766     ofm->match.wildcards = htonl(0);
767     ofm->match.in_port = flow->in_port;
768     memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
769     memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
770     ofm->match.dl_vlan = flow->dl_vlan;
771     ofm->match.dl_type = flow->dl_type;
772     ofm->match.nw_src = flow->nw_src;
773     ofm->match.nw_dst = flow->nw_dst;
774     ofm->match.nw_proto = flow->nw_proto;
775     ofm->match.tp_src = flow->tp_src;
776     ofm->match.tp_dst = flow->tp_dst;
777     ofm->command = htons(OFPFC_ADD);
778     ofm->idle_timeout = htons(idle_timeout);
779     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
780     ofm->buffer_id = htonl(buffer_id);
781     return out;
782 }
783
784 struct ofpbuf *
785 make_add_simple_flow(const struct flow *flow,
786                      uint32_t buffer_id, uint16_t out_port,
787                      uint16_t idle_timeout)
788 {
789     struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout, 1);
790     struct ofp_flow_mod *ofm = buffer->data;
791     ofm->actions[0].type = htons(OFPAT_OUTPUT);
792     ofm->actions[0].arg.output.max_len = htons(0);
793     ofm->actions[0].arg.output.port = htons(out_port);
794     return buffer;
795 }
796
797 struct ofpbuf *
798 make_unbuffered_packet_out(const struct ofpbuf *packet,
799                            uint16_t in_port, uint16_t out_port)
800 {
801     struct ofp_packet_out *opo;
802     size_t size = sizeof *opo + sizeof opo->actions[0];
803     struct ofpbuf *out = ofpbuf_new(size + packet->size);
804     opo = ofpbuf_put_uninit(out, size);
805     memset(opo, 0, size);
806     opo->header.version = OFP_VERSION;
807     opo->header.type = OFPT_PACKET_OUT;
808     opo->buffer_id = htonl(UINT32_MAX);
809     opo->in_port = htons(in_port);
810     opo->n_actions = htons(1);
811     opo->actions[0].type = htons(OFPAT_OUTPUT);
812     opo->actions[0].arg.output.max_len = htons(0);
813     opo->actions[0].arg.output.port = htons(out_port);
814     ofpbuf_put(out, packet->data, packet->size);
815     update_openflow_length(out);
816     return out;
817 }
818
819 struct ofpbuf *
820 make_buffered_packet_out(uint32_t buffer_id,
821                          uint16_t in_port, uint16_t out_port)
822 {
823     struct ofp_packet_out *opo;
824     size_t size = sizeof *opo + sizeof opo->actions[0];
825     struct ofpbuf *out = ofpbuf_new(size);
826     opo = ofpbuf_put_uninit(out, size);
827     memset(opo, 0, size);
828     opo->header.version = OFP_VERSION;
829     opo->header.type = OFPT_PACKET_OUT;
830     opo->header.length = htons(size);
831     opo->buffer_id = htonl(buffer_id);
832     opo->in_port = htons(in_port);
833     opo->n_actions = htons(1);
834     opo->actions[0].type = htons(OFPAT_OUTPUT);
835     opo->actions[0].arg.output.max_len = htons(0);
836     opo->actions[0].arg.output.port = htons(out_port);
837     return out;
838 }
839
840 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
841 struct ofpbuf *
842 make_echo_request(void)
843 {
844     struct ofp_header *rq;
845     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
846     rq = ofpbuf_put_uninit(out, sizeof *rq);
847     rq->version = OFP_VERSION;
848     rq->type = OFPT_ECHO_REQUEST;
849     rq->length = htons(sizeof *rq);
850     rq->xid = 0;
851     return out;
852 }
853
854 /* Creates and returns an OFPT_ECHO_REPLY message matching the
855  * OFPT_ECHO_REQUEST message in 'rq'. */
856 struct ofpbuf *
857 make_echo_reply(const struct ofp_header *rq)
858 {
859     size_t size = ntohs(rq->length);
860     struct ofpbuf *out = ofpbuf_new(size);
861     struct ofp_header *reply = ofpbuf_put(out, rq, size);
862     reply->type = OFPT_ECHO_REPLY;
863     return out;
864 }
865
866 void
867 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
868            uint32_t ip, const char *name)
869 {
870     vconn->class = class;
871     vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
872                     : !connect_status ? VCS_SEND_HELLO
873                     : VCS_DISCONNECTED);
874     vconn->error = connect_status;
875     vconn->version = -1;
876     vconn->min_version = -1;
877     vconn->ip = ip;
878     vconn->name = xstrdup(name);
879 }
880
881 void
882 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
883             const char *name)
884 {
885     pvconn->class = class;
886     pvconn->name = xstrdup(name);
887 }