coverity 181579: check result of malloc as intended
[platform/upstream/libwebsockets.git] / lib / ssl.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 /* workaround for mingw */
25 #if !defined(ECONNABORTED)
26 #define ECONNABORTED 103
27 #endif
28
29 int lws_alloc_vfs_file(struct lws_context *context, const char *filename, uint8_t **buf,
30                 lws_filepos_t *amount)
31 {
32         lws_filepos_t len;
33         lws_fop_flags_t flags = LWS_O_RDONLY;
34         lws_fop_fd_t fops_fd = lws_vfs_file_open(
35                                 lws_get_fops(context), filename, &flags);
36         int ret = 1;
37
38         if (!fops_fd)
39                 return 1;
40
41         len = lws_vfs_get_length(fops_fd);
42
43         *buf = malloc((size_t)len);
44         if (!*buf)
45                 goto bail;
46
47         if (lws_vfs_file_read(fops_fd, amount, *buf, len))
48                 goto bail;
49
50         ret = 0;
51 bail:
52         lws_vfs_file_close(&fops_fd);
53
54         return ret;
55 }
56
57 #if defined(LWS_WITH_ESP32)
58 int alloc_file(struct lws_context *context, const char *filename, uint8_t **buf,
59                lws_filepos_t *amount)
60 {
61         nvs_handle nvh;
62         size_t s;
63         int n = 0;
64
65         ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
66         if (nvs_get_blob(nvh, filename, NULL, &s) != ESP_OK) {
67                 n = 1;
68                 goto bail;
69         }
70         *buf = malloc(s);
71         if (!*buf) {
72                 n = 2;
73                 goto bail;
74         }
75         if (nvs_get_blob(nvh, filename, (char *)*buf, &s) != ESP_OK) {
76                 free(*buf);
77                 n = 1;
78                 goto bail;
79         }
80
81         *amount = s;
82
83 bail:
84         nvs_close(nvh);
85
86         return n;
87 }
88 int alloc_pem_to_der_file(struct lws_context *context, const char *filename, uint8_t **buf,
89                lws_filepos_t *amount)
90 {
91         uint8_t *pem, *p, *q, *end;
92         lws_filepos_t len;
93         int n;
94
95         n = alloc_file(context, filename, &pem, &len);
96         if (n)
97                 return n;
98
99         /* trim the first line */
100
101         p = pem;
102         end = p + len;
103         if (strncmp((char *)p, "-----", 5))
104                 goto bail;
105         p += 5;
106         while (p < end && *p != '\n' && *p != '-')
107                 p++;
108
109         if (*p != '-')
110                 goto bail;
111
112         while (p < end && *p != '\n')
113                 p++;
114
115         if (p >= end)
116                 goto bail;
117
118         p++;
119
120         /* trim the last line */
121
122         q = end - 2;
123
124         while (q > pem && *q != '\n')
125                 q--;
126
127         if (*q != '\n')
128                 goto bail;
129
130         *q = '\0';
131
132         *amount = lws_b64_decode_string((char *)p, (char *)pem, len);
133         *buf = pem;
134
135         return 0;
136
137 bail:
138         free(pem);
139
140         return 4;
141 }
142 #endif
143
144 int openssl_websocket_private_data_index,
145     openssl_SSL_CTX_private_data_index;
146
147 int lws_ssl_get_error(struct lws *wsi, int n)
148 {
149         if (!wsi->ssl)
150                 return 99;
151         lwsl_debug("%s: %p %d\n", __func__, wsi->ssl, n);
152         return SSL_get_error(wsi->ssl, n);
153 }
154
155 /* Copies a string describing the code returned by lws_ssl_get_error(),
156  * which may also contain system error information in the case of SSL_ERROR_SYSCALL,
157  * into buf up to len.
158  * Returns a pointer to buf.
159  *
160  * Note: the lws_ssl_get_error() code is *not* an error code that can be passed
161  * to ERR_error_string(),
162  *
163  * ret is the return value originally passed to lws_ssl_get_error(), needed to disambiguate
164  * SYS_ERROR_SYSCALL.
165  *
166  * See man page for SSL_get_error().
167  *
168  * Not thread safe, uses strerror()
169  */
170 char* lws_ssl_get_error_string(int status, int ret, char *buf, size_t len) {
171         switch (status) {
172         case SSL_ERROR_NONE: return strncpy(buf, "SSL_ERROR_NONE", len);
173         case SSL_ERROR_ZERO_RETURN: return strncpy(buf, "SSL_ERROR_ZERO_RETURN", len);
174         case SSL_ERROR_WANT_READ: return strncpy(buf, "SSL_ERROR_WANT_READ", len);
175         case SSL_ERROR_WANT_WRITE: return strncpy(buf, "SSL_ERROR_WANT_WRITE", len);
176         case SSL_ERROR_WANT_CONNECT: return strncpy(buf, "SSL_ERROR_WANT_CONNECT", len);
177         case SSL_ERROR_WANT_ACCEPT: return strncpy(buf, "SSL_ERROR_WANT_ACCEPT", len);
178         case SSL_ERROR_WANT_X509_LOOKUP: return strncpy(buf, "SSL_ERROR_WANT_X509_LOOKUP", len);
179         case SSL_ERROR_SYSCALL:
180                 switch (ret) {
181                 case 0:
182                         lws_snprintf(buf, len, "SSL_ERROR_SYSCALL: EOF");
183                         return buf;
184                 case -1:
185 #ifndef LWS_PLAT_OPTEE
186                         lws_snprintf(buf, len, "SSL_ERROR_SYSCALL: %s", strerror(errno));
187 #else
188                         lws_snprintf(buf, len, "SSL_ERROR_SYSCALL: %d", errno);
189 #endif
190                         return buf;
191                 default:
192                         return strncpy(buf, "SSL_ERROR_SYSCALL", len);
193         }
194         case SSL_ERROR_SSL: return "SSL_ERROR_SSL";
195         default: return "SSL_ERROR_UNKNOWN";
196         }
197 }
198
199 void
200 lws_ssl_elaborate_error(void)
201 {
202 #if defined(LWS_WITH_ESP32)
203 #else
204         char buf[256];
205         u_long err;
206
207         while ((err = ERR_get_error()) != 0) {
208                 ERR_error_string_n(err, buf, sizeof(buf));
209                 lwsl_err("*** %s\n", buf);
210         }
211 #endif
212 }
213
214 #if !defined(LWS_WITH_ESP32)
215
216 static int
217 lws_context_init_ssl_pem_passwd_cb(char * buf, int size, int rwflag, void *userdata)
218 {
219         struct lws_context_creation_info * info =
220                         (struct lws_context_creation_info *)userdata;
221
222         strncpy(buf, info->ssl_private_key_password, size);
223         buf[size - 1] = '\0';
224
225         return strlen(buf);
226 }
227
228 void
229 lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info)
230 {
231         if (!info->ssl_private_key_password)
232                 return;
233         /*
234          * password provided, set ssl callback and user data
235          * for checking password which will be trigered during
236          * SSL_CTX_use_PrivateKey_file function
237          */
238         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info);
239         SSL_CTX_set_default_passwd_cb(ssl_ctx, lws_context_init_ssl_pem_passwd_cb);
240 }
241 #endif
242
243 int
244 lws_context_init_ssl_library(struct lws_context_creation_info *info)
245 {
246 #ifdef USE_WOLFSSL
247 #ifdef USE_OLD_CYASSL
248         lwsl_notice(" Compiled with CyaSSL support\n");
249 #else
250         lwsl_notice(" Compiled with wolfSSL support\n");
251 #endif
252 #else
253 #if defined(LWS_USE_BORINGSSL)
254         lwsl_notice(" Compiled with BoringSSL support\n");
255 #else
256         lwsl_notice(" Compiled with OpenSSL support\n");
257 #endif
258 #endif
259         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) {
260                 lwsl_notice(" SSL disabled: no LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT\n");
261                 return 0;
262         }
263
264         /* basic openssl init */
265
266         lwsl_notice("Doing SSL library init\n");
267
268 #if !defined(LWS_WITH_ESP32)
269         SSL_library_init();
270         OpenSSL_add_all_algorithms();
271         SSL_load_error_strings();
272
273         openssl_websocket_private_data_index =
274                 SSL_get_ex_new_index(0, "lws", NULL, NULL, NULL);
275
276         openssl_SSL_CTX_private_data_index = SSL_CTX_get_ex_new_index(0,
277                         NULL, NULL, NULL, NULL);
278 #endif
279
280         return 0;
281 }
282
283 LWS_VISIBLE void
284 lws_ssl_destroy(struct lws_vhost *vhost)
285 {
286         if (!lws_check_opt(vhost->context->options,
287                            LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
288                 return;
289
290         if (vhost->ssl_ctx)
291                 SSL_CTX_free(vhost->ssl_ctx);
292         if (!vhost->user_supplied_ssl_ctx && vhost->ssl_client_ctx)
293                 SSL_CTX_free(vhost->ssl_client_ctx);
294 #if !defined(LWS_WITH_ESP32)
295
296 // after 1.1.0 no need
297 #if (OPENSSL_VERSION_NUMBER <  0x10100000)
298 // <= 1.0.1f = old api, 1.0.1g+ = new api
299 #if (OPENSSL_VERSION_NUMBER <= 0x1000106f) || defined(USE_WOLFSSL)
300         ERR_remove_state(0);
301 #else
302 #if OPENSSL_VERSION_NUMBER >= 0x1010005f && \
303     !defined(LIBRESSL_VERSION_NUMBER) && \
304     !defined(OPENSSL_IS_BORINGSSL)
305         ERR_remove_thread_state();
306 #else
307         ERR_remove_thread_state(NULL);
308 #endif
309 #endif
310         // after 1.1.0 no need
311 #if  (OPENSSL_VERSION_NUMBER >= 0x10002000) && (OPENSSL_VERSION_NUMBER <= 0x10100000)
312         SSL_COMP_free_compression_methods();
313 #endif
314         ERR_free_strings();
315         EVP_cleanup();
316         CRYPTO_cleanup_all_ex_data();
317 #endif
318 #endif
319 }
320
321 LWS_VISIBLE void
322 lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi)
323 {
324         struct lws_context *context = wsi->context;
325         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
326
327         if (!wsi->pending_read_list_prev &&
328             !wsi->pending_read_list_next &&
329             pt->pending_read_list != wsi)
330                 /* we are not on the list */
331                 return;
332
333         /* point previous guy's next to our next */
334         if (!wsi->pending_read_list_prev)
335                 pt->pending_read_list = wsi->pending_read_list_next;
336         else
337                 wsi->pending_read_list_prev->pending_read_list_next =
338                         wsi->pending_read_list_next;
339
340         /* point next guy's previous to our previous */
341         if (wsi->pending_read_list_next)
342                 wsi->pending_read_list_next->pending_read_list_prev =
343                         wsi->pending_read_list_prev;
344
345         wsi->pending_read_list_prev = NULL;
346         wsi->pending_read_list_next = NULL;
347 }
348
349 LWS_VISIBLE int
350 lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len)
351 {
352         struct lws_context *context = wsi->context;
353         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
354         int n = 0;
355 #if !defined(LWS_WITH_ESP32)
356         int ssl_read_errno = 0;
357 #endif
358
359         if (!wsi->ssl)
360                 return lws_ssl_capable_read_no_ssl(wsi, buf, len);
361
362         lws_stats_atomic_bump(context, pt, LWSSTATS_C_API_READ, 1);
363
364         errno = 0;
365         n = SSL_read(wsi->ssl, buf, len);
366 #if defined(LWS_WITH_ESP32)
367         if (!n && errno == ENOTCONN) {
368                 lwsl_debug("%p: SSL_read ENOTCONN\n", wsi);
369                 return LWS_SSL_CAPABLE_ERROR;
370         }
371 #endif
372 #if defined(LWS_WITH_STATS)
373         if (!wsi->seen_rx) {
374                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_SSL_RX_DELAY,
375                                 time_in_microseconds() - wsi->accept_start_us);
376                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_SSL_CONNS_HAD_RX, 1);
377                 wsi->seen_rx = 1;
378         }
379 #endif
380
381
382         lwsl_debug("%p: SSL_read says %d\n", wsi, n);
383         /* manpage: returning 0 means connection shut down */
384         if (!n) {
385                 n = lws_ssl_get_error(wsi, n);
386                 lwsl_debug("%p: ssl err %d errno %d\n", wsi, n, errno);
387                 if (n == SSL_ERROR_ZERO_RETURN)
388                         return LWS_SSL_CAPABLE_ERROR;
389
390                 if (n == SSL_ERROR_SYSCALL) {
391 #if !defined(LWS_WITH_ESP32)
392                         int err = ERR_get_error();
393                         if (err == 0 && (ssl_read_errno == EPIPE ||
394                                          ssl_read_errno == ECONNABORTED ||
395                                          ssl_read_errno == 0))
396                                 return LWS_SSL_CAPABLE_ERROR;
397 #endif
398                 }
399
400                 lwsl_err("%s failed: %s\n",__func__,
401                          ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
402                 lws_ssl_elaborate_error();
403
404                 return LWS_SSL_CAPABLE_ERROR;
405         }
406
407         if (n < 0) {
408                 n = lws_ssl_get_error(wsi, n);
409                 // lwsl_notice("get_ssl_err result %d\n", n);
410                 if (n ==  SSL_ERROR_WANT_READ || SSL_want_read(wsi->ssl)) {
411                         lwsl_debug("%s: WANT_READ\n", __func__);
412                         lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi);
413                         return LWS_SSL_CAPABLE_MORE_SERVICE;
414                 }
415                 if (n ==  SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->ssl)) {
416                         lwsl_debug("%s: WANT_WRITE\n", __func__);
417                         lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi);
418                         return LWS_SSL_CAPABLE_MORE_SERVICE;
419                 }
420
421
422                 lwsl_err("%s failed2: %s\n",__func__,
423                                  ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
424                         lws_ssl_elaborate_error();
425
426                 return LWS_SSL_CAPABLE_ERROR;
427         }
428
429         lws_stats_atomic_bump(context, pt, LWSSTATS_B_READ, n);
430
431         if (wsi->vhost)
432                 wsi->vhost->conn_stats.rx += n;
433
434         lws_restart_ws_ping_pong_timer(wsi);
435
436         /*
437          * if it was our buffer that limited what we read,
438          * check if SSL has additional data pending inside SSL buffers.
439          *
440          * Because these won't signal at the network layer with POLLIN
441          * and if we don't realize, this data will sit there forever
442          */
443         if (n != len)
444                 goto bail;
445         if (!wsi->ssl)
446                 goto bail;
447
448         if (!SSL_pending(wsi->ssl))
449                 goto bail;
450
451         if (wsi->pending_read_list_next)
452                 return n;
453         if (wsi->pending_read_list_prev)
454                 return n;
455         if (pt->pending_read_list == wsi)
456                 return n;
457
458         /* add us to the linked list of guys with pending ssl */
459         if (pt->pending_read_list)
460                 pt->pending_read_list->pending_read_list_prev = wsi;
461
462         wsi->pending_read_list_next = pt->pending_read_list;
463         wsi->pending_read_list_prev = NULL;
464         pt->pending_read_list = wsi;
465
466         return n;
467 bail:
468         lws_ssl_remove_wsi_from_buffered_list(wsi);
469
470         return n;
471 }
472
473 LWS_VISIBLE int
474 lws_ssl_pending(struct lws *wsi)
475 {
476         if (!wsi->ssl)
477                 return 0;
478
479         return SSL_pending(wsi->ssl);
480 }
481
482 LWS_VISIBLE int
483 lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len)
484 {
485         int n;
486 #if !defined(LWS_WITH_ESP32)
487         int ssl_read_errno = 0;
488 #endif
489
490         if (!wsi->ssl)
491                 return lws_ssl_capable_write_no_ssl(wsi, buf, len);
492
493         n = SSL_write(wsi->ssl, buf, len);
494         if (n > 0)
495                 return n;
496
497         n = lws_ssl_get_error(wsi, n);
498         if (n == SSL_ERROR_WANT_READ || n == SSL_ERROR_WANT_WRITE) {
499                 if (n == SSL_ERROR_WANT_WRITE) {
500                         lwsl_debug("%s: WANT_WRITE\n", __func__);
501                         lws_set_blocking_send(wsi);
502                 }
503                 return LWS_SSL_CAPABLE_MORE_SERVICE;
504         }
505
506  if (n == SSL_ERROR_ZERO_RETURN)
507   return LWS_SSL_CAPABLE_ERROR;
508
509 #if !defined(LWS_WITH_ESP32)
510  if (n == SSL_ERROR_SYSCALL) {
511
512   int err = ERR_get_error();
513   if (err == 0
514     && (ssl_read_errno == EPIPE
515      || ssl_read_errno == ECONNABORTED
516      || ssl_read_errno == 0))
517     return LWS_SSL_CAPABLE_ERROR;
518  }
519 #endif
520
521  lwsl_err("%s failed: %s\n",__func__,
522    ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
523         lws_ssl_elaborate_error();
524
525         return LWS_SSL_CAPABLE_ERROR;
526 }
527
528 static int
529 lws_gate_accepts(struct lws_context *context, int on)
530 {
531         struct lws_vhost *v = context->vhost_list;
532
533         lwsl_info("gating accepts %d\n", on);
534         context->ssl_gate_accepts = !on;
535 #if defined(LWS_WITH_STATS)
536         context->updated = 1;
537 #endif
538
539         while (v) {
540                 if (v->use_ssl &&  v->lserv_wsi) /* gate ability to accept incoming connections */
541                         if (lws_change_pollfd(v->lserv_wsi, (LWS_POLLIN) * !on, (LWS_POLLIN) * on))
542                                 lwsl_err("Unable to set accept POLLIN %d\n", on);
543
544                 v = v->vhost_next;
545         }
546
547         return 0;
548 }
549
550 void
551 lws_ssl_info_callback(const SSL *ssl, int where, int ret)
552 {
553         struct lws *wsi;
554         struct lws_context *context;
555         struct lws_ssl_info si;
556
557         context = (struct lws_context *)SSL_CTX_get_ex_data(
558                                         SSL_get_SSL_CTX(ssl),
559                                         openssl_SSL_CTX_private_data_index);
560         if (!context)
561                 return;
562         wsi = wsi_from_fd(context, SSL_get_fd(ssl));
563         if (!wsi)
564                 return;
565
566         if (!(where & wsi->vhost->ssl_info_event_mask))
567                 return;
568
569         si.where = where;
570         si.ret = ret;
571
572         if (user_callback_handle_rxflow(wsi->protocol->callback,
573                                                    wsi, LWS_CALLBACK_SSL_INFO,
574                                                    wsi->user_space, &si, 0))
575                 lws_set_timeout(wsi, PENDING_TIMEOUT_KILLED_BY_SSL_INFO, -1);
576 }
577
578
579 LWS_VISIBLE int
580 lws_ssl_close(struct lws *wsi)
581 {
582         lws_sockfd_type n;
583
584         if (!wsi->ssl)
585                 return 0; /* not handled */
586
587 #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
588         /* kill ssl callbacks, becausse we will remove the fd from the
589          * table linking it to the wsi
590          */
591         if (wsi->vhost->ssl_info_event_mask)
592                 SSL_set_info_callback(wsi->ssl, NULL);
593 #endif
594
595         n = SSL_get_fd(wsi->ssl);
596         SSL_shutdown(wsi->ssl);
597         compatible_close(n);
598         SSL_free(wsi->ssl);
599         wsi->ssl = NULL;
600
601         if (wsi->context->simultaneous_ssl_restriction &&
602             wsi->context->simultaneous_ssl-- ==
603                             wsi->context->simultaneous_ssl_restriction)
604                 /* we made space and can do an accept */
605                 lws_gate_accepts(wsi->context, 1);
606 #if defined(LWS_WITH_STATS)
607         wsi->context->updated = 1;
608 #endif
609
610         return 1; /* handled */
611 }
612
613 /* leave all wsi close processing to the caller */
614
615 LWS_VISIBLE int
616 lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd)
617 {
618         struct lws_context *context = wsi->context;
619         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
620         int n, m;
621 #if !defined(USE_WOLFSSL) && !defined(LWS_WITH_ESP32)
622         BIO *bio;
623 #endif
624         char buf[256];
625
626         if (!LWS_SSL_ENABLED(wsi->vhost))
627                 return 0;
628
629         switch (wsi->mode) {
630         case LWSCM_SSL_INIT:
631         case LWSCM_SSL_INIT_RAW:
632                 if (wsi->ssl)
633                         lwsl_err("%s: leaking ssl\n", __func__);
634                 if (accept_fd == LWS_SOCK_INVALID)
635                         assert(0);
636                 if (context->simultaneous_ssl_restriction &&
637                     context->simultaneous_ssl >= context->simultaneous_ssl_restriction) {
638                         lwsl_notice("unable to deal with SSL connection\n");
639                         return 1;
640                 }
641                 errno = 0;
642                 wsi->ssl = SSL_new(wsi->vhost->ssl_ctx);
643                 if (wsi->ssl == NULL) {
644                         lwsl_err("SSL_new failed: %d (errno %d)\n",
645                                  lws_ssl_get_error(wsi, 0), errno);
646
647                         lws_ssl_elaborate_error();
648                         if (accept_fd != LWS_SOCK_INVALID)
649                                 compatible_close(accept_fd);
650                         goto fail;
651                 }
652 #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)
653                 if (wsi->vhost->ssl_info_event_mask)
654                         SSL_set_info_callback(wsi->ssl, lws_ssl_info_callback);
655 #endif
656                 if (context->simultaneous_ssl_restriction &&
657                     ++context->simultaneous_ssl == context->simultaneous_ssl_restriction)
658                         /* that was the last allowed SSL connection */
659                         lws_gate_accepts(context, 0);
660 #if defined(LWS_WITH_STATS)
661         context->updated = 1;
662 #endif
663
664 #if !defined(LWS_WITH_ESP32)
665                 SSL_set_ex_data(wsi->ssl,
666                         openssl_websocket_private_data_index, wsi);
667 #endif
668                 SSL_set_fd(wsi->ssl, accept_fd);
669
670 #ifdef USE_WOLFSSL
671 #ifdef USE_OLD_CYASSL
672                 CyaSSL_set_using_nonblock(wsi->ssl, 1);
673 #else
674                 wolfSSL_set_using_nonblock(wsi->ssl, 1);
675 #endif
676 #else
677 #if defined(LWS_WITH_ESP32)
678                 lws_plat_set_socket_options(wsi->vhost, accept_fd);
679 #else
680                 SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
681                 bio = SSL_get_rbio(wsi->ssl);
682                 if (bio)
683                         BIO_set_nbio(bio, 1); /* nonblocking */
684                 else
685                         lwsl_notice("NULL rbio\n");
686                 bio = SSL_get_wbio(wsi->ssl);
687                 if (bio)
688                         BIO_set_nbio(bio, 1); /* nonblocking */
689                 else
690                         lwsl_notice("NULL rbio\n");
691 #endif
692 #endif
693
694                 /*
695                  * we are not accepted yet, but we need to enter ourselves
696                  * as a live connection.  That way we can retry when more
697                  * pieces come if we're not sorted yet
698                  */
699
700                 if (wsi->mode == LWSCM_SSL_INIT)
701                         wsi->mode = LWSCM_SSL_ACK_PENDING;
702                 else
703                         wsi->mode = LWSCM_SSL_ACK_PENDING_RAW;
704
705                 if (insert_wsi_socket_into_fds(context, wsi)) {
706                         lwsl_err("%s: failed to insert into fds\n", __func__);
707                         goto fail;
708                 }
709
710                 lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,
711                                 context->timeout_secs);
712
713                 lwsl_debug("inserted SSL accept into fds, trying SSL_accept\n");
714
715                 /* fallthru */
716
717         case LWSCM_SSL_ACK_PENDING:
718         case LWSCM_SSL_ACK_PENDING_RAW:
719                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
720                         lwsl_err("%s: lws_change_pollfd failed\n", __func__);
721                         goto fail;
722                 }
723
724                 lws_latency_pre(context, wsi);
725
726                 if (wsi->vhost->allow_non_ssl_on_ssl_port) {
727
728                         n = recv(wsi->desc.sockfd, (char *)pt->serv_buf, context->pt_serv_buf_size,
729                                  MSG_PEEK);
730
731                 /*
732                  * optionally allow non-SSL connect on SSL listening socket
733                  * This is disabled by default, if enabled it goes around any
734                  * SSL-level access control (eg, client-side certs) so leave
735                  * it disabled unless you know it's not a problem for you
736                  */
737
738                         if (n >= 1 && pt->serv_buf[0] >= ' ') {
739                                 /*
740                                 * TLS content-type for Handshake is 0x16, and
741                                 * for ChangeCipherSpec Record, it's 0x14
742                                 *
743                                 * A non-ssl session will start with the HTTP
744                                 * method in ASCII.  If we see it's not a legit
745                                 * SSL handshake kill the SSL for this
746                                 * connection and try to handle as a HTTP
747                                 * connection upgrade directly.
748                                 */
749                                 wsi->use_ssl = 0;
750
751                                 SSL_shutdown(wsi->ssl);
752                                 SSL_free(wsi->ssl);
753                                 wsi->ssl = NULL;
754                                 if (lws_check_opt(context->options,
755                                     LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS))
756                                         wsi->redirect_to_https = 1;
757                                 goto accepted;
758                         }
759                         if (!n) /*
760                                  * connection is gone, or nothing to read
761                                  * if it's gone, we will timeout on
762                                  * PENDING_TIMEOUT_SSL_ACCEPT
763                                  */
764                                 break;
765                         if (n < 0 && (LWS_ERRNO == LWS_EAGAIN ||
766                                       LWS_ERRNO == LWS_EWOULDBLOCK)) {
767                                 /*
768                                  * well, we get no way to know ssl or not
769                                  * so go around again waiting for something
770                                  * to come and give us a hint, or timeout the
771                                  * connection.
772                                  */
773                                 m = SSL_ERROR_WANT_READ;
774                                 goto go_again;
775                         }
776                 }
777
778                 /* normal SSL connection processing path */
779
780 #if defined(LWS_WITH_STATS)
781                 if (!wsi->accept_start_us)
782                         wsi->accept_start_us = time_in_microseconds();
783 #endif
784
785                 n = SSL_accept(wsi->ssl);
786                 lws_latency(context, wsi,
787                         "SSL_accept LWSCM_SSL_ACK_PENDING\n", n, n == 1);
788                 lwsl_info("SSL_accept says %d\n", n);
789                 if (n == 1)
790                         goto accepted;
791
792                 m = lws_ssl_get_error(wsi, n);
793
794 #if defined(LWS_WITH_ESP32)
795                 if (m == 5 && errno == 11)
796                         m = SSL_ERROR_WANT_READ;
797 #endif
798
799 go_again:
800                 if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->ssl)) {
801                         if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
802                                 lwsl_err("%s: WANT_READ change_pollfd failed\n", __func__);
803                                 goto fail;
804                         }
805
806                         lwsl_info("SSL_ERROR_WANT_READ\n");
807                         break;
808                 }
809                 if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->ssl)) {
810                         lwsl_debug("%s: WANT_WRITE\n", __func__);
811
812                         if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {
813                                 lwsl_err("%s: WANT_WRITE change_pollfd failed\n", __func__);
814                                 goto fail;
815                         }
816
817                         break;
818                 }
819                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_SSL_CONNECTIONS_FAILED, 1);
820                 lwsl_err("SSL_accept failed socket %u: %s\n", wsi->desc.sockfd,
821                          lws_ssl_get_error_string(m, n, buf, sizeof(buf)));
822                 lws_ssl_elaborate_error();
823                 goto fail;
824
825 accepted:
826                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, 1);
827 #if defined(LWS_WITH_STATS)
828                 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY, time_in_microseconds() - wsi->accept_start_us);
829                 wsi->accept_start_us = time_in_microseconds();
830 #endif
831
832                 /* OK, we are accepted... give him some time to negotiate */
833                 lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
834                                 context->timeout_secs);
835
836                 if (wsi->mode == LWSCM_SSL_ACK_PENDING_RAW)
837                         wsi->mode = LWSCM_RAW;
838                 else
839                         wsi->mode = LWSCM_HTTP_SERVING;
840
841                 lws_http2_configure_if_upgraded(wsi);
842
843                 lwsl_debug("accepted new SSL conn\n");
844                 break;
845         }
846
847         return 0;
848
849 fail:
850         return 1;
851 }
852
853 void
854 lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost)
855 {
856         if (vhost->ssl_ctx)
857                 SSL_CTX_free(vhost->ssl_ctx);
858
859         if (!vhost->user_supplied_ssl_ctx && vhost->ssl_client_ctx)
860                 SSL_CTX_free(vhost->ssl_client_ctx);
861 }
862
863 void
864 lws_ssl_context_destroy(struct lws_context *context)
865 {
866
867 #if !defined(LWS_WITH_ESP32)
868
869 // after 1.1.0 no need
870 #if (OPENSSL_VERSION_NUMBER <  0x10100000)
871 // <= 1.0.1f = old api, 1.0.1g+ = new api
872 #if (OPENSSL_VERSION_NUMBER <= 0x1000106f) || defined(USE_WOLFSSL)
873         ERR_remove_state(0);
874 #else
875 #if OPENSSL_VERSION_NUMBER >= 0x1010005f && \
876     !defined(LIBRESSL_VERSION_NUMBER) && \
877     !defined(OPENSSL_IS_BORINGSSL)
878         ERR_remove_thread_state();
879 #else
880         ERR_remove_thread_state(NULL);
881 #endif
882 #endif
883         // after 1.1.0 no need
884 #if  (OPENSSL_VERSION_NUMBER >= 0x10002000) && (OPENSSL_VERSION_NUMBER <= 0x10100000)
885         SSL_COMP_free_compression_methods();
886 #endif
887         ERR_free_strings();
888         EVP_cleanup();
889         CRYPTO_cleanup_all_ex_data();
890 #endif
891 #endif
892 }