Rename struct buffer to struct ofpbuf.
[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 "flow.h"
44 #include "ofp-print.h"
45 #include "ofpbuf.h"
46 #include "openflow.h"
47 #include "poll-loop.h"
48 #include "random.h"
49 #include "util.h"
50
51 #define THIS_MODULE VLM_vconn
52 #include "vlog.h"
53
54 static struct vconn_class *vconn_classes[] = {
55     &tcp_vconn_class,
56     &ptcp_vconn_class,
57 #ifdef HAVE_NETLINK
58     &netlink_vconn_class,
59 #endif
60 #ifdef HAVE_OPENSSL
61     &ssl_vconn_class,
62     &pssl_vconn_class,
63 #endif
64     &unix_vconn_class,
65     &punix_vconn_class,
66 };
67
68 /* High rate limit because most of the rate-limiting here is individual
69  * OpenFlow messages going over the vconn.  If those are enabled then we
70  * really need to see them. */
71 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(600, 600);
72
73 /* Check the validity of the vconn class structures. */
74 static void
75 check_vconn_classes(void)
76 {
77 #ifndef NDEBUG
78     size_t i;
79
80     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
81         struct vconn_class *class = vconn_classes[i];
82         assert(class->name != NULL);
83         assert(class->open != NULL);
84         if (class->close || class->accept || class->recv || class->send
85             || class->wait) {
86             assert(class->close != NULL);
87             assert(class->accept
88                    ? !class->recv && !class->send
89                    :  class->recv && class->send);
90             assert(class->wait != NULL);
91         } else {
92             /* This class delegates to another one. */
93         }
94     }
95 #endif
96 }
97
98 /* Prints information on active (if 'active') and passive (if 'passive')
99  * connection methods supported by the vconn. */
100 void
101 vconn_usage(bool active, bool passive)
102 {
103     /* Really this should be implemented via callbacks into the vconn
104      * providers, but that seems too heavy-weight to bother with at the
105      * moment. */
106     
107     printf("\n");
108     if (active) {
109         printf("Active OpenFlow connection methods:\n");
110 #ifdef HAVE_NETLINK
111         printf("  nl:DP_IDX               "
112                "local datapath DP_IDX\n");
113 #endif
114         printf("  tcp:HOST[:PORT]         "
115                "PORT (default: %d) on remote TCP HOST\n", OFP_TCP_PORT);
116 #ifdef HAVE_OPENSSL
117         printf("  ssl:HOST[:PORT]         "
118                "SSL PORT (default: %d) on remote HOST\n", OFP_SSL_PORT);
119 #endif
120         printf("  unix:FILE               Unix domain socket named FILE\n");
121     }
122
123     if (passive) {
124         printf("Passive OpenFlow connection methods:\n");
125         printf("  ptcp:[PORT]             "
126                "listen to TCP PORT (default: %d)\n",
127                OFP_TCP_PORT);
128 #ifdef HAVE_OPENSSL
129         printf("  pssl:[PORT]             "
130                "listen for SSL on PORT (default: %d)\n",
131                OFP_SSL_PORT);
132 #endif
133         printf("  punix:FILE              "
134                "listen on Unix domain socket FILE\n");
135     }
136
137 #ifdef HAVE_OPENSSL
138     printf("PKI configuration (required to use SSL):\n"
139            "  -p, --private-key=FILE  file with private key\n"
140            "  -c, --certificate=FILE  file with certificate for private key\n"
141            "  -C, --ca-cert=FILE      file with peer CA certificate\n");
142 #endif
143 }
144
145 /* Attempts to connect to an OpenFlow device.  'name' is a connection name in
146  * the form "TYPE:ARGS", where TYPE is the vconn class's name and ARGS are
147  * vconn class-specific.
148  *
149  * Returns 0 if successful, otherwise a positive errno value.  If successful,
150  * stores a pointer to the new connection in '*vconnp', otherwise a null
151  * pointer.  */
152 int
153 vconn_open(const char *name, struct vconn **vconnp)
154 {
155     size_t prefix_len;
156     size_t i;
157
158     check_vconn_classes();
159
160     *vconnp = NULL;
161     prefix_len = strcspn(name, ":");
162     if (prefix_len == strlen(name)) {
163         error(0, "`%s' not correct format for peer name", name);
164         return EAFNOSUPPORT;
165     }
166     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
167         struct vconn_class *class = vconn_classes[i];
168         if (strlen(class->name) == prefix_len
169             && !memcmp(class->name, name, prefix_len)) {
170             struct vconn *vconn;
171             char *suffix_copy = xstrdup(name + prefix_len + 1);
172             int retval = class->open(name, suffix_copy, &vconn);
173             free(suffix_copy);
174             if (!retval) {
175                 assert(vconn->connect_status != EAGAIN
176                        || vconn->class->connect);
177                 vconn->name = xstrdup(name);
178                 *vconnp = vconn;
179             }
180             return retval;
181         }
182     }
183     error(0, "unknown peer type `%.*s'", (int) prefix_len, name);
184     return EAFNOSUPPORT;
185 }
186
187 int
188 vconn_open_block(const char *name, struct vconn **vconnp)
189 {
190     struct vconn *vconn;
191     int error;
192
193     error = vconn_open(name, &vconn);
194     while (error == EAGAIN) {
195         vconn_connect_wait(vconn);
196         poll_block();
197         error = vconn_connect(vconn);
198         assert(error != EINPROGRESS);
199     }
200     if (error) {
201         vconn_close(vconn);
202         *vconnp = NULL;
203     } else {
204         *vconnp = vconn;
205     }
206     return error;
207 }
208
209 /* Closes 'vconn'. */
210 void
211 vconn_close(struct vconn *vconn)
212 {
213     if (vconn != NULL) {
214         char *name = vconn->name;
215         (vconn->class->close)(vconn);
216         free(name);
217     }
218 }
219
220 /* Returns true if 'vconn' is a passive vconn, that is, its purpose is to
221  * wait for connections to arrive, not to transfer data.  Returns false if
222  * 'vconn' is an active vconn, that is, its purpose is to transfer data, not
223  * to wait for new connections to arrive. */
224 bool
225 vconn_is_passive(const struct vconn *vconn)
226 {
227     return vconn->class->accept != NULL;
228 }
229
230 /* Returns the IP address of the peer, or 0 if the peer is not connected over
231  * an IP-based protocol or if its IP address is not yet known. */
232 uint32_t
233 vconn_get_ip(const struct vconn *vconn) 
234 {
235     return vconn->ip;
236 }
237
238 /* Tries to complete the connection on 'vconn', which must be an active
239  * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
240  * was successful or a positive errno value if it failed.  If the
241  * connection is still in progress, returns EAGAIN. */
242 int
243 vconn_connect(struct vconn *vconn)
244 {
245     if (vconn->connect_status == EAGAIN) {
246         vconn->connect_status = (vconn->class->connect)(vconn);
247         assert(vconn->connect_status != EINPROGRESS);
248     }
249     return vconn->connect_status;
250 }
251
252 /* Tries to accept a new connection on 'vconn', which must be a passive vconn.
253  * If successful, stores the new connection in '*new_vconn' and returns 0.
254  * Otherwise, returns a positive errno value.
255  *
256  * vconn_accept will not block waiting for a connection.  If no connection is
257  * ready to be accepted, it returns EAGAIN immediately. */
258 int
259 vconn_accept(struct vconn *vconn, struct vconn **new_vconn)
260 {
261     int retval;
262
263     retval = (vconn->class->accept)(vconn, new_vconn);
264
265     if (retval) {
266         *new_vconn = NULL;
267     } else {
268         assert((*new_vconn)->connect_status != EAGAIN
269                || (*new_vconn)->class->connect);
270     }
271     return retval;
272 }
273
274 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
275  * vconn.  If successful, stores the received message into '*msgp' and returns
276  * 0.  The caller is responsible for destroying the message with
277  * ofpbuf_delete().  On failure, returns a positive errno value and stores a
278  * null pointer into '*msgp'.  On normal connection close, returns EOF.
279  *
280  * vconn_recv will not block waiting for a packet to arrive.  If no packets
281  * have been received, it returns EAGAIN immediately. */
282 int
283 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
284 {
285     int retval = vconn_connect(vconn);
286     if (!retval) {
287         retval = (vconn->class->recv)(vconn, msgp);
288         if (!retval) {
289             struct ofp_header *oh;
290
291             if (VLOG_IS_DBG_ENABLED()) {
292                 char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
293                 VLOG_DBG_RL(&rl, "%s: received: %s", vconn->name, s);
294                 free(s);
295             }
296
297             oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
298             if (oh->version != OFP_VERSION) {
299                 VLOG_ERR_RL(&rl, "%s: received OpenFlow version %02"PRIx8" "
300                             "!= expected %02x",
301                             vconn->name, oh->version, OFP_VERSION);
302                 ofpbuf_delete(*msgp);
303                 *msgp = NULL;
304                 return EPROTO;
305             }
306         }
307     }
308     if (retval) {
309         *msgp = NULL;
310     }
311     return retval;
312 }
313
314 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
315  * vconn.  If successful, returns 0, in which case ownership of 'msg' is
316  * transferred to the vconn.  Success does not guarantee that 'msg' has been or
317  * ever will be delivered to the peer, only that it has been queued for
318  * transmission.
319  *
320  * Returns a positive errno value on failure, in which case the caller
321  * retains ownership of 'msg'.
322  *
323  * vconn_send will not block.  If 'msg' cannot be immediately accepted for
324  * transmission, it returns EAGAIN immediately. */
325 int
326 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
327 {
328     int retval = vconn_connect(vconn);
329     if (!retval) {
330         assert(msg->size >= sizeof(struct ofp_header));
331         assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
332         if (!VLOG_IS_DBG_ENABLED()) { 
333             retval = (vconn->class->send)(vconn, msg);
334         } else {
335             char *s = ofp_to_string(msg->data, msg->size, 1);
336             retval = (vconn->class->send)(vconn, msg);
337             if (retval != EAGAIN) {
338                 VLOG_DBG_RL(&rl, "%s: sent (%s): %s", vconn->name, strerror(retval), s);
339             }
340             free(s);
341         }
342     }
343     return retval;
344 }
345
346 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
347 int
348 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
349 {
350     int retval;
351     while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
352         vconn_send_wait(vconn);
353         poll_block();
354     }
355     return retval;
356 }
357
358 /* Same as vconn_recv, except that it waits until a message is received. */
359 int
360 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
361 {
362     int retval;
363     while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
364         vconn_recv_wait(vconn);
365         poll_block();
366     }
367     return retval;
368 }
369
370 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
371  * matching transaction ID.  Returns 0 if successful, in which case the reply
372  * is stored in '*replyp' for the caller to examine and free.  Otherwise
373  * returns a positive errno value, or EOF, and sets '*replyp' to null.
374  *
375  * 'request' is always destroyed, regardless of the return value. */
376 int
377 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
378                struct ofpbuf **replyp)
379 {
380     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
381     int error;
382
383     *replyp = NULL;
384     error = vconn_send_block(vconn, request);
385     if (error) {
386         ofpbuf_delete(request);
387         return error;
388     }
389     for (;;) {
390         uint32_t recv_xid;
391         struct ofpbuf *reply;
392
393         error = vconn_recv_block(vconn, &reply);
394         if (error) {
395             return error;
396         }
397         recv_xid = ((struct ofp_header *) reply->data)->xid;
398         if (send_xid == recv_xid) {
399             *replyp = reply;
400             return 0;
401         }
402
403         VLOG_DBG_RL(&rl, "%s: received reply with xid %08"PRIx32" != expected "
404                     "%08"PRIx32, vconn->name, recv_xid, send_xid);
405         ofpbuf_delete(reply);
406     }
407 }
408
409 void
410 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
411 {
412     int connect_status;
413
414     assert(vconn_is_passive(vconn)
415            ? wait == WAIT_ACCEPT || wait == WAIT_CONNECT
416            : wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
417
418     connect_status = vconn_connect(vconn);
419     if (connect_status) {
420         if (connect_status == EAGAIN) {
421             wait = WAIT_CONNECT;
422         } else {
423             poll_immediate_wake();
424             return;
425         }
426     }
427
428     (vconn->class->wait)(vconn, wait);
429 }
430
431 void
432 vconn_connect_wait(struct vconn *vconn)
433 {
434     vconn_wait(vconn, WAIT_CONNECT);
435 }
436
437 void
438 vconn_accept_wait(struct vconn *vconn)
439 {
440     vconn_wait(vconn, WAIT_ACCEPT);
441 }
442
443 void
444 vconn_recv_wait(struct vconn *vconn)
445 {
446     vconn_wait(vconn, WAIT_RECV);
447 }
448
449 void
450 vconn_send_wait(struct vconn *vconn)
451 {
452     vconn_wait(vconn, WAIT_SEND);
453 }
454
455 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
456  * containing an OpenFlow header with the given 'type' and a random transaction
457  * id.  Stores the new buffer in '*bufferp'.  The caller must free the buffer
458  * when it is no longer needed. */
459 void *
460 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp) 
461 {
462     return make_openflow_xid(openflow_len, type, random_uint32(), bufferp);
463 }
464
465 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
466  * containing an OpenFlow header with the given 'type' and transaction id
467  * 'xid'.  Stores the new buffer in '*bufferp'.  The caller must free the
468  * buffer when it is no longer needed. */
469 void *
470 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
471                   struct ofpbuf **bufferp)
472 {
473     struct ofpbuf *buffer;
474     struct ofp_header *oh;
475
476     assert(openflow_len >= sizeof *oh);
477     assert(openflow_len <= UINT16_MAX);
478     buffer = *bufferp = ofpbuf_new(openflow_len);
479     oh = ofpbuf_put_uninit(buffer, openflow_len);
480     memset(oh, 0, openflow_len);
481     oh->version = OFP_VERSION;
482     oh->type = type;
483     oh->length = htons(openflow_len);
484     oh->xid = xid;
485     return oh;
486 }
487
488 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
489  * 'buffer->size'. */
490 void
491 update_openflow_length(struct ofpbuf *buffer) 
492 {
493     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
494     oh->length = htons(buffer->size); 
495 }
496
497 struct ofpbuf *
498 make_add_flow(const struct flow *flow, uint32_t buffer_id,
499               uint16_t idle_timeout, size_t n_actions)
500 {
501     struct ofp_flow_mod *ofm;
502     size_t size = sizeof *ofm + n_actions * sizeof ofm->actions[0];
503     struct ofpbuf *out = ofpbuf_new(size);
504     ofm = ofpbuf_put_uninit(out, size);
505     memset(ofm, 0, size);
506     ofm->header.version = OFP_VERSION;
507     ofm->header.type = OFPT_FLOW_MOD;
508     ofm->header.length = htons(size);
509     ofm->match.wildcards = htonl(0);
510     ofm->match.in_port = flow->in_port;
511     memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
512     memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
513     ofm->match.dl_vlan = flow->dl_vlan;
514     ofm->match.dl_type = flow->dl_type;
515     ofm->match.nw_src = flow->nw_src;
516     ofm->match.nw_dst = flow->nw_dst;
517     ofm->match.nw_proto = flow->nw_proto;
518     ofm->match.tp_src = flow->tp_src;
519     ofm->match.tp_dst = flow->tp_dst;
520     ofm->command = htons(OFPFC_ADD);
521     ofm->idle_timeout = htons(idle_timeout);
522     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
523     ofm->buffer_id = htonl(buffer_id);
524     return out;
525 }
526
527 struct ofpbuf *
528 make_add_simple_flow(const struct flow *flow,
529                      uint32_t buffer_id, uint16_t out_port,
530                      uint16_t idle_timeout)
531 {
532     struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout, 1);
533     struct ofp_flow_mod *ofm = buffer->data;
534     ofm->actions[0].type = htons(OFPAT_OUTPUT);
535     ofm->actions[0].arg.output.max_len = htons(0);
536     ofm->actions[0].arg.output.port = htons(out_port);
537     return buffer;
538 }
539
540 struct ofpbuf *
541 make_unbuffered_packet_out(const struct ofpbuf *packet,
542                            uint16_t in_port, uint16_t out_port)
543 {
544     struct ofp_packet_out *opo;
545     size_t size = sizeof *opo + sizeof opo->actions[0];
546     struct ofpbuf *out = ofpbuf_new(size + packet->size);
547     opo = ofpbuf_put_uninit(out, size);
548     memset(opo, 0, sizeof *opo);
549     opo->header.version = OFP_VERSION;
550     opo->header.type = OFPT_PACKET_OUT;
551     opo->buffer_id = htonl(UINT32_MAX);
552     opo->in_port = htons(in_port);
553     opo->n_actions = htons(1);
554     opo->actions[0].type = htons(OFPAT_OUTPUT);
555     opo->actions[0].arg.output.max_len = htons(0);
556     opo->actions[0].arg.output.port = htons(out_port);
557     ofpbuf_put(out, packet->data, packet->size);
558     update_openflow_length(out);
559     return out;
560 }
561
562 struct ofpbuf *
563 make_buffered_packet_out(uint32_t buffer_id,
564                          uint16_t in_port, uint16_t out_port)
565 {
566     struct ofp_packet_out *opo;
567     size_t size = sizeof *opo + sizeof opo->actions[0];
568     struct ofpbuf *out = ofpbuf_new(size);
569     opo = ofpbuf_put_uninit(out, size);
570     memset(opo, 0, size);
571     opo->header.version = OFP_VERSION;
572     opo->header.type = OFPT_PACKET_OUT;
573     opo->header.length = htons(size);
574     opo->buffer_id = htonl(buffer_id);
575     opo->in_port = htons(in_port);
576     opo->n_actions = htons(1);
577     opo->actions[0].type = htons(OFPAT_OUTPUT);
578     opo->actions[0].arg.output.max_len = htons(0);
579     opo->actions[0].arg.output.port = htons(out_port);
580     return out;
581 }
582
583 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
584 struct ofpbuf *
585 make_echo_request(void)
586 {
587     struct ofp_header *rq;
588     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
589     rq = ofpbuf_put_uninit(out, sizeof *rq);
590     rq->version = OFP_VERSION;
591     rq->type = OFPT_ECHO_REQUEST;
592     rq->length = htons(sizeof *rq);
593     rq->xid = 0;
594     return out;
595 }
596
597 /* Creates and returns an OFPT_ECHO_REPLY message matching the
598  * OFPT_ECHO_REQUEST message in 'rq'. */
599 struct ofpbuf *
600 make_echo_reply(const struct ofp_header *rq)
601 {
602     size_t size = ntohs(rq->length);
603     struct ofpbuf *out = ofpbuf_new(size);
604     struct ofp_header *reply = ofpbuf_put(out, rq, size);
605     reply->type = OFPT_ECHO_REPLY;
606     return out;
607 }
608
609 void
610 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
611            uint32_t ip, const char *name)
612 {
613     vconn->class = class;
614     vconn->connect_status = connect_status;
615     vconn->ip = ip;
616     vconn->name = xstrdup(name);
617 }
618