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