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