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