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