[CVE-2016-3739] TLS certificate check bypass with mbedTLS/PolarSSL
[platform/upstream/curl.git] / lib / vtls / polarssl.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
9  * Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com>
10  *
11  * This software is licensed as described in the file COPYING, which
12  * you should have received as part of this distribution. The terms
13  * are also available at https://curl.haxx.se/docs/copyright.html.
14  *
15  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
16  * copies of the Software, and permit persons to whom the Software is
17  * furnished to do so, under the terms of the COPYING file.
18  *
19  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20  * KIND, either express or implied.
21  *
22  ***************************************************************************/
23
24 /*
25  * Source file for all PolarSSL-specific code for the TLS/SSL layer. No code
26  * but vtls.c should ever call or use these functions.
27  *
28  */
29
30 #include "curl_setup.h"
31
32 #ifdef USE_POLARSSL
33
34 #include <polarssl/net.h>
35 #include <polarssl/ssl.h>
36 #include <polarssl/certs.h>
37 #include <polarssl/x509.h>
38 #include <polarssl/version.h>
39
40 #if POLARSSL_VERSION_NUMBER < 0x01030000
41 #error too old PolarSSL
42 #endif
43
44 #include <polarssl/error.h>
45 #include <polarssl/entropy.h>
46 #include <polarssl/ctr_drbg.h>
47
48 #include "urldata.h"
49 #include "sendf.h"
50 #include "inet_pton.h"
51 #include "polarssl.h"
52 #include "vtls.h"
53 #include "parsedate.h"
54 #include "connect.h" /* for the connect timeout */
55 #include "select.h"
56 #include "rawstr.h"
57 #include "polarssl_threadlock.h"
58 #include "curl_printf.h"
59 #include "curl_memory.h"
60 /* The last #include file should be: */
61 #include "memdebug.h"
62
63 /* apply threading? */
64 #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
65 #define THREADING_SUPPORT
66 #endif
67
68 #if defined(THREADING_SUPPORT)
69 static entropy_context entropy;
70
71 static int  entropy_init_initialized  = 0;
72
73 /* start of entropy_init_mutex() */
74 static void entropy_init_mutex(entropy_context *ctx)
75 {
76   /* lock 0 = entropy_init_mutex() */
77   Curl_polarsslthreadlock_lock_function(0);
78   if(entropy_init_initialized == 0) {
79     entropy_init(ctx);
80     entropy_init_initialized = 1;
81   }
82   Curl_polarsslthreadlock_unlock_function(0);
83 }
84 /* end of entropy_init_mutex() */
85
86 /* start of entropy_func_mutex() */
87 static int entropy_func_mutex(void *data, unsigned char *output, size_t len)
88 {
89     int ret;
90     /* lock 1 = entropy_func_mutex() */
91     Curl_polarsslthreadlock_lock_function(1);
92     ret = entropy_func(data, output, len);
93     Curl_polarsslthreadlock_unlock_function(1);
94
95     return ret;
96 }
97 /* end of entropy_func_mutex() */
98
99 #endif /* THREADING_SUPPORT */
100
101 /* Define this to enable lots of debugging for PolarSSL */
102 #undef POLARSSL_DEBUG
103
104 #ifdef POLARSSL_DEBUG
105 static void polarssl_debug(void *context, int level, const char *line)
106 {
107   struct SessionHandle *data = NULL;
108
109   if(!context)
110     return;
111
112   data = (struct SessionHandle *)context;
113
114   infof(data, "%s", line);
115   (void) level;
116 }
117 #else
118 #endif
119
120 /* ALPN for http2? */
121 #ifdef POLARSSL_SSL_ALPN
122 #  define HAS_ALPN
123 #endif
124
125 static Curl_recv polarssl_recv;
126 static Curl_send polarssl_send;
127
128
129 static CURLcode
130 polarssl_connect_step1(struct connectdata *conn,
131                      int sockindex)
132 {
133   struct SessionHandle *data = conn->data;
134   struct ssl_connect_data* connssl = &conn->ssl[sockindex];
135
136   bool sni = TRUE; /* default is SNI enabled */
137   int ret = -1;
138 #ifdef ENABLE_IPV6
139   struct in6_addr addr;
140 #else
141   struct in_addr addr;
142 #endif
143   void *old_session = NULL;
144   size_t old_session_size = 0;
145   char errorbuf[128];
146   errorbuf[0]=0;
147
148   /* PolarSSL only supports SSLv3 and TLSv1 */
149   if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
150     failf(data, "PolarSSL does not support SSLv2");
151     return CURLE_SSL_CONNECT_ERROR;
152   }
153   else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
154     sni = FALSE; /* SSLv3 has no SNI */
155
156 #ifdef THREADING_SUPPORT
157   entropy_init_mutex(&entropy);
158
159   if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func_mutex, &entropy,
160                                connssl->ssn.id, connssl->ssn.length)) != 0) {
161 #ifdef POLARSSL_ERROR_C
162      error_strerror(ret, errorbuf, sizeof(errorbuf));
163 #endif /* POLARSSL_ERROR_C */
164      failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
165                                                             -ret, errorbuf);
166   }
167 #else
168   entropy_init(&connssl->entropy);
169
170   if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func, &connssl->entropy,
171                                 connssl->ssn.id, connssl->ssn.length)) != 0) {
172 #ifdef POLARSSL_ERROR_C
173      error_strerror(ret, errorbuf, sizeof(errorbuf));
174 #endif /* POLARSSL_ERROR_C */
175      failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
176                                                             -ret, errorbuf);
177   }
178 #endif /* THREADING_SUPPORT */
179
180   /* Load the trusted CA */
181   memset(&connssl->cacert, 0, sizeof(x509_crt));
182
183   if(data->set.str[STRING_SSL_CAFILE]) {
184     ret = x509_crt_parse_file(&connssl->cacert,
185                               data->set.str[STRING_SSL_CAFILE]);
186
187     if(ret<0) {
188 #ifdef POLARSSL_ERROR_C
189       error_strerror(ret, errorbuf, sizeof(errorbuf));
190 #endif /* POLARSSL_ERROR_C */
191       failf(data, "Error reading ca cert file %s - PolarSSL: (-0x%04X) %s",
192             data->set.str[STRING_SSL_CAFILE], -ret, errorbuf);
193
194       if(data->set.ssl.verifypeer)
195         return CURLE_SSL_CACERT_BADFILE;
196     }
197   }
198
199   if(data->set.str[STRING_SSL_CAPATH]) {
200     ret = x509_crt_parse_path(&connssl->cacert,
201                               data->set.str[STRING_SSL_CAPATH]);
202
203     if(ret<0) {
204 #ifdef POLARSSL_ERROR_C
205       error_strerror(ret, errorbuf, sizeof(errorbuf));
206 #endif /* POLARSSL_ERROR_C */
207       failf(data, "Error reading ca cert path %s - PolarSSL: (-0x%04X) %s",
208             data->set.str[STRING_SSL_CAPATH], -ret, errorbuf);
209
210       if(data->set.ssl.verifypeer)
211         return CURLE_SSL_CACERT_BADFILE;
212     }
213   }
214
215   /* Load the client certificate */
216   memset(&connssl->clicert, 0, sizeof(x509_crt));
217
218   if(data->set.str[STRING_CERT]) {
219     ret = x509_crt_parse_file(&connssl->clicert,
220                               data->set.str[STRING_CERT]);
221
222     if(ret) {
223 #ifdef POLARSSL_ERROR_C
224       error_strerror(ret, errorbuf, sizeof(errorbuf));
225 #endif /* POLARSSL_ERROR_C */
226       failf(data, "Error reading client cert file %s - PolarSSL: (-0x%04X) %s",
227             data->set.str[STRING_CERT], -ret, errorbuf);
228
229       return CURLE_SSL_CERTPROBLEM;
230     }
231   }
232
233   /* Load the client private key */
234   if(data->set.str[STRING_KEY]) {
235     pk_context pk;
236     pk_init(&pk);
237     ret = pk_parse_keyfile(&pk, data->set.str[STRING_KEY],
238                            data->set.str[STRING_KEY_PASSWD]);
239     if(ret == 0 && !pk_can_do(&pk, POLARSSL_PK_RSA))
240       ret = POLARSSL_ERR_PK_TYPE_MISMATCH;
241     if(ret == 0)
242       rsa_copy(&connssl->rsa, pk_rsa(pk));
243     else
244       rsa_free(&connssl->rsa);
245     pk_free(&pk);
246
247     if(ret) {
248 #ifdef POLARSSL_ERROR_C
249       error_strerror(ret, errorbuf, sizeof(errorbuf));
250 #endif /* POLARSSL_ERROR_C */
251       failf(data, "Error reading private key %s - PolarSSL: (-0x%04X) %s",
252             data->set.str[STRING_KEY], -ret, errorbuf);
253
254       return CURLE_SSL_CERTPROBLEM;
255     }
256   }
257
258   /* Load the CRL */
259   memset(&connssl->crl, 0, sizeof(x509_crl));
260
261   if(data->set.str[STRING_SSL_CRLFILE]) {
262     ret = x509_crl_parse_file(&connssl->crl,
263                               data->set.str[STRING_SSL_CRLFILE]);
264
265     if(ret) {
266 #ifdef POLARSSL_ERROR_C
267       error_strerror(ret, errorbuf, sizeof(errorbuf));
268 #endif /* POLARSSL_ERROR_C */
269       failf(data, "Error reading CRL file %s - PolarSSL: (-0x%04X) %s",
270             data->set.str[STRING_SSL_CRLFILE], -ret, errorbuf);
271
272       return CURLE_SSL_CRL_BADFILE;
273     }
274   }
275
276   infof(data, "PolarSSL: Connecting to %s:%d\n",
277         conn->host.name, conn->remote_port);
278
279   if(ssl_init(&connssl->ssl)) {
280     failf(data, "PolarSSL: ssl_init failed");
281     return CURLE_SSL_CONNECT_ERROR;
282   }
283
284   switch(data->set.ssl.version) {
285   default:
286   case CURL_SSLVERSION_DEFAULT:
287   case CURL_SSLVERSION_TLSv1:
288     ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
289                         SSL_MINOR_VERSION_1);
290     break;
291   case CURL_SSLVERSION_SSLv3:
292     ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
293                         SSL_MINOR_VERSION_0);
294     ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
295                         SSL_MINOR_VERSION_0);
296     infof(data, "PolarSSL: Forced min. SSL Version to be SSLv3\n");
297     break;
298   case CURL_SSLVERSION_TLSv1_0:
299     ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
300                         SSL_MINOR_VERSION_1);
301     ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
302                         SSL_MINOR_VERSION_1);
303     infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.0\n");
304     break;
305   case CURL_SSLVERSION_TLSv1_1:
306     ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
307                         SSL_MINOR_VERSION_2);
308     ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
309                         SSL_MINOR_VERSION_2);
310     infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.1\n");
311     break;
312   case CURL_SSLVERSION_TLSv1_2:
313     ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
314                         SSL_MINOR_VERSION_3);
315     ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
316                         SSL_MINOR_VERSION_3);
317     infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.2\n");
318     break;
319   }
320
321   ssl_set_endpoint(&connssl->ssl, SSL_IS_CLIENT);
322   ssl_set_authmode(&connssl->ssl, SSL_VERIFY_OPTIONAL);
323
324   ssl_set_rng(&connssl->ssl, ctr_drbg_random,
325               &connssl->ctr_drbg);
326   ssl_set_bio(&connssl->ssl,
327               net_recv, &conn->sock[sockindex],
328               net_send, &conn->sock[sockindex]);
329
330   ssl_set_ciphersuites(&connssl->ssl, ssl_list_ciphersuites());
331   if(!Curl_ssl_getsessionid(conn, &old_session, &old_session_size)) {
332     memcpy(&connssl->ssn, old_session, old_session_size);
333     infof(data, "PolarSSL re-using session\n");
334   }
335
336   ssl_set_session(&connssl->ssl,
337                   &connssl->ssn);
338
339   ssl_set_ca_chain(&connssl->ssl,
340                    &connssl->cacert,
341                    &connssl->crl,
342                    conn->host.name);
343
344   ssl_set_own_cert_rsa(&connssl->ssl,
345                        &connssl->clicert, &connssl->rsa);
346
347   if(ssl_set_hostname(&connssl->ssl, conn->host.name)) {
348     /* ssl_set_hostname() sets the name to use in CN/SAN checks *and* the name
349        to set in the SNI extension. So even if curl connects to a host
350        specified as an IP address, this function must be used. */
351     failf(data, "couldn't set hostname in PolarSSL");
352     return CURLE_SSL_CONNECT_ERROR;
353   }
354
355 #ifdef HAS_ALPN
356   if(data->set.ssl_enable_alpn) {
357     static const char* protocols[3];
358     int cur = 0;
359
360 #ifdef USE_NGHTTP2
361     if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
362       protocols[cur++] = NGHTTP2_PROTO_VERSION_ID;
363       infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
364     }
365 #endif
366
367     protocols[cur++] = ALPN_HTTP_1_1;
368     infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
369
370     protocols[cur] = NULL;
371
372     ssl_set_alpn_protocols(&connssl->ssl, protocols);
373   }
374 #endif
375
376 #ifdef POLARSSL_DEBUG
377   ssl_set_dbg(&connssl->ssl, polarssl_debug, data);
378 #endif
379
380   connssl->connecting_state = ssl_connect_2;
381
382   return CURLE_OK;
383 }
384
385 static CURLcode
386 polarssl_connect_step2(struct connectdata *conn,
387                      int sockindex)
388 {
389   int ret;
390   struct SessionHandle *data = conn->data;
391   struct ssl_connect_data* connssl = &conn->ssl[sockindex];
392   char buffer[1024];
393
394   char errorbuf[128];
395   errorbuf[0] = 0;
396
397   conn->recv[sockindex] = polarssl_recv;
398   conn->send[sockindex] = polarssl_send;
399
400   ret = ssl_handshake(&connssl->ssl);
401
402   switch(ret) {
403   case 0:
404     break;
405
406   case POLARSSL_ERR_NET_WANT_READ:
407     connssl->connecting_state = ssl_connect_2_reading;
408     return CURLE_OK;
409
410   case POLARSSL_ERR_NET_WANT_WRITE:
411     connssl->connecting_state = ssl_connect_2_writing;
412     return CURLE_OK;
413
414   default:
415 #ifdef POLARSSL_ERROR_C
416     error_strerror(ret, errorbuf, sizeof(errorbuf));
417 #endif /* POLARSSL_ERROR_C */
418     failf(data, "ssl_handshake returned - PolarSSL: (-0x%04X) %s",
419           -ret, errorbuf);
420     return CURLE_SSL_CONNECT_ERROR;
421   }
422
423   infof(data, "PolarSSL: Handshake complete, cipher is %s\n",
424         ssl_get_ciphersuite(&conn->ssl[sockindex].ssl) );
425
426   ret = ssl_get_verify_result(&conn->ssl[sockindex].ssl);
427
428   if(ret && data->set.ssl.verifypeer) {
429     if(ret & BADCERT_EXPIRED)
430       failf(data, "Cert verify failed: BADCERT_EXPIRED");
431
432     if(ret & BADCERT_REVOKED) {
433       failf(data, "Cert verify failed: BADCERT_REVOKED");
434       return CURLE_SSL_CACERT;
435     }
436
437     if(ret & BADCERT_CN_MISMATCH)
438       failf(data, "Cert verify failed: BADCERT_CN_MISMATCH");
439
440     if(ret & BADCERT_NOT_TRUSTED)
441       failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED");
442
443     return CURLE_PEER_FAILED_VERIFICATION;
444   }
445
446   if(ssl_get_peer_cert(&(connssl->ssl))) {
447     /* If the session was resumed, there will be no peer certs */
448     memset(buffer, 0, sizeof(buffer));
449
450     if(x509_crt_info(buffer, sizeof(buffer), (char *)"* ",
451                      ssl_get_peer_cert(&(connssl->ssl))) != -1)
452       infof(data, "Dumping cert info:\n%s\n", buffer);
453   }
454
455 #ifdef HAS_ALPN
456   if(data->set.ssl_enable_alpn) {
457     const char *next_protocol = ssl_get_alpn_protocol(&connssl->ssl);
458
459     if(next_protocol != NULL) {
460       infof(data, "ALPN, server accepted to use %s\n", next_protocol);
461
462 #ifdef USE_NGHTTP2
463       if(!strncmp(next_protocol, NGHTTP2_PROTO_VERSION_ID,
464                   NGHTTP2_PROTO_VERSION_ID_LEN)) {
465         conn->negnpn = CURL_HTTP_VERSION_2;
466       }
467       else
468 #endif
469       if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH)) {
470         conn->negnpn = CURL_HTTP_VERSION_1_1;
471       }
472     }
473     else
474       infof(data, "ALPN, server did not agree to a protocol\n");
475   }
476 #endif
477
478   connssl->connecting_state = ssl_connect_3;
479   infof(data, "SSL connected\n");
480
481   return CURLE_OK;
482 }
483
484 static CURLcode
485 polarssl_connect_step3(struct connectdata *conn,
486                      int sockindex)
487 {
488   CURLcode result = CURLE_OK;
489   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
490   struct SessionHandle *data = conn->data;
491   void *old_ssl_sessionid = NULL;
492   ssl_session *our_ssl_sessionid = &conn->ssl[sockindex].ssn;
493   bool incache;
494
495   DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
496
497   /* Save the current session data for possible re-use */
498   incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL));
499   if(incache) {
500     if(old_ssl_sessionid != our_ssl_sessionid) {
501       infof(data, "old SSL session ID is stale, removing\n");
502       Curl_ssl_delsessionid(conn, old_ssl_sessionid);
503       incache = FALSE;
504     }
505   }
506
507   if(!incache) {
508     void *new_session = malloc(sizeof(ssl_session));
509
510     if(new_session) {
511       memcpy(new_session, our_ssl_sessionid, sizeof(ssl_session));
512
513       result = Curl_ssl_addsessionid(conn, new_session, sizeof(ssl_session));
514     }
515     else
516       result = CURLE_OUT_OF_MEMORY;
517
518     if(result) {
519       failf(data, "failed to store ssl session");
520       return result;
521     }
522   }
523
524   connssl->connecting_state = ssl_connect_done;
525
526   return CURLE_OK;
527 }
528
529 static ssize_t polarssl_send(struct connectdata *conn,
530                              int sockindex,
531                              const void *mem,
532                              size_t len,
533                              CURLcode *curlcode)
534 {
535   int ret = -1;
536
537   ret = ssl_write(&conn->ssl[sockindex].ssl,
538                   (unsigned char *)mem, len);
539
540   if(ret < 0) {
541     *curlcode = (ret == POLARSSL_ERR_NET_WANT_WRITE) ?
542       CURLE_AGAIN : CURLE_SEND_ERROR;
543     ret = -1;
544   }
545
546   return ret;
547 }
548
549 void Curl_polarssl_close(struct connectdata *conn, int sockindex)
550 {
551   rsa_free(&conn->ssl[sockindex].rsa);
552   x509_crt_free(&conn->ssl[sockindex].clicert);
553   x509_crt_free(&conn->ssl[sockindex].cacert);
554   x509_crl_free(&conn->ssl[sockindex].crl);
555   ssl_free(&conn->ssl[sockindex].ssl);
556 }
557
558 static ssize_t polarssl_recv(struct connectdata *conn,
559                              int num,
560                              char *buf,
561                              size_t buffersize,
562                              CURLcode *curlcode)
563 {
564   int ret = -1;
565   ssize_t len = -1;
566
567   memset(buf, 0, buffersize);
568   ret = ssl_read(&conn->ssl[num].ssl, (unsigned char *)buf, buffersize);
569
570   if(ret <= 0) {
571     if(ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
572       return 0;
573
574     *curlcode = (ret == POLARSSL_ERR_NET_WANT_READ) ?
575       CURLE_AGAIN : CURLE_RECV_ERROR;
576     return -1;
577   }
578
579   len = ret;
580
581   return len;
582 }
583
584 void Curl_polarssl_session_free(void *ptr)
585 {
586   free(ptr);
587 }
588
589 /* 1.3.10 was the first rebranded version. All new releases (in 1.3 branch and
590    higher) will be mbed TLS branded.. */
591
592 size_t Curl_polarssl_version(char *buffer, size_t size)
593 {
594   unsigned int version = version_get_number();
595   return snprintf(buffer, size, "%s/%d.%d.%d",
596                   version >= 0x01030A00?"mbedTLS":"PolarSSL",
597                   version>>24, (version>>16)&0xff, (version>>8)&0xff);
598 }
599
600 static CURLcode
601 polarssl_connect_common(struct connectdata *conn,
602                         int sockindex,
603                         bool nonblocking,
604                         bool *done)
605 {
606   CURLcode result;
607   struct SessionHandle *data = conn->data;
608   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
609   curl_socket_t sockfd = conn->sock[sockindex];
610   long timeout_ms;
611   int what;
612
613   /* check if the connection has already been established */
614   if(ssl_connection_complete == connssl->state) {
615     *done = TRUE;
616     return CURLE_OK;
617   }
618
619   if(ssl_connect_1 == connssl->connecting_state) {
620     /* Find out how much more time we're allowed */
621     timeout_ms = Curl_timeleft(data, NULL, TRUE);
622
623     if(timeout_ms < 0) {
624       /* no need to continue if time already is up */
625       failf(data, "SSL connection timeout");
626       return CURLE_OPERATION_TIMEDOUT;
627     }
628
629     result = polarssl_connect_step1(conn, sockindex);
630     if(result)
631       return result;
632   }
633
634   while(ssl_connect_2 == connssl->connecting_state ||
635         ssl_connect_2_reading == connssl->connecting_state ||
636         ssl_connect_2_writing == connssl->connecting_state) {
637
638     /* check allowed time left */
639     timeout_ms = Curl_timeleft(data, NULL, TRUE);
640
641     if(timeout_ms < 0) {
642       /* no need to continue if time already is up */
643       failf(data, "SSL connection timeout");
644       return CURLE_OPERATION_TIMEDOUT;
645     }
646
647     /* if ssl is expecting something, check if it's available. */
648     if(connssl->connecting_state == ssl_connect_2_reading ||
649        connssl->connecting_state == ssl_connect_2_writing) {
650
651       curl_socket_t writefd = ssl_connect_2_writing==
652         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
653       curl_socket_t readfd = ssl_connect_2_reading==
654         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
655
656       what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms);
657       if(what < 0) {
658         /* fatal error */
659         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
660         return CURLE_SSL_CONNECT_ERROR;
661       }
662       else if(0 == what) {
663         if(nonblocking) {
664           *done = FALSE;
665           return CURLE_OK;
666         }
667         else {
668           /* timeout */
669           failf(data, "SSL connection timeout");
670           return CURLE_OPERATION_TIMEDOUT;
671         }
672       }
673       /* socket is readable or writable */
674     }
675
676     /* Run transaction, and return to the caller if it failed or if
677      * this connection is part of a multi handle and this loop would
678      * execute again. This permits the owner of a multi handle to
679      * abort a connection attempt before step2 has completed while
680      * ensuring that a client using select() or epoll() will always
681      * have a valid fdset to wait on.
682      */
683     result = polarssl_connect_step2(conn, sockindex);
684     if(result || (nonblocking &&
685                   (ssl_connect_2 == connssl->connecting_state ||
686                    ssl_connect_2_reading == connssl->connecting_state ||
687                    ssl_connect_2_writing == connssl->connecting_state)))
688       return result;
689
690   } /* repeat step2 until all transactions are done. */
691
692   if(ssl_connect_3 == connssl->connecting_state) {
693     result = polarssl_connect_step3(conn, sockindex);
694     if(result)
695       return result;
696   }
697
698   if(ssl_connect_done == connssl->connecting_state) {
699     connssl->state = ssl_connection_complete;
700     conn->recv[sockindex] = polarssl_recv;
701     conn->send[sockindex] = polarssl_send;
702     *done = TRUE;
703   }
704   else
705     *done = FALSE;
706
707   /* Reset our connect state machine */
708   connssl->connecting_state = ssl_connect_1;
709
710   return CURLE_OK;
711 }
712
713 CURLcode
714 Curl_polarssl_connect_nonblocking(struct connectdata *conn,
715                                 int sockindex,
716                                 bool *done)
717 {
718   return polarssl_connect_common(conn, sockindex, TRUE, done);
719 }
720
721
722 CURLcode
723 Curl_polarssl_connect(struct connectdata *conn,
724                     int sockindex)
725 {
726   CURLcode result;
727   bool done = FALSE;
728
729   result = polarssl_connect_common(conn, sockindex, FALSE, &done);
730   if(result)
731     return result;
732
733   DEBUGASSERT(done);
734
735   return CURLE_OK;
736 }
737
738 /*
739  * return 0 error initializing SSL
740  * return 1 SSL initialized successfully
741  */
742 int Curl_polarssl_init(void)
743 {
744   return Curl_polarsslthreadlock_thread_setup();
745 }
746
747 void Curl_polarssl_cleanup(void)
748 {
749   (void)Curl_polarsslthreadlock_thread_cleanup();
750 }
751
752 #endif /* USE_POLARSSL */