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