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