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