In userspace switch, don't truncate packets to 0 bytes with max_len of 0.
[sliver-openvswitch.git] / lib / vconn-ssl.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-ssl.h"
36 #include "dhparams.h"
37 #include <assert.h>
38 #include <errno.h>
39 #include <inttypes.h>
40 #include <string.h>
41 #include <netinet/tcp.h>
42 #include <openssl/err.h>
43 #include <openssl/ssl.h>
44 #include <poll.h>
45 #include <unistd.h>
46 #include "ofpbuf.h"
47 #include "socket-util.h"
48 #include "util.h"
49 #include "openflow.h"
50 #include "packets.h"
51 #include "poll-loop.h"
52 #include "socket-util.h"
53 #include "vconn.h"
54 #include "vconn-provider.h"
55
56 #include "vlog.h"
57 #define THIS_MODULE VLM_vconn_ssl
58
59 /* Active SSL. */
60
61 enum ssl_state {
62     STATE_TCP_CONNECTING,
63     STATE_SSL_CONNECTING
64 };
65
66 enum session_type {
67     CLIENT,
68     SERVER
69 };
70
71 struct ssl_vconn
72 {
73     struct vconn vconn;
74     enum ssl_state state;
75     int connect_error;
76     enum session_type type;
77     int fd;
78     SSL *ssl;
79     struct ofpbuf *rxbuf;
80     struct ofpbuf *txbuf;
81     struct poll_waiter *tx_waiter;
82
83     /* rx_want and tx_want record the result of the last call to SSL_read()
84      * and SSL_write(), respectively:
85      *
86      *    - If the call reported that data needed to be read from the file
87      *      descriptor, the corresponding member is set to SSL_READING.
88      *
89      *    - If the call reported that data needed to be written to the file
90      *      descriptor, the corresponding member is set to SSL_WRITING.
91      *
92      *    - Otherwise, the member is set to SSL_NOTHING, indicating that the
93      *      call completed successfully (or with an error) and that there is no
94      *      need to block.
95      *
96      * These are needed because there is no way to ask OpenSSL what a data read
97      * or write would require without giving it a buffer to receive into or
98      * data to send, respectively.  (Note that the SSL_want() status is
99      * overwritten by each SSL_read() or SSL_write() call, so we can't rely on
100      * its value.)
101      *
102      * A single call to SSL_read() or SSL_write() can perform both reading
103      * and writing and thus invalidate not one of these values but actually
104      * both.  Consider this situation, for example:
105      *
106      *    - SSL_write() blocks on a read, so tx_want gets SSL_READING.
107      *
108      *    - SSL_read() laters succeeds reading from 'fd' and clears out the
109      *      whole receive buffer, so rx_want gets SSL_READING.
110      *
111      *    - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
112      *      blocks.
113      *
114      *    - Now we're stuck blocking until the peer sends us data, even though
115      *      SSL_write() could now succeed, which could easily be a deadlock
116      *      condition.
117      *
118      * On the other hand, we can't reset both tx_want and rx_want on every call
119      * to SSL_read() or SSL_write(), because that would produce livelock,
120      * e.g. in this situation:
121      *
122      *    - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
123      *
124      *    - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
125      *      but tx_want gets reset to SSL_NOTHING.
126      *
127      *    - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
128      *      blocks.
129      *
130      *    - Client wakes up immediately since SSL_NOTHING in tx_want indicates
131      *      that no blocking is necessary.
132      *
133      * The solution we adopt here is to set tx_want to SSL_NOTHING after
134      * calling SSL_read() only if the SSL state of the connection changed,
135      * which indicates that an SSL-level renegotiation made some progress, and
136      * similarly for rx_want and SSL_write().  This prevents both the
137      * deadlock and livelock situations above.
138      */
139     int rx_want, tx_want;
140 };
141
142 /* SSL context created by ssl_init(). */
143 static SSL_CTX *ctx;
144
145 /* Required configuration. */
146 static bool has_private_key, has_certificate, has_ca_cert;
147
148 /* Who knows what can trigger various SSL errors, so let's throttle them down
149  * quite a bit. */
150 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 25);
151
152 static int ssl_init(void);
153 static int do_ssl_init(void);
154 static bool ssl_wants_io(int ssl_error);
155 static void ssl_close(struct vconn *);
156 static int interpret_ssl_error(const char *function, int ret, int error,
157                                int *want);
158 static void ssl_tx_poll_callback(int fd, short int revents, void *vconn_);
159 static DH *tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength);
160
161 short int
162 want_to_poll_events(int want)
163 {
164     switch (want) {
165     case SSL_NOTHING:
166         NOT_REACHED();
167
168     case SSL_READING:
169         return POLLIN;
170
171     case SSL_WRITING:
172         return POLLOUT;
173
174     default:
175         NOT_REACHED();
176     }
177 }
178
179 static int
180 new_ssl_vconn(const char *name, int fd, enum session_type type,
181               enum ssl_state state, const struct sockaddr_in *sin,
182               struct vconn **vconnp)
183 {
184     struct ssl_vconn *sslv;
185     SSL *ssl = NULL;
186     int on = 1;
187     int retval;
188
189     /* Check for all the needful configuration. */
190     if (!has_private_key) {
191         VLOG_ERR("Private key must be configured to use SSL");
192         goto error;
193     }
194     if (!has_certificate) {
195         VLOG_ERR("Certificate must be configured to use SSL");
196         goto error;
197     }
198     if (!has_ca_cert) {
199         VLOG_ERR("CA certificate must be configured to use SSL");
200         goto error;
201     }
202     if (!SSL_CTX_check_private_key(ctx)) {
203         VLOG_ERR("Private key does not match certificate public key");
204         goto error;
205     }
206
207     /* Disable Nagle. */
208     retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
209     if (retval) {
210         VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
211         close(fd);
212         return errno;
213     }
214
215     /* Create and configure OpenSSL stream. */
216     ssl = SSL_new(ctx);
217     if (ssl == NULL) {
218         VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
219         close(fd);
220         return ENOPROTOOPT;
221     }
222     if (SSL_set_fd(ssl, fd) == 0) {
223         VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
224         goto error;
225     }
226
227     /* Create and return the ssl_vconn. */
228     sslv = xmalloc(sizeof *sslv);
229     vconn_init(&sslv->vconn, &ssl_vconn_class, EAGAIN, sin->sin_addr.s_addr,
230                name);
231     sslv->state = state;
232     sslv->type = type;
233     sslv->fd = fd;
234     sslv->ssl = ssl;
235     sslv->rxbuf = NULL;
236     sslv->txbuf = NULL;
237     sslv->tx_waiter = NULL;
238     sslv->rx_want = sslv->tx_want = SSL_NOTHING;
239     *vconnp = &sslv->vconn;
240     return 0;
241
242 error:
243     if (ssl) {
244         SSL_free(ssl);
245     }
246     close(fd);
247     return ENOPROTOOPT;
248 }
249
250 static struct ssl_vconn *
251 ssl_vconn_cast(struct vconn *vconn)
252 {
253     assert(vconn->class == &ssl_vconn_class);
254     return CONTAINER_OF(vconn, struct ssl_vconn, vconn);
255 }
256
257 static int
258 ssl_open(const char *name, char *suffix, struct vconn **vconnp)
259 {
260     char *save_ptr, *host_name, *port_string;
261     struct sockaddr_in sin;
262     int retval;
263     int fd;
264
265     retval = ssl_init();
266     if (retval) {
267         return retval;
268     }
269
270     /* Glibc 2.7 has a bug in strtok_r when compiling with optimization that
271      * can cause segfaults here:
272      * http://sources.redhat.com/bugzilla/show_bug.cgi?id=5614.
273      * Using "::" instead of the obvious ":" works around it. */
274     host_name = strtok_r(suffix, "::", &save_ptr);
275     port_string = strtok_r(NULL, "::", &save_ptr);
276     if (!host_name) {
277         ofp_error(0, "%s: bad peer name format", name);
278         return EAFNOSUPPORT;
279     }
280
281     memset(&sin, 0, sizeof sin);
282     sin.sin_family = AF_INET;
283     if (lookup_ip(host_name, &sin.sin_addr)) {
284         return ENOENT;
285     }
286     sin.sin_port = htons(port_string && *port_string ? atoi(port_string)
287                          : OFP_SSL_PORT);
288
289     /* Create socket. */
290     fd = socket(AF_INET, SOCK_STREAM, 0);
291     if (fd < 0) {
292         VLOG_ERR("%s: socket: %s", name, strerror(errno));
293         return errno;
294     }
295     retval = set_nonblocking(fd);
296     if (retval) {
297         close(fd);
298         return retval;
299     }
300
301     /* Connect socket. */
302     retval = connect(fd, (struct sockaddr *) &sin, sizeof sin);
303     if (retval < 0) {
304         if (errno == EINPROGRESS) {
305             return new_ssl_vconn(name, fd, CLIENT, STATE_TCP_CONNECTING,
306                                  &sin, vconnp);
307         } else {
308             int error = errno;
309             VLOG_ERR("%s: connect: %s", name, strerror(error));
310             close(fd);
311             return error;
312         }
313     } else {
314         return new_ssl_vconn(name, fd, CLIENT, STATE_SSL_CONNECTING,
315                              &sin, vconnp);
316     }
317 }
318
319 static int
320 ssl_connect(struct vconn *vconn)
321 {
322     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
323     int retval;
324
325     switch (sslv->state) {
326     case STATE_TCP_CONNECTING:
327         retval = check_connection_completion(sslv->fd);
328         if (retval) {
329             return retval;
330         }
331         sslv->state = STATE_SSL_CONNECTING;
332         /* Fall through. */
333
334     case STATE_SSL_CONNECTING:
335         retval = (sslv->type == CLIENT
336                    ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
337         if (retval != 1) {
338             int error = SSL_get_error(sslv->ssl, retval);
339             if (retval < 0 && ssl_wants_io(error)) {
340                 return EAGAIN;
341             } else {
342                 int unused;
343                 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
344                                      : "SSL_accept"), retval, error, &unused);
345                 shutdown(sslv->fd, SHUT_RDWR);
346                 return EPROTO;
347             }
348         } else {
349             return 0;
350         }
351     }
352
353     NOT_REACHED();
354 }
355
356 static void
357 ssl_close(struct vconn *vconn)
358 {
359     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
360     poll_cancel(sslv->tx_waiter);
361     SSL_free(sslv->ssl);
362     close(sslv->fd);
363     free(sslv);
364 }
365
366 static int
367 interpret_ssl_error(const char *function, int ret, int error,
368                     int *want)
369 {
370     *want = SSL_NOTHING;
371
372     switch (error) {
373     case SSL_ERROR_NONE:
374         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_NONE", function);
375         break;
376
377     case SSL_ERROR_ZERO_RETURN:
378         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_ZERO_RETURN", function);
379         break;
380
381     case SSL_ERROR_WANT_READ:
382         *want = SSL_READING;
383         return EAGAIN;
384
385     case SSL_ERROR_WANT_WRITE:
386         *want = SSL_WRITING;
387         return EAGAIN;
388
389     case SSL_ERROR_WANT_CONNECT:
390         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_CONNECT", function);
391         break;
392
393     case SSL_ERROR_WANT_ACCEPT:
394         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
395         break;
396
397     case SSL_ERROR_WANT_X509_LOOKUP:
398         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_X509_LOOKUP",
399                     function);
400         break;
401
402     case SSL_ERROR_SYSCALL: {
403         int queued_error = ERR_get_error();
404         if (queued_error == 0) {
405             if (ret < 0) {
406                 int status = errno;
407                 VLOG_WARN_RL(&rl, "%s: system error (%s)",
408                              function, strerror(status));
409                 return status;
410             } else {
411                 VLOG_WARN_RL(&rl, "%s: unexpected SSL connection close",
412                              function);
413                 return EPROTO;
414             }
415         } else {
416             VLOG_DBG_RL(&rl, "%s: %s",
417                         function, ERR_error_string(queued_error, NULL));
418             break;
419         }
420     }
421
422     case SSL_ERROR_SSL: {
423         int queued_error = ERR_get_error();
424         if (queued_error != 0) {
425             VLOG_DBG_RL(&rl, "%s: %s",
426                         function, ERR_error_string(queued_error, NULL));
427         } else {
428             VLOG_ERR_RL(&rl, "%s: SSL_ERROR_SSL without queued error",
429                         function);
430         }
431         break;
432     }
433
434     default:
435         VLOG_ERR_RL(&rl, "%s: bad SSL error code %d", function, error);
436         break;
437     }
438     return EIO;
439 }
440
441 static int
442 ssl_recv(struct vconn *vconn, struct ofpbuf **bufferp)
443 {
444     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
445     struct ofpbuf *rx;
446     size_t want_bytes;
447     int old_state;
448     ssize_t ret;
449
450     if (sslv->rxbuf == NULL) {
451         sslv->rxbuf = ofpbuf_new(1564);
452     }
453     rx = sslv->rxbuf;
454
455 again:
456     if (sizeof(struct ofp_header) > rx->size) {
457         want_bytes = sizeof(struct ofp_header) - rx->size;
458     } else {
459         struct ofp_header *oh = rx->data;
460         size_t length = ntohs(oh->length);
461         if (length < sizeof(struct ofp_header)) {
462             VLOG_ERR_RL(&rl, "received too-short ofp_header (%zu bytes)",
463                         length);
464             return EPROTO;
465         }
466         want_bytes = length - rx->size;
467         if (!want_bytes) {
468             *bufferp = rx;
469             sslv->rxbuf = NULL;
470             return 0;
471         }
472     }
473     ofpbuf_prealloc_tailroom(rx, want_bytes);
474
475     /* Behavior of zero-byte SSL_read is poorly defined. */
476     assert(want_bytes > 0);
477
478     old_state = SSL_get_state(sslv->ssl);
479     ret = SSL_read(sslv->ssl, ofpbuf_tail(rx), want_bytes);
480     if (old_state != SSL_get_state(sslv->ssl)) {
481         sslv->tx_want = SSL_NOTHING;
482         if (sslv->tx_waiter) {
483             poll_cancel(sslv->tx_waiter);
484             ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
485         }
486     }
487     sslv->rx_want = SSL_NOTHING;
488
489     if (ret > 0) {
490         rx->size += ret;
491         if (ret == want_bytes) {
492             if (rx->size > sizeof(struct ofp_header)) {
493                 *bufferp = rx;
494                 sslv->rxbuf = NULL;
495                 return 0;
496             } else {
497                 goto again;
498             }
499         }
500         return EAGAIN;
501     } else {
502         int error = SSL_get_error(sslv->ssl, ret);
503         if (error == SSL_ERROR_ZERO_RETURN) {
504             /* Connection closed (EOF). */
505             if (rx->size) {
506                 VLOG_WARN_RL(&rl, "SSL_read: unexpected connection close");
507                 return EPROTO;
508             } else {
509                 return EOF;
510             }
511         } else {
512             return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
513         }
514     }
515 }
516
517 static void
518 ssl_clear_txbuf(struct ssl_vconn *sslv)
519 {
520     ofpbuf_delete(sslv->txbuf);
521     sslv->txbuf = NULL;
522     sslv->tx_waiter = NULL;
523 }
524
525 static void
526 ssl_register_tx_waiter(struct vconn *vconn)
527 {
528     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
529     sslv->tx_waiter = poll_fd_callback(sslv->fd,
530                                        want_to_poll_events(sslv->tx_want),
531                                        ssl_tx_poll_callback, vconn);
532 }
533
534 static int
535 ssl_do_tx(struct vconn *vconn)
536 {
537     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
538
539     for (;;) {
540         int old_state = SSL_get_state(sslv->ssl);
541         int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
542         if (old_state != SSL_get_state(sslv->ssl)) {
543             sslv->rx_want = SSL_NOTHING;
544         }
545         sslv->tx_want = SSL_NOTHING;
546         if (ret > 0) {
547             ofpbuf_pull(sslv->txbuf, ret);
548             if (sslv->txbuf->size == 0) {
549                 return 0;
550             }
551         } else {
552             int ssl_error = SSL_get_error(sslv->ssl, ret);
553             if (ssl_error == SSL_ERROR_ZERO_RETURN) {
554                 VLOG_WARN_RL(&rl, "SSL_write: connection closed");
555                 return EPIPE;
556             } else {
557                 return interpret_ssl_error("SSL_write", ret, ssl_error,
558                                            &sslv->tx_want);
559             }
560         }
561     }
562 }
563
564 static void
565 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
566 {
567     struct vconn *vconn = vconn_;
568     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
569     int error = ssl_do_tx(vconn);
570     if (error != EAGAIN) {
571         ssl_clear_txbuf(sslv);
572     } else {
573         ssl_register_tx_waiter(vconn);
574     }
575 }
576
577 static int
578 ssl_send(struct vconn *vconn, struct ofpbuf *buffer)
579 {
580     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
581
582     if (sslv->txbuf) {
583         return EAGAIN;
584     } else {
585         int error;
586
587         sslv->txbuf = buffer;
588         error = ssl_do_tx(vconn);
589         switch (error) {
590         case 0:
591             ssl_clear_txbuf(sslv);
592             return 0;
593         case EAGAIN:
594             ssl_register_tx_waiter(vconn);
595             return 0;
596         default:
597             sslv->txbuf = NULL;
598             return error;
599         }
600     }
601 }
602
603 static void
604 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
605 {
606     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
607
608     switch (wait) {
609     case WAIT_CONNECT:
610         if (vconn_connect(vconn) != EAGAIN) {
611             poll_immediate_wake();
612         } else {
613             switch (sslv->state) {
614             case STATE_TCP_CONNECTING:
615                 poll_fd_wait(sslv->fd, POLLOUT);
616                 break;
617
618             case STATE_SSL_CONNECTING:
619                 /* ssl_connect() called SSL_accept() or SSL_connect(), which
620                  * set up the status that we test here. */
621                 poll_fd_wait(sslv->fd,
622                              want_to_poll_events(SSL_want(sslv->ssl)));
623                 break;
624
625             default:
626                 NOT_REACHED();
627             }
628         }
629         break;
630
631     case WAIT_RECV:
632         if (sslv->rx_want != SSL_NOTHING) {
633             poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
634         } else {
635             poll_immediate_wake();
636         }
637         break;
638
639     case WAIT_SEND:
640         if (!sslv->txbuf) {
641             /* We have room in our tx queue. */
642             poll_immediate_wake();
643         } else {
644             /* The call to ssl_tx_poll_callback() will wake us up. */
645         }
646         break;
647
648     default:
649         NOT_REACHED();
650     }
651 }
652
653 struct vconn_class ssl_vconn_class = {
654     "ssl",                      /* name */
655     ssl_open,                   /* open */
656     ssl_close,                  /* close */
657     ssl_connect,                /* connect */
658     NULL,                       /* accept */
659     ssl_recv,                   /* recv */
660     ssl_send,                   /* send */
661     ssl_wait,                   /* wait */
662 };
663 \f
664 /* Passive SSL. */
665
666 struct pssl_vconn
667 {
668     struct vconn vconn;
669     int fd;
670 };
671
672 static struct pssl_vconn *
673 pssl_vconn_cast(struct vconn *vconn)
674 {
675     assert(vconn->class == &pssl_vconn_class);
676     return CONTAINER_OF(vconn, struct pssl_vconn, vconn);
677 }
678
679 static int
680 pssl_open(const char *name, char *suffix, struct vconn **vconnp)
681 {
682     struct sockaddr_in sin;
683     struct pssl_vconn *pssl;
684     int retval;
685     int fd;
686     unsigned int yes = 1;
687
688     retval = ssl_init();
689     if (retval) {
690         return retval;
691     }
692
693     /* Create socket. */
694     fd = socket(AF_INET, SOCK_STREAM, 0);
695     if (fd < 0) {
696         int error = errno;
697         VLOG_ERR("%s: socket: %s", name, strerror(error));
698         return error;
699     }
700
701     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
702         int error = errno;
703         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
704         return error;
705     }
706
707     memset(&sin, 0, sizeof sin);
708     sin.sin_family = AF_INET;
709     sin.sin_addr.s_addr = htonl(INADDR_ANY);
710     sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
711     retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
712     if (retval < 0) {
713         int error = errno;
714         VLOG_ERR("%s: bind: %s", name, strerror(error));
715         close(fd);
716         return error;
717     }
718
719     retval = listen(fd, 10);
720     if (retval < 0) {
721         int error = errno;
722         VLOG_ERR("%s: listen: %s", name, strerror(error));
723         close(fd);
724         return error;
725     }
726
727     retval = set_nonblocking(fd);
728     if (retval) {
729         close(fd);
730         return retval;
731     }
732
733     pssl = xmalloc(sizeof *pssl);
734     vconn_init(&pssl->vconn, &pssl_vconn_class, 0, 0, name);
735     pssl->fd = fd;
736     *vconnp = &pssl->vconn;
737     return 0;
738 }
739
740 static void
741 pssl_close(struct vconn *vconn)
742 {
743     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
744     close(pssl->fd);
745     free(pssl);
746 }
747
748 static int
749 pssl_accept(struct vconn *vconn, struct vconn **new_vconnp)
750 {
751     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
752     struct sockaddr_in sin;
753     socklen_t sin_len = sizeof sin;
754     char name[128];
755     int new_fd;
756     int error;
757
758     new_fd = accept(pssl->fd, &sin, &sin_len);
759     if (new_fd < 0) {
760         int error = errno;
761         if (error != EAGAIN) {
762             VLOG_DBG_RL(&rl, "accept: %s", strerror(error));
763         }
764         return error;
765     }
766
767     error = set_nonblocking(new_fd);
768     if (error) {
769         close(new_fd);
770         return error;
771     }
772
773     sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
774     if (sin.sin_port != htons(OFP_SSL_PORT)) {
775         sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
776     }
777     return new_ssl_vconn(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
778                          new_vconnp);
779 }
780
781 static void
782 pssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
783 {
784     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
785     assert(wait == WAIT_ACCEPT);
786     poll_fd_wait(pssl->fd, POLLIN);
787 }
788
789 struct vconn_class pssl_vconn_class = {
790     "pssl",                     /* name */
791     pssl_open,                  /* open */
792     pssl_close,                 /* close */
793     NULL,                       /* connect */
794     pssl_accept,                /* accept */
795     NULL,                       /* recv */
796     NULL,                       /* send */
797     pssl_wait,                  /* wait */
798 };
799 \f
800 /*
801  * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
802  * OpenSSL is requesting that we call it back when the socket is ready for read
803  * or writing, respectively.
804  */
805 static bool
806 ssl_wants_io(int ssl_error)
807 {
808     return (ssl_error == SSL_ERROR_WANT_WRITE
809             || ssl_error == SSL_ERROR_WANT_READ);
810 }
811
812 static int
813 ssl_init(void)
814 {
815     static int init_status = -1;
816     if (init_status < 0) {
817         init_status = do_ssl_init();
818         assert(init_status >= 0);
819     }
820     return init_status;
821 }
822
823 static int
824 do_ssl_init(void)
825 {
826     SSL_METHOD *method;
827
828     SSL_library_init();
829     SSL_load_error_strings();
830
831     method = TLSv1_method();
832     if (method == NULL) {
833         VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
834         return ENOPROTOOPT;
835     }
836
837     ctx = SSL_CTX_new(method);
838     if (ctx == NULL) {
839         VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
840         return ENOPROTOOPT;
841     }
842     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
843     SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
844     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
845     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
846     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
847                        NULL);
848
849     return 0;
850 }
851
852 static DH *
853 tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength)
854 {
855     struct dh {
856         int keylength;
857         DH *dh;
858         DH *(*constructor)(void);
859     };
860
861     static struct dh dh_table[] = {
862         {1024, NULL, get_dh1024},
863         {2048, NULL, get_dh2048},
864         {4096, NULL, get_dh4096},
865     };
866
867     struct dh *dh;
868
869     for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
870         if (dh->keylength == keylength) {
871             if (!dh->dh) {
872                 dh->dh = dh->constructor();
873                 if (!dh->dh) {
874                     ofp_fatal(ENOMEM, "out of memory constructing "
875                               "Diffie-Hellman parameters");
876                 }
877             }
878             return dh->dh;
879         }
880     }
881     VLOG_ERR_RL(&rl, "no Diffie-Hellman parameters for key length %d",
882                 keylength);
883     return NULL;
884 }
885
886 /* Returns true if SSL is at least partially configured. */
887 bool
888 vconn_ssl_is_configured(void) 
889 {
890     return has_private_key || has_certificate || has_ca_cert;
891 }
892
893 void
894 vconn_ssl_set_private_key_file(const char *file_name)
895 {
896     if (ssl_init()) {
897         return;
898     }
899     if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
900         VLOG_ERR("SSL_use_PrivateKey_file: %s",
901                  ERR_error_string(ERR_get_error(), NULL));
902         return;
903     }
904     has_private_key = true;
905 }
906
907 void
908 vconn_ssl_set_certificate_file(const char *file_name)
909 {
910     if (ssl_init()) {
911         return;
912     }
913     if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
914         VLOG_ERR("SSL_use_certificate_file: %s",
915                  ERR_error_string(ERR_get_error(), NULL));
916         return;
917     }
918     has_certificate = true;
919 }
920
921 void
922 vconn_ssl_set_ca_cert_file(const char *file_name)
923 {
924     STACK_OF(X509_NAME) *ca_list;
925
926     if (ssl_init()) {
927         return;
928     }
929
930     /* Set up list of CAs that the server will accept from the client. */
931     ca_list = SSL_load_client_CA_file(file_name);
932     if (ca_list == NULL) {
933         VLOG_ERR("SSL_load_client_CA_file: %s",
934                  ERR_error_string(ERR_get_error(), NULL));
935         return;
936     }
937     SSL_CTX_set_client_CA_list(ctx, ca_list);
938
939     /* Set up CAs for OpenSSL to trust in verifying the peer's certificate. */
940     if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
941         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
942                  ERR_error_string(ERR_get_error(), NULL));
943         return;
944     }
945
946     has_ca_cert = true;
947 }