3 * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include <pj/ssl_sock.h>
20 #include <pj/activesock.h>
21 #include <pj/compat/socket.h>
22 #include <pj/assert.h>
30 #include <pj/string.h>
34 /* Only build when PJ_HAS_SSL_SOCK is enabled */
35 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK!=0
37 #define THIS_FILE "ssl_sock_ossl.c"
39 /* Workaround for ticket #985 */
40 #define DELAYED_CLOSE_TIMEOUT 200
43 #define MAX_CIPHERS 100
46 * Include OpenSSL headers
48 #include <openssl/bio.h>
49 #include <openssl/ssl.h>
50 #include <openssl/err.h>
51 #include <openssl/x509v3.h>
56 # pragma comment( lib, "libeay32MTd")
57 # pragma comment( lib, "ssleay32MTd")
59 # pragma comment( lib, "libeay32MT")
60 # pragma comment( lib, "ssleay32MT")
66 * SSL/TLS state enumeration.
70 SSL_STATE_HANDSHAKING,
75 * Internal timer types.
80 TIMER_HANDSHAKE_TIMEOUT,
85 * Structure of SSL socket read buffer.
87 typedef struct read_data_t
94 * Get the offset of pointer to read-buffer of SSL socket from read-buffer
95 * of active socket. Note that both SSL socket and active socket employ
96 * different but correlated read-buffers (as much as async_cnt for each),
97 * and to make it easier/faster to find corresponding SSL socket's read-buffer
98 * from known active socket's read-buffer, the pointer of corresponding
99 * SSL socket's read-buffer is stored right after the end of active socket's
102 #define OFFSET_OF_READ_DATA_PTR(ssock, asock_rbuf) \
104 ((pj_int8_t*)(asock_rbuf) + \
105 ssock->param.read_buffer_size)
108 * Structure of SSL socket write buffer.
110 typedef struct write_data_t {
111 pj_ioqueue_op_key_t key;
112 pj_size_t record_len;
113 pj_ioqueue_op_key_t *app_key;
114 pj_size_t plain_data_len;
124 * Structure of SSL socket write state.
126 typedef struct write_state_t {
131 write_data_t *last_data;
135 * Structure of write data pending.
137 typedef struct write_pending_t {
138 PJ_DECL_LIST_MEMBER(struct write_pending_t);
143 * Secure socket structure definition.
148 pj_ssl_sock_t *parent;
149 pj_ssl_sock_param param;
152 pj_ssl_cert_info local_cert_info;
153 pj_ssl_cert_info remote_cert_info;
156 enum ssl_state ssl_state;
157 pj_ioqueue_op_key_t handshake_op_key;
158 pj_timer_entry timer;
159 pj_status_t verify_status;
162 pj_activesock_t *asock;
164 pj_sockaddr local_addr;
165 pj_sockaddr rem_addr;
168 pj_bool_t read_started;
170 pj_uint32_t read_flags;
172 read_data_t *ssock_rbuf;
174 write_state_t write_state;
175 write_pending_t write_pending;
176 write_pending_t write_pending_empty;
177 pj_lock_t *write_mutex; /* protect write BIO and write_state */
187 * Certificate/credential structure definition.
193 pj_str_t privkey_file;
194 pj_str_t privkey_pass;
198 static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock);
201 *******************************************************************
202 * Static/internal functions.
203 *******************************************************************
207 * Mapping from OpenSSL error codes to pjlib error space.
210 #define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \
211 PJ_ERRNO_SPACE_SIZE*6)
213 #define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE
215 #define STATUS_FROM_SSL_ERR(err, status) { \
216 status = ERR_GET_LIB(err)*300 + ERR_GET_REASON(err);\
217 pj_assert(status < PJ_SSL_ERRNO_SPACE_SIZE);\
218 if (status) status += PJ_SSL_ERRNO_START;\
221 #define GET_SSL_STATUS(status) { \
222 unsigned long e = ERR_get_error();\
223 STATUS_FROM_SSL_ERR(e, status);\
227 * Get error string of OpenSSL.
229 static pj_str_t ssl_strerror(pj_status_t status,
230 char *buf, pj_size_t bufsize)
233 unsigned long ssl_err = status;
237 ssl_err -= PJ_SSL_ERRNO_START;
240 ssl_err = ERR_PACK(l, 0, r);
243 #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0)
246 const char *tmp = NULL;
249 tmp = ERR_reason_error_string(ssl_err);
251 tmp = X509_verify_cert_error_string(ssl_err);
254 pj_ansi_strncpy(buf, tmp, bufsize);
255 errstr = pj_str(buf);
260 #endif /* PJ_HAS_ERROR_STRING */
263 errstr.slen = pj_ansi_snprintf(buf, bufsize,
264 "Unknown OpenSSL error %lu",
271 /* OpenSSL library initialization counter */
272 static int openssl_init_count;
274 /* OpenSSL available ciphers */
275 static unsigned openssl_cipher_num;
276 static struct openssl_ciphers_t {
279 } openssl_ciphers[MAX_CIPHERS];
281 /* OpenSSL application data index */
282 static int sslsock_idx;
285 /* Initialize OpenSSL */
286 static pj_status_t init_openssl(void)
290 if (openssl_init_count)
293 openssl_init_count = 1;
295 /* Register error subsystem */
296 status = pj_register_strerror(PJ_SSL_ERRNO_START,
297 PJ_SSL_ERRNO_SPACE_SIZE,
299 pj_assert(status == PJ_SUCCESS);
301 /* Init OpenSSL lib */
303 SSL_load_error_strings();
304 OpenSSL_add_all_algorithms();
306 /* Init available ciphers */
307 if (openssl_cipher_num == 0) {
308 SSL_METHOD *meth = NULL;
311 STACK_OF(SSL_CIPHER) *sk_cipher;
314 meth = (SSL_METHOD*)SSLv23_server_method();
316 meth = (SSL_METHOD*)TLSv1_server_method();
318 meth = (SSL_METHOD*)SSLv3_server_method();
319 #ifndef OPENSSL_NO_SSL2
321 meth = (SSL_METHOD*)SSLv2_server_method();
325 ctx=SSL_CTX_new(meth);
326 SSL_CTX_set_cipher_list(ctx, "ALL");
329 sk_cipher = SSL_get_ciphers(ssl);
331 n = sk_SSL_CIPHER_num(sk_cipher);
332 if (n > PJ_ARRAY_SIZE(openssl_ciphers))
333 n = PJ_ARRAY_SIZE(openssl_ciphers);
335 for (i = 0; i < n; ++i) {
337 c = sk_SSL_CIPHER_value(sk_cipher,i);
338 openssl_ciphers[i].id = (pj_ssl_cipher)
339 (pj_uint32_t)c->id & 0x00FFFFFF;
340 openssl_ciphers[i].name = SSL_CIPHER_get_name(c);
346 openssl_cipher_num = n;
349 /* Create OpenSSL application data index for SSL socket */
350 sslsock_idx = SSL_get_ex_new_index(0, "SSL socket", NULL, NULL, NULL);
356 /* Shutdown OpenSSL */
357 static void shutdown_openssl(void)
359 PJ_UNUSED_ARG(openssl_init_count);
363 /* SSL password callback. */
364 static int password_cb(char *buf, int num, int rwflag, void *user_data)
366 pj_ssl_cert_t *cert = (pj_ssl_cert_t*) user_data;
368 PJ_UNUSED_ARG(rwflag);
370 if(num < cert->privkey_pass.slen)
373 pj_memcpy(buf, cert->privkey_pass.ptr, cert->privkey_pass.slen);
374 return cert->privkey_pass.slen;
378 /* SSL password callback. */
379 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
381 pj_ssl_sock_t *ssock;
385 /* Get SSL instance */
386 ossl_ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
387 SSL_get_ex_data_X509_STORE_CTX_idx());
390 /* Get SSL socket instance */
391 ssock = SSL_get_ex_data(ossl_ssl, sslsock_idx);
394 /* Store verification status */
395 err = X509_STORE_CTX_get_error(x509_ctx);
400 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
401 ssock->verify_status |= PJ_SSL_CERT_EISSUER_NOT_FOUND;
404 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
405 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
406 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
407 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
408 ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
411 case X509_V_ERR_CERT_NOT_YET_VALID:
412 case X509_V_ERR_CERT_HAS_EXPIRED:
413 ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
416 case X509_V_ERR_UNABLE_TO_GET_CRL:
417 case X509_V_ERR_CRL_NOT_YET_VALID:
418 case X509_V_ERR_CRL_HAS_EXPIRED:
419 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
420 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
421 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
422 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
423 ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE;
426 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
427 case X509_V_ERR_CERT_UNTRUSTED:
428 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
429 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
430 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
433 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
434 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
435 case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
436 case X509_V_ERR_AKID_SKID_MISMATCH:
437 case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
438 case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
439 ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH;
442 case X509_V_ERR_CERT_REVOKED:
443 ssock->verify_status |= PJ_SSL_CERT_EREVOKED;
446 case X509_V_ERR_INVALID_PURPOSE:
447 case X509_V_ERR_CERT_REJECTED:
448 case X509_V_ERR_INVALID_CA:
449 ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE;
452 case X509_V_ERR_CERT_CHAIN_TOO_LONG: /* not really used */
453 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
454 ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG;
458 case X509_V_ERR_OUT_OF_MEM:
460 ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
464 /* When verification is not requested just return ok here, however
465 * application can still get the verification status.
467 if (PJ_FALSE == ssock->param.verify_peer)
473 /* Setting SSL sock cipher list */
474 static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock);
477 /* Create and initialize new SSL context and instance */
478 static pj_status_t create_ssl(pj_ssl_sock_t *ssock)
480 SSL_METHOD *ssl_method;
490 /* Make sure OpenSSL library has been initialized */
493 /* Determine SSL method to use */
494 switch (ssock->param.proto) {
495 case PJ_SSL_SOCK_PROTO_DEFAULT:
496 case PJ_SSL_SOCK_PROTO_TLS1:
497 ssl_method = (SSL_METHOD*)TLSv1_method();
499 #ifndef OPENSSL_NO_SSL2
500 case PJ_SSL_SOCK_PROTO_SSL2:
501 ssl_method = (SSL_METHOD*)SSLv2_method();
504 case PJ_SSL_SOCK_PROTO_SSL3:
505 ssl_method = (SSL_METHOD*)SSLv3_method();
507 case PJ_SSL_SOCK_PROTO_SSL23:
508 ssl_method = (SSL_METHOD*)SSLv23_method();
510 //case PJ_SSL_SOCK_PROTO_DTLS1:
511 //ssl_method = (SSL_METHOD*)DTLSv1_method();
517 /* Create SSL context */
518 ctx = SSL_CTX_new(ssl_method);
520 GET_SSL_STATUS(status);
524 /* Apply credentials */
526 /* Load CA list if one is specified. */
527 if (cert->CA_file.slen) {
529 rc = SSL_CTX_load_verify_locations(ctx, cert->CA_file.ptr, NULL);
532 GET_SSL_STATUS(status);
533 PJ_LOG(1,(ssock->pool->obj_name, "Error loading CA list file "
534 "'%s'", cert->CA_file.ptr));
540 /* Set password callback */
541 if (cert->privkey_pass.slen) {
542 SSL_CTX_set_default_passwd_cb(ctx, password_cb);
543 SSL_CTX_set_default_passwd_cb_userdata(ctx, cert);
547 /* Load certificate if one is specified */
548 if (cert->cert_file.slen) {
550 /* Load certificate chain from file into ctx */
551 rc = SSL_CTX_use_certificate_chain_file(ctx, cert->cert_file.ptr);
554 GET_SSL_STATUS(status);
555 PJ_LOG(1,(ssock->pool->obj_name, "Error loading certificate "
556 "chain file '%s'", cert->cert_file.ptr));
563 /* Load private key if one is specified */
564 if (cert->privkey_file.slen) {
565 /* Adds the first private key found in file to ctx */
566 rc = SSL_CTX_use_PrivateKey_file(ctx, cert->privkey_file.ptr,
570 GET_SSL_STATUS(status);
571 PJ_LOG(1,(ssock->pool->obj_name, "Error adding private key "
572 "from '%s'", cert->privkey_file.ptr));
579 /* Create SSL instance */
580 ssock->ossl_ctx = ctx;
581 ssock->ossl_ssl = SSL_new(ssock->ossl_ctx);
582 if (ssock->ossl_ssl == NULL) {
583 GET_SSL_STATUS(status);
587 /* Set SSL sock as application data of SSL instance */
588 SSL_set_ex_data(ssock->ossl_ssl, sslsock_idx, ssock);
590 /* SSL verification options */
591 mode = SSL_VERIFY_PEER;
592 if (ssock->is_server && ssock->param.require_client_cert)
593 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
595 SSL_set_verify(ssock->ossl_ssl, mode, &verify_cb);
597 /* Set cipher list */
598 status = set_cipher_list(ssock);
599 if (status != PJ_SUCCESS)
603 ssock->ossl_rbio = BIO_new(BIO_s_mem());
604 ssock->ossl_wbio = BIO_new(BIO_s_mem());
605 (void)BIO_set_close(ssock->ossl_rbio, BIO_CLOSE);
606 (void)BIO_set_close(ssock->ossl_wbio, BIO_CLOSE);
607 SSL_set_bio(ssock->ossl_ssl, ssock->ossl_rbio, ssock->ossl_wbio);
613 /* Destroy SSL context and instance */
614 static void destroy_ssl(pj_ssl_sock_t *ssock)
616 /* Destroy SSL instance */
617 if (ssock->ossl_ssl) {
618 SSL_shutdown(ssock->ossl_ssl);
619 SSL_free(ssock->ossl_ssl); /* this will also close BIOs */
620 ssock->ossl_ssl = NULL;
623 /* Destroy SSL context */
624 if (ssock->ossl_ctx) {
625 SSL_CTX_free(ssock->ossl_ctx);
626 ssock->ossl_ctx = NULL;
629 /* Potentially shutdown OpenSSL library if this is the last
636 /* Reset SSL socket state */
637 static void reset_ssl_sock_state(pj_ssl_sock_t *ssock)
639 ssock->ssl_state = SSL_STATE_NULL;
644 pj_activesock_close(ssock->asock);
646 ssock->sock = PJ_INVALID_SOCKET;
648 if (ssock->sock != PJ_INVALID_SOCKET) {
649 pj_sock_close(ssock->sock);
650 ssock->sock = PJ_INVALID_SOCKET;
653 /* Upon error, OpenSSL may leave any error description in the thread
654 * error queue, which sometime may cause next call to SSL API returning
655 * false error alarm, e.g: in Linux, SSL_CTX_use_certificate_chain_file()
656 * returning false error after a handshake error (in different SSL_CTX!).
657 * For now, just clear thread error queue here.
663 /* Generate cipher list with user preference order in OpenSSL format */
664 static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock)
667 pj_str_t cipher_list;
668 STACK_OF(SSL_CIPHER) *sk_cipher;
672 if (ssock->param.ciphers_num == 0)
675 pj_strset(&cipher_list, buf, 0);
677 /* Set SSL with ALL available ciphers */
678 SSL_set_cipher_list(ssock->ossl_ssl, "ALL");
680 /* Generate user specified cipher list in OpenSSL format */
681 sk_cipher = SSL_get_ciphers(ssock->ossl_ssl);
682 for (i = 0; i < ssock->param.ciphers_num; ++i) {
683 for (j = 0; j < sk_SSL_CIPHER_num(sk_cipher); ++j) {
685 c = sk_SSL_CIPHER_value(sk_cipher, j);
686 if (ssock->param.ciphers[i] == (pj_ssl_cipher)
687 ((pj_uint32_t)c->id & 0x00FFFFFF))
691 c_name = SSL_CIPHER_get_name(c);
693 /* Check buffer size */
694 if (cipher_list.slen + pj_ansi_strlen(c_name) + 2 > sizeof(buf)) {
695 pj_assert(!"Insufficient temporary buffer for cipher");
699 /* Add colon separator */
700 if (cipher_list.slen)
701 pj_strcat2(&cipher_list, ":");
704 pj_strcat2(&cipher_list, c_name);
710 /* Put NULL termination in the generated cipher list */
711 cipher_list.ptr[cipher_list.slen] = '\0';
713 /* Finally, set chosen cipher list */
714 ret = SSL_set_cipher_list(ssock->ossl_ssl, buf);
717 GET_SSL_STATUS(status);
725 /* Parse OpenSSL ASN1_TIME to pj_time_val and GMT info */
726 static pj_bool_t parse_ossl_asn1_time(pj_time_val *tv, pj_bool_t *gmt,
729 unsigned long parts[7] = {0};
736 utc = tm->type == V_ASN1_UTCTIME;
742 *gmt = (*end == 'Z');
745 for (i = 0; i < 7 && p < end; ++i) {
749 /* 4 digits year part for non-UTC time format */
752 /* fraction of seconds */
754 st.slen = end - p + 1;
756 /* other parts always 2 digits length */
761 parts[i] = pj_strtoul(&st);
765 /* encode parts to pj_time_val */
768 pt.year += (pt.year < 50)? 2000:1900;
769 pt.mon = parts[1] - 1;
776 pj_time_encode(&pt, tv);
782 /* Get Common Name field string from a general name string */
783 static void get_cn_from_gen_name(const pj_str_t *gen_name, pj_str_t *cn)
785 pj_str_t CN_sign = {"/CN=", 4};
788 pj_bzero(cn, sizeof(cn));
790 p = pj_strstr(gen_name, &CN_sign);
794 p += 4; /* shift pointer to value part */
795 pj_strset(cn, p, gen_name->slen - (p - gen_name->ptr));
796 q = pj_strchr(cn, '/');
802 /* Get certificate info from OpenSSL X509, in case the certificate info
803 * hal already populated, this function will check if the contents need
804 * to be updated by inspecting the issuer and the serial number.
806 static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, X509 *x)
808 pj_bool_t update_needed;
810 pj_uint8_t serial_no[64] = {0}; /* should be >= sizeof(ci->serial_no) */
813 GENERAL_NAMES *names = NULL;
815 pj_assert(pool && ci && x);
818 X509_NAME_oneline(X509_get_issuer_name(x), buf, sizeof(buf));
821 p = (pj_uint8_t*) M_ASN1_STRING_data(X509_get_serialNumber(x));
822 len = M_ASN1_STRING_length(X509_get_serialNumber(x));
823 if (len > sizeof(ci->serial_no))
824 len = sizeof(ci->serial_no);
825 pj_memcpy(serial_no + sizeof(ci->serial_no) - len, p, len);
827 /* Check if the contents need to be updated. */
828 update_needed = pj_strcmp2(&ci->issuer.info, buf) ||
829 pj_memcmp(ci->serial_no, serial_no, sizeof(ci->serial_no));
833 /* Update cert info */
835 pj_bzero(ci, sizeof(pj_ssl_cert_info));
838 ci->version = X509_get_version(x) + 1;
841 pj_strdup2(pool, &ci->issuer.info, buf);
842 get_cn_from_gen_name(&ci->issuer.info, &ci->issuer.cn);
845 pj_memcpy(ci->serial_no, serial_no, sizeof(ci->serial_no));
848 pj_strdup2(pool, &ci->subject.info,
849 X509_NAME_oneline(X509_get_subject_name(x),
851 get_cn_from_gen_name(&ci->subject.info, &ci->subject.cn);
854 parse_ossl_asn1_time(&ci->validity.start, &ci->validity.gmt,
855 X509_get_notBefore(x));
856 parse_ossl_asn1_time(&ci->validity.end, &ci->validity.gmt,
857 X509_get_notAfter(x));
859 /* Subject Alternative Name extension */
860 if (ci->version >= 3) {
861 names = (GENERAL_NAMES*) X509_get_ext_d2i(x, NID_subject_alt_name,
867 cnt = sk_GENERAL_NAME_num(names);
868 ci->subj_alt_name.entry = pj_pool_calloc(pool, cnt,
869 sizeof(*ci->subj_alt_name.entry));
871 for (i = 0; i < cnt; ++i) {
872 unsigned char *p = 0;
873 pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN;
874 const GENERAL_NAME *name;
876 name = sk_GENERAL_NAME_value(names, i);
878 switch (name->type) {
880 len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
881 type = PJ_SSL_CERT_NAME_RFC822;
884 len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
885 type = PJ_SSL_CERT_NAME_DNS;
888 len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
889 type = PJ_SSL_CERT_NAME_URI;
892 p = ASN1_STRING_data(name->d.ip);
893 len = ASN1_STRING_length(name->d.ip);
894 type = PJ_SSL_CERT_NAME_IP;
900 if (p && len && type != PJ_SSL_CERT_NAME_UNKNOWN) {
901 ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type;
902 if (type == PJ_SSL_CERT_NAME_IP) {
903 int af = pj_AF_INET();
904 if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6();
905 pj_inet_ntop2(af, p, buf, sizeof(buf));
907 &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
911 &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
915 ci->subj_alt_name.cnt++;
922 /* Update local & remote certificates info. This function should be
923 * called after handshake or renegotiation successfully completed.
925 static void update_certs_info(pj_ssl_sock_t *ssock)
929 pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED);
931 /* Active local certificate */
932 x = SSL_get_certificate(ssock->ossl_ssl);
934 get_cert_info(ssock->pool, &ssock->local_cert_info, x);
935 /* Don't free local's X509! */
937 pj_bzero(&ssock->local_cert_info, sizeof(pj_ssl_cert_info));
940 /* Active remote certificate */
941 x = SSL_get_peer_certificate(ssock->ossl_ssl);
943 get_cert_info(ssock->pool, &ssock->remote_cert_info, x);
944 /* Free peer's X509 */
947 pj_bzero(&ssock->remote_cert_info, sizeof(pj_ssl_cert_info));
952 /* When handshake completed:
953 * - notify application
954 * - if handshake failed, reset SSL state
955 * - return PJ_FALSE when SSL socket instance is destroyed by application.
957 static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock,
960 /* Cancel handshake timer */
961 if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) {
962 pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
963 ssock->timer.id = TIMER_NONE;
966 /* Update certificates info on successful handshake */
967 if (status == PJ_SUCCESS)
968 update_certs_info(ssock);
971 if (ssock->is_server) {
972 if (status != PJ_SUCCESS) {
973 /* Handshake failed in accepting, destroy our self silently. */
975 char errmsg[PJ_ERR_MSG_SIZE];
976 char buf[PJ_INET6_ADDRSTRLEN+10];
978 pj_strerror(status, errmsg, sizeof(errmsg));
979 PJ_LOG(3,(ssock->pool->obj_name, "Handshake failed in accepting "
981 pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3),
984 /* Workaround for ticket #985 */
985 #if defined(PJ_WIN32) && PJ_WIN32!=0
986 if (ssock->param.timer_heap) {
987 pj_time_val interval = {0, DELAYED_CLOSE_TIMEOUT};
989 reset_ssl_sock_state(ssock);
991 ssock->timer.id = TIMER_CLOSE;
992 pj_time_val_normalize(&interval);
993 if (pj_timer_heap_schedule(ssock->param.timer_heap,
994 &ssock->timer, &interval) != 0)
996 ssock->timer.id = TIMER_NONE;
997 pj_ssl_sock_close(ssock);
1000 #endif /* PJ_WIN32 */
1002 pj_ssl_sock_close(ssock);
1006 /* Notify application the newly accepted SSL socket */
1007 if (ssock->param.cb.on_accept_complete) {
1009 ret = (*ssock->param.cb.on_accept_complete)
1010 (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,
1011 pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr));
1012 if (ret == PJ_FALSE)
1019 /* On failure, reset SSL socket state first, as app may try to
1020 * reconnect in the callback.
1022 if (status != PJ_SUCCESS) {
1023 reset_ssl_sock_state(ssock);
1025 if (ssock->param.cb.on_connect_complete) {
1027 ret = (*ssock->param.cb.on_connect_complete)(ssock, status);
1028 if (ret == PJ_FALSE)
1036 /* Flush write BIO to network socket. Note that any access to write BIO
1037 * MUST be serialized, so mutex protection must cover any call to OpenSSL
1038 * API (that possibly generate data for write BIO) along with the call to
1039 * this function (flushing all data in write BIO generated by above
1040 * OpenSSL API call).
1042 static pj_status_t flush_write_bio(pj_ssl_sock_t *ssock,
1043 pj_ioqueue_op_key_t *send_key,
1050 write_state_t *write_st = &ssock->write_state;
1051 write_data_t *wdata;
1052 pj_size_t avail_len, needed_len, skipped_len = 0;
1055 /* Check if there is data in write BIO, flush it if any */
1056 if (!BIO_pending(ssock->ossl_wbio))
1059 /* Get data and its length */
1060 len = BIO_get_mem_data(ssock->ossl_wbio, &data);
1064 /* Calculate buffer size needed, and align it to 8 */
1065 needed_len = len + sizeof(write_data_t);
1066 needed_len = ((needed_len + 7) >> 3) << 3;
1068 /* Check buffer availability */
1069 avail_len = write_st->max_len - write_st->len;
1070 if (avail_len < needed_len)
1073 /* More buffer availability check, note that the write data must be in
1074 * a contigue buffer.
1076 if (write_st->len == 0) {
1078 write_st->start = write_st->buf;
1079 wdata = (write_data_t*)write_st->start;
1084 pj_size_t reg1_len, reg2_len;
1086 /* Unused slots may be wrapped/splitted into two regions, so let's
1087 * analyze them if any region can hold the write data.
1089 reg1 = write_st->start + write_st->len;
1090 if (reg1 >= write_st->buf + write_st->max_len)
1091 reg1 -= write_st->max_len;
1092 reg1_len = write_st->max_len - write_st->len;
1093 if (reg1 + reg1_len > write_st->buf + write_st->max_len) {
1094 reg1_len = write_st->buf + write_st->max_len - reg1;
1095 reg2 = write_st->buf;
1096 reg2_len = write_st->start - write_st->buf;
1101 avail_len = PJ_MAX(reg1_len, reg2_len);
1102 if (avail_len < needed_len)
1105 /* Get write data pointer and update buffer length */
1106 if (reg1_len >= needed_len) {
1107 wdata = (write_data_t*)reg1;
1109 wdata = (write_data_t*)reg2;
1110 /* Unused slot in region 1 is skipped as current write data
1113 skipped_len = reg1_len;
1117 /* Copy the data and set its properties into the buffer */
1118 pj_bzero(wdata, sizeof(write_data_t));
1119 wdata->app_key = send_key;
1120 wdata->record_len = needed_len;
1121 wdata->data_len = len;
1122 wdata->plain_data_len = orig_len;
1123 wdata->flags = flags;
1124 pj_memcpy(&wdata->data, data, len);
1127 if (ssock->param.sock_type == pj_SOCK_STREAM()) {
1128 status = pj_activesock_send(ssock->asock, &wdata->key,
1129 wdata->data.content, &len,
1132 status = pj_activesock_sendto(ssock->asock, &wdata->key,
1133 wdata->data.content, &len,
1135 (pj_sockaddr_t*)&ssock->rem_addr,
1139 /* Oh no, EWOULDBLOCK! */
1140 if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) {
1141 /* Just return PJ_SUCCESS here, the pending data will be sent in next
1142 * call of this function since the data is still stored in write BIO.
1147 /* Reset write BIO after flushed */
1148 (void)BIO_reset(ssock->ossl_wbio);
1150 if (status == PJ_EPENDING) {
1151 /* Update write state */
1152 pj_assert(skipped_len==0 || write_st->last_data);
1153 write_st->len += needed_len + skipped_len;
1154 if (write_st->last_data)
1155 write_st->last_data->record_len += skipped_len;
1156 write_st->last_data = wdata;
1163 static void on_timer(pj_timer_heap_t *th, struct pj_timer_entry *te)
1165 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)te->user_data;
1166 int timer_id = te->id;
1168 te->id = TIMER_NONE;
1173 case TIMER_HANDSHAKE_TIMEOUT:
1174 PJ_LOG(1,(ssock->pool->obj_name, "SSL timeout after %d.%ds",
1175 ssock->param.timeout.sec, ssock->param.timeout.msec));
1177 on_handshake_complete(ssock, PJ_ETIMEDOUT);
1180 pj_ssl_sock_close(ssock);
1183 pj_assert(!"Unknown timer");
1189 /* Asynchronouse handshake */
1190 static pj_status_t do_handshake(pj_ssl_sock_t *ssock)
1195 pj_lock_acquire(ssock->write_mutex);
1197 /* Perform SSL handshake */
1198 err = SSL_do_handshake(ssock->ossl_ssl);
1200 err = SSL_get_error(ssock->ossl_ssl, err);
1201 if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
1203 /* Handshake fails */
1204 GET_SSL_STATUS(status);
1205 pj_lock_release(ssock->write_mutex);
1210 /* SSL_do_handshake() may put some pending data into SSL write BIO,
1213 status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
1214 if (status != PJ_SUCCESS && status != PJ_EPENDING) {
1215 pj_lock_release(ssock->write_mutex);
1219 pj_lock_release(ssock->write_mutex);
1221 /* Check if handshake has been completed */
1222 if (SSL_is_init_finished(ssock->ossl_ssl)) {
1223 ssock->ssl_state = SSL_STATE_ESTABLISHED;
1232 *******************************************************************
1233 * Active socket callbacks.
1234 *******************************************************************
1237 static pj_bool_t asock_on_data_read (pj_activesock_t *asock,
1241 pj_size_t *remainder)
1243 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1244 pj_activesock_get_user_data(asock);
1247 /* Socket error or closed */
1248 if (data && size > 0) {
1249 /* Consume the whole data */
1250 nwritten = BIO_write(ssock->ossl_rbio, data, size);
1251 if (nwritten < size) {
1252 GET_SSL_STATUS(status);
1257 /* Check if SSL handshake hasn't finished yet */
1258 if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
1259 pj_bool_t ret = PJ_TRUE;
1261 if (status == PJ_SUCCESS)
1262 status = do_handshake(ssock);
1264 /* Not pending is either success or failed */
1265 if (status != PJ_EPENDING)
1266 ret = on_handshake_complete(ssock, status);
1271 /* See if there is any decrypted data for the application */
1272 if (ssock->read_started) {
1274 read_data_t *buf = *(OFFSET_OF_READ_DATA_PTR(ssock, data));
1275 void *data_ = (pj_int8_t*)buf->data + buf->len;
1276 int size_ = ssock->read_size - buf->len;
1278 /* SSL_read() may write some data to BIO write when re-negotiation
1279 * is on progress, so let's protect it with write mutex.
1281 pj_lock_acquire(ssock->write_mutex);
1282 size_ = SSL_read(ssock->ossl_ssl, data_, size_);
1283 pj_lock_release(ssock->write_mutex);
1285 if (size_ > 0 || status != PJ_SUCCESS) {
1286 if (ssock->param.cb.on_data_read) {
1288 pj_size_t remainder_ = 0;
1293 ret = (*ssock->param.cb.on_data_read)(ssock, buf->data,
1297 /* We've been destroyed */
1301 /* Application may have left some data to be consumed
1304 buf->len = remainder_;
1307 /* Active socket signalled connection closed/error, this has
1308 * been signalled to the application along with any remaining
1309 * buffer. So, let's just reset SSL socket now.
1311 if (status != PJ_SUCCESS) {
1312 reset_ssl_sock_state(ssock);
1318 int err = SSL_get_error(ssock->ossl_ssl, size);
1320 /* SSL might just return SSL_ERROR_WANT_READ in
1323 if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
1325 /* Reset SSL socket state, then return PJ_FALSE */
1326 GET_SSL_STATUS(status);
1327 reset_ssl_sock_state(ssock);
1331 status = do_handshake(ssock);
1332 if (status == PJ_SUCCESS) {
1333 /* Renegotiation completed */
1335 /* Update certificates */
1336 update_certs_info(ssock);
1338 pj_lock_acquire(ssock->write_mutex);
1339 status = flush_delayed_send(ssock);
1340 pj_lock_release(ssock->write_mutex);
1342 if (status != PJ_SUCCESS && status != PJ_EPENDING) {
1343 PJ_PERROR(1,(ssock->pool->obj_name, status,
1344 "Failed to flush delayed send"));
1347 } else if (status != PJ_EPENDING) {
1348 PJ_PERROR(1,(ssock->pool->obj_name, status,
1349 "Renegotiation failed"));
1361 if (ssock->ssl_state == SSL_STATE_HANDSHAKING)
1362 return on_handshake_complete(ssock, status);
1364 if (ssock->read_started && ssock->param.cb.on_data_read) {
1366 ret = (*ssock->param.cb.on_data_read)(ssock, NULL, 0, status,
1369 /* We've been destroyed */
1374 reset_ssl_sock_state(ssock);
1379 static pj_bool_t asock_on_data_sent (pj_activesock_t *asock,
1380 pj_ioqueue_op_key_t *send_key,
1383 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1384 pj_activesock_get_user_data(asock);
1386 PJ_UNUSED_ARG(send_key);
1387 PJ_UNUSED_ARG(sent);
1389 if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
1390 /* Initial handshaking */
1393 status = do_handshake(ssock);
1394 /* Not pending is either success or failed */
1395 if (status != PJ_EPENDING)
1396 return on_handshake_complete(ssock, status);
1398 } else if (send_key != &ssock->handshake_op_key) {
1399 /* Some data has been sent, notify application */
1400 write_data_t *wdata = (write_data_t*)send_key;
1401 if (ssock->param.cb.on_data_sent) {
1403 ret = (*ssock->param.cb.on_data_sent)(ssock, wdata->app_key,
1404 wdata->plain_data_len);
1406 /* We've been destroyed */
1411 /* Update write buffer state */
1412 pj_lock_acquire(ssock->write_mutex);
1413 ssock->write_state.start += wdata->record_len;
1414 ssock->write_state.len -= wdata->record_len;
1415 if (ssock->write_state.last_data == wdata) {
1416 pj_assert(ssock->write_state.len == 0);
1417 ssock->write_state.last_data = NULL;
1419 pj_lock_release(ssock->write_mutex);
1422 /* SSL re-negotiation is on-progress, just do nothing */
1429 static pj_bool_t asock_on_accept_complete (pj_activesock_t *asock,
1431 const pj_sockaddr_t *src_addr,
1434 pj_ssl_sock_t *ssock_parent = (pj_ssl_sock_t*)
1435 pj_activesock_get_user_data(asock);
1436 pj_ssl_sock_t *ssock;
1437 pj_activesock_cb asock_cb;
1438 pj_activesock_cfg asock_cfg;
1442 PJ_UNUSED_ARG(src_addr_len);
1444 /* Create new SSL socket instance */
1445 status = pj_ssl_sock_create(ssock_parent->pool, &ssock_parent->param,
1447 if (status != PJ_SUCCESS)
1450 /* Update new SSL socket attributes */
1451 ssock->sock = newsock;
1452 ssock->parent = ssock_parent;
1453 ssock->is_server = PJ_TRUE;
1454 if (ssock_parent->cert) {
1455 status = pj_ssl_sock_set_certificate(ssock, ssock->pool,
1456 ssock_parent->cert);
1457 if (status != PJ_SUCCESS)
1461 /* Apply QoS, if specified */
1462 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
1463 &ssock->param.qos_params, 1,
1464 ssock->pool->obj_name, NULL);
1465 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
1468 /* Update local address */
1469 ssock->addr_len = src_addr_len;
1470 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
1472 if (status != PJ_SUCCESS) {
1473 /* This fails on few envs, e.g: win IOCP, just tolerate this and
1474 * use parent local address instead.
1476 pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);
1479 /* Set remote address */
1480 pj_sockaddr_cp(&ssock->rem_addr, src_addr);
1482 /* Create SSL context */
1483 status = create_ssl(ssock);
1484 if (status != PJ_SUCCESS)
1487 /* Prepare read buffer */
1488 ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool,
1489 ssock->param.async_cnt,
1491 for (i = 0; i<ssock->param.async_cnt; ++i) {
1492 ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
1494 ssock->param.read_buffer_size +
1495 sizeof(read_data_t*));
1498 /* Create active socket */
1499 pj_activesock_cfg_default(&asock_cfg);
1500 asock_cfg.async_cnt = ssock->param.async_cnt;
1501 asock_cfg.concurrency = ssock->param.concurrency;
1502 asock_cfg.whole_data = PJ_TRUE;
1504 pj_bzero(&asock_cb, sizeof(asock_cb));
1505 asock_cb.on_data_read = asock_on_data_read;
1506 asock_cb.on_data_sent = asock_on_data_sent;
1508 status = pj_activesock_create(ssock->pool,
1510 ssock->param.sock_type,
1512 ssock->param.ioqueue,
1517 if (status != PJ_SUCCESS)
1521 status = pj_activesock_start_read2(ssock->asock, ssock->pool,
1522 ssock->param.read_buffer_size,
1524 PJ_IOQUEUE_ALWAYS_ASYNC);
1525 if (status != PJ_SUCCESS)
1528 /* Prepare write/send state */
1529 pj_assert(ssock->write_state.max_len == 0);
1530 ssock->write_state.buf = (char*)
1531 pj_pool_alloc(ssock->pool,
1532 ssock->param.send_buffer_size);
1533 ssock->write_state.max_len = ssock->param.send_buffer_size;
1534 ssock->write_state.start = ssock->write_state.buf;
1535 ssock->write_state.len = 0;
1537 /* Start handshake timer */
1538 if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
1539 ssock->param.timeout.msec != 0))
1541 pj_assert(ssock->timer.id == TIMER_NONE);
1542 ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
1543 status = pj_timer_heap_schedule(ssock->param.timer_heap,
1545 &ssock->param.timeout);
1546 if (status != PJ_SUCCESS)
1547 ssock->timer.id = TIMER_NONE;
1550 /* Start SSL handshake */
1551 ssock->ssl_state = SSL_STATE_HANDSHAKING;
1552 SSL_set_accept_state(ssock->ossl_ssl);
1553 status = do_handshake(ssock);
1556 if (ssock && status != PJ_EPENDING)
1557 on_handshake_complete(ssock, status);
1559 /* Must return PJ_TRUE whatever happened, as active socket must
1560 * continue listening.
1566 static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock,
1569 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1570 pj_activesock_get_user_data(asock);
1573 if (status != PJ_SUCCESS)
1576 /* Update local address */
1577 ssock->addr_len = sizeof(pj_sockaddr);
1578 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
1580 if (status != PJ_SUCCESS)
1583 /* Create SSL context */
1584 status = create_ssl(ssock);
1585 if (status != PJ_SUCCESS)
1588 /* Prepare read buffer */
1589 ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool,
1590 ssock->param.async_cnt,
1592 for (i = 0; i<ssock->param.async_cnt; ++i) {
1593 ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
1595 ssock->param.read_buffer_size +
1596 sizeof(read_data_t*));
1600 status = pj_activesock_start_read2(ssock->asock, ssock->pool,
1601 ssock->param.read_buffer_size,
1603 PJ_IOQUEUE_ALWAYS_ASYNC);
1604 if (status != PJ_SUCCESS)
1607 /* Prepare write/send state */
1608 pj_assert(ssock->write_state.max_len == 0);
1609 ssock->write_state.buf = (char*)
1610 pj_pool_alloc(ssock->pool,
1611 ssock->param.send_buffer_size);
1612 ssock->write_state.max_len = ssock->param.send_buffer_size;
1613 ssock->write_state.start = ssock->write_state.buf;
1614 ssock->write_state.len = 0;
1616 #ifdef SSL_set_tlsext_host_name
1617 /* Set server name to connect */
1618 if (ssock->param.server_name.slen) {
1619 /* Server name is null terminated already */
1620 if (!SSL_set_tlsext_host_name(ssock->ossl_ssl,
1621 ssock->param.server_name.ptr))
1623 char err_str[PJ_ERR_MSG_SIZE];
1625 ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
1626 PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() "
1627 "failed: %s", err_str));
1632 /* Start SSL handshake */
1633 ssock->ssl_state = SSL_STATE_HANDSHAKING;
1634 SSL_set_connect_state(ssock->ossl_ssl);
1636 status = do_handshake(ssock);
1637 if (status != PJ_EPENDING)
1643 return on_handshake_complete(ssock, status);
1649 *******************************************************************
1651 *******************************************************************
1654 /* Load credentials from files. */
1655 PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files (pj_pool_t *pool,
1656 const pj_str_t *CA_file,
1657 const pj_str_t *cert_file,
1658 const pj_str_t *privkey_file,
1659 const pj_str_t *privkey_pass,
1660 pj_ssl_cert_t **p_cert)
1662 pj_ssl_cert_t *cert;
1664 PJ_ASSERT_RETURN(pool && CA_file && cert_file && privkey_file, PJ_EINVAL);
1666 cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
1667 pj_strdup_with_null(pool, &cert->CA_file, CA_file);
1668 pj_strdup_with_null(pool, &cert->cert_file, cert_file);
1669 pj_strdup_with_null(pool, &cert->privkey_file, privkey_file);
1670 pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass);
1678 /* Set SSL socket credentials. */
1679 PJ_DECL(pj_status_t) pj_ssl_sock_set_certificate(
1680 pj_ssl_sock_t *ssock,
1682 const pj_ssl_cert_t *cert)
1684 pj_ssl_cert_t *cert_;
1686 PJ_ASSERT_RETURN(ssock && pool && cert, PJ_EINVAL);
1688 cert_ = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
1689 pj_memcpy(cert_, cert, sizeof(cert));
1690 pj_strdup_with_null(pool, &cert_->CA_file, &cert->CA_file);
1691 pj_strdup_with_null(pool, &cert_->cert_file, &cert->cert_file);
1692 pj_strdup_with_null(pool, &cert_->privkey_file, &cert->privkey_file);
1693 pj_strdup_with_null(pool, &cert_->privkey_pass, &cert->privkey_pass);
1695 ssock->cert = cert_;
1701 /* Get available ciphers. */
1702 PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[],
1703 unsigned *cipher_num)
1707 PJ_ASSERT_RETURN(ciphers && cipher_num, PJ_EINVAL);
1709 if (openssl_cipher_num == 0) {
1714 if (openssl_cipher_num == 0) {
1716 return PJ_ENOTFOUND;
1719 *cipher_num = PJ_MIN(*cipher_num, openssl_cipher_num);
1721 for (i = 0; i < *cipher_num; ++i)
1722 ciphers[i] = openssl_ciphers[i].id;
1728 /* Get cipher name string */
1729 PJ_DEF(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher)
1733 if (openssl_cipher_num == 0) {
1738 for (i = 0; i < openssl_cipher_num; ++i) {
1739 if (cipher == openssl_ciphers[i].id)
1740 return openssl_ciphers[i].name;
1746 /* Check if the specified cipher is supported by SSL/TLS backend. */
1747 PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher)
1751 if (openssl_cipher_num == 0) {
1756 for (i = 0; i < openssl_cipher_num; ++i) {
1757 if (cipher == openssl_ciphers[i].id)
1766 * Create SSL socket instance.
1768 PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool,
1769 const pj_ssl_sock_param *param,
1770 pj_ssl_sock_t **p_ssock)
1772 pj_ssl_sock_t *ssock;
1775 PJ_ASSERT_RETURN(pool && param && p_ssock, PJ_EINVAL);
1776 PJ_ASSERT_RETURN(param->sock_type == pj_SOCK_STREAM(), PJ_ENOTSUP);
1778 pool = pj_pool_create(pool->factory, "ssl%p", 512, 512, NULL);
1780 /* Create secure socket */
1781 ssock = PJ_POOL_ZALLOC_T(pool, pj_ssl_sock_t);
1783 ssock->sock = PJ_INVALID_SOCKET;
1784 ssock->ssl_state = SSL_STATE_NULL;
1785 pj_list_init(&ssock->write_pending);
1786 pj_list_init(&ssock->write_pending_empty);
1787 pj_timer_entry_init(&ssock->timer, 0, ssock, &on_timer);
1789 /* Create secure socket mutex */
1790 status = pj_lock_create_recursive_mutex(pool, pool->obj_name,
1791 &ssock->write_mutex);
1792 if (status != PJ_SUCCESS)
1795 /* Init secure socket param */
1796 ssock->param = *param;
1797 ssock->param.read_buffer_size = ((ssock->param.read_buffer_size+7)>>3)<<3;
1798 if (param->ciphers_num > 0) {
1800 ssock->param.ciphers = (pj_ssl_cipher*)
1801 pj_pool_calloc(pool, param->ciphers_num,
1802 sizeof(pj_ssl_cipher));
1803 for (i = 0; i < param->ciphers_num; ++i)
1804 ssock->param.ciphers[i] = param->ciphers[i];
1807 /* Server name must be null-terminated */
1808 pj_strdup_with_null(pool, &ssock->param.server_name,
1809 ¶m->server_name);
1819 * Close the secure socket. This will unregister the socket from the
1820 * ioqueue and ultimately close the socket.
1822 PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock)
1826 PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
1831 if (ssock->timer.id != TIMER_NONE) {
1832 pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
1833 ssock->timer.id = TIMER_NONE;
1836 reset_ssl_sock_state(ssock);
1837 pj_lock_destroy(ssock->write_mutex);
1842 pj_pool_release(pool);
1849 * Associate arbitrary data with the secure socket.
1851 PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock,
1854 PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
1856 ssock->param.user_data = user_data;
1862 * Retrieve the user data previously associated with this secure
1865 PJ_DEF(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock)
1867 PJ_ASSERT_RETURN(ssock, NULL);
1869 return ssock->param.user_data;
1874 * Retrieve the local address and port used by specified SSL socket.
1876 PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock,
1877 pj_ssl_sock_info *info)
1879 pj_bzero(info, sizeof(*info));
1881 /* Established flag */
1882 info->established = (ssock->ssl_state == SSL_STATE_ESTABLISHED);
1885 info->proto = ssock->param.proto;
1888 pj_sockaddr_cp(&info->local_addr, &ssock->local_addr);
1890 if (info->established) {
1891 const SSL_CIPHER *cipher;
1893 /* Current cipher */
1894 cipher = SSL_get_current_cipher(ssock->ossl_ssl);
1895 info->cipher = (cipher->id & 0x00FFFFFF);
1897 /* Remote address */
1898 pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr);
1900 /* Certificates info */
1901 info->local_cert_info = &ssock->local_cert_info;
1902 info->remote_cert_info = &ssock->remote_cert_info;
1904 /* Verification status */
1905 info->verify_status = ssock->verify_status;
1913 * Starts read operation on this secure socket.
1915 PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock,
1923 PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL);
1924 PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
1926 readbuf = (void**) pj_pool_calloc(pool, ssock->param.async_cnt,
1929 for (i=0; i<ssock->param.async_cnt; ++i) {
1930 readbuf[i] = pj_pool_alloc(pool, buff_size);
1933 return pj_ssl_sock_start_read2(ssock, pool, buff_size,
1939 * Same as #pj_ssl_sock_start_read(), except that the application
1940 * supplies the buffers for the read operation so that the acive socket
1941 * does not have to allocate the buffers.
1943 PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock,
1951 PJ_ASSERT_RETURN(ssock && pool && buff_size && readbuf, PJ_EINVAL);
1952 PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
1954 /* Create SSL socket read buffer */
1955 ssock->ssock_rbuf = (read_data_t*)pj_pool_calloc(pool,
1956 ssock->param.async_cnt,
1957 sizeof(read_data_t));
1959 /* Store SSL socket read buffer pointer in the activesock read buffer */
1960 for (i=0; i<ssock->param.async_cnt; ++i) {
1961 read_data_t **p_ssock_rbuf =
1962 OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]);
1964 ssock->ssock_rbuf[i].data = readbuf[i];
1965 ssock->ssock_rbuf[i].len = 0;
1967 *p_ssock_rbuf = &ssock->ssock_rbuf[i];
1970 ssock->read_size = buff_size;
1971 ssock->read_started = PJ_TRUE;
1972 ssock->read_flags = flags;
1979 * Same as pj_ssl_sock_start_read(), except that this function is used
1980 * only for datagram sockets, and it will trigger \a on_data_recvfrom()
1983 PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock,
1988 PJ_UNUSED_ARG(ssock);
1989 PJ_UNUSED_ARG(pool);
1990 PJ_UNUSED_ARG(buff_size);
1991 PJ_UNUSED_ARG(flags);
1998 * Same as #pj_ssl_sock_start_recvfrom() except that the recvfrom()
1999 * operation takes the buffer from the argument rather than creating
2002 PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock,
2008 PJ_UNUSED_ARG(ssock);
2009 PJ_UNUSED_ARG(pool);
2010 PJ_UNUSED_ARG(buff_size);
2011 PJ_UNUSED_ARG(readbuf);
2012 PJ_UNUSED_ARG(flags);
2017 /* Write plain data to SSL and flush write BIO. Note that accessing
2018 * write BIO must be serialized, so a call to this function must be
2019 * protected by write mutex of SSL socket.
2021 static pj_status_t ssl_write(pj_ssl_sock_t *ssock,
2022 pj_ioqueue_op_key_t *send_key,
2030 /* Write the plain data to SSL, after SSL encrypts it, write BIO will
2031 * contain the secured data to be sent via socket. Note that re-
2032 * negotitation may be on progress, so sending data should be delayed
2033 * until re-negotiation is completed.
2035 nwritten = SSL_write(ssock->ossl_ssl, data, size);
2037 if (nwritten == size) {
2038 /* All data written, flush write BIO to network socket */
2039 status = flush_write_bio(ssock, send_key, size, flags);
2040 } else if (nwritten <= 0) {
2041 /* SSL failed to process the data, it may just that re-negotiation
2045 err = SSL_get_error(ssock->ossl_ssl, nwritten);
2046 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_NONE) {
2047 /* Re-negotiation is on progress, flush re-negotiation data */
2048 status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
2049 if (status == PJ_SUCCESS || status == PJ_EPENDING)
2050 /* Just return PJ_EBUSY when re-negotiation is on progress */
2053 /* Some problem occured */
2054 GET_SSL_STATUS(status);
2057 /* nwritten < *size, shouldn't happen, unless write BIO cannot hold
2058 * the whole secured data, perhaps because of insufficient memory.
2066 /* Flush delayed data sending in the write pending list. Note that accessing
2067 * write pending list must be serialized, so a call to this function must be
2068 * protected by write mutex of SSL socket.
2070 static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock)
2072 while (!pj_list_empty(&ssock->write_pending)) {
2073 write_pending_t *wp;
2076 wp = ssock->write_pending.next;
2078 status = ssl_write(ssock, &wp->data.key, wp->data.data.ptr,
2079 wp->data.plain_data_len, wp->data.flags);
2080 if (status != PJ_SUCCESS)
2084 pj_list_push_back(&ssock->write_pending_empty, wp);
2090 /* Sending is delayed, push back the sending data into pending list. Note that
2091 * accessing write pending list must be serialized, so a call to this function
2092 * must be protected by write mutex of SSL socket.
2094 static pj_status_t delay_send (pj_ssl_sock_t *ssock,
2095 pj_ioqueue_op_key_t *send_key,
2100 write_pending_t *wp;
2102 /* Init write pending instance */
2103 if (!pj_list_empty(&ssock->write_pending_empty)) {
2104 wp = ssock->write_pending_empty.next;
2107 wp = PJ_POOL_ZALLOC_T(ssock->pool, write_pending_t);
2110 wp->data.app_key = send_key;
2111 wp->data.plain_data_len = size;
2112 wp->data.data.ptr = data;
2113 wp->data.flags = flags;
2115 pj_list_push_back(&ssock->write_pending, wp);
2117 /* Must return PJ_EPENDING */
2122 * Send data using the socket.
2124 PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock,
2125 pj_ioqueue_op_key_t *send_key,
2132 PJ_ASSERT_RETURN(ssock && data && size && (*size>0), PJ_EINVAL);
2133 PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2135 pj_lock_acquire(ssock->write_mutex);
2137 /* Flush delayed send first. Sending data might be delayed when
2138 * re-negotiation is on-progress.
2140 status = flush_delayed_send(ssock);
2141 if (status == PJ_EBUSY) {
2142 /* Re-negotiation is on progress, delay sending */
2143 status = delay_send(ssock, send_key, data, *size, flags);
2145 } else if (status != PJ_SUCCESS) {
2149 /* Write data to SSL */
2150 status = ssl_write(ssock, send_key, data, *size, flags);
2151 if (status == PJ_EBUSY) {
2152 /* Re-negotiation is on progress, delay sending */
2153 status = delay_send(ssock, send_key, data, *size, flags);
2157 pj_lock_release(ssock->write_mutex);
2163 * Send datagram using the socket.
2165 PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock,
2166 pj_ioqueue_op_key_t *send_key,
2170 const pj_sockaddr_t *addr,
2173 PJ_UNUSED_ARG(ssock);
2174 PJ_UNUSED_ARG(send_key);
2175 PJ_UNUSED_ARG(data);
2176 PJ_UNUSED_ARG(size);
2177 PJ_UNUSED_ARG(flags);
2178 PJ_UNUSED_ARG(addr);
2179 PJ_UNUSED_ARG(addr_len);
2186 * Starts asynchronous socket accept() operations on this secure socket.
2188 PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock,
2190 const pj_sockaddr_t *localaddr,
2193 pj_activesock_cb asock_cb;
2194 pj_activesock_cfg asock_cfg;
2197 PJ_ASSERT_RETURN(ssock && pool && localaddr && addr_len, PJ_EINVAL);
2200 status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0,
2202 if (status != PJ_SUCCESS)
2205 /* Apply QoS, if specified */
2206 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
2207 &ssock->param.qos_params, 2,
2208 ssock->pool->obj_name, NULL);
2209 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
2213 status = pj_sock_bind(ssock->sock, localaddr, addr_len);
2214 if (status != PJ_SUCCESS)
2217 /* Start listening to the address */
2218 status = pj_sock_listen(ssock->sock, PJ_SOMAXCONN);
2219 if (status != PJ_SUCCESS)
2222 /* Create active socket */
2223 pj_activesock_cfg_default(&asock_cfg);
2224 asock_cfg.async_cnt = ssock->param.async_cnt;
2225 asock_cfg.concurrency = ssock->param.concurrency;
2226 asock_cfg.whole_data = PJ_TRUE;
2228 pj_bzero(&asock_cb, sizeof(asock_cb));
2229 asock_cb.on_accept_complete = asock_on_accept_complete;
2231 status = pj_activesock_create(pool,
2233 ssock->param.sock_type,
2235 ssock->param.ioqueue,
2240 if (status != PJ_SUCCESS)
2243 /* Start accepting */
2244 status = pj_activesock_start_accept(ssock->asock, pool);
2245 if (status != PJ_SUCCESS)
2248 /* Update local address */
2249 ssock->addr_len = addr_len;
2250 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
2252 if (status != PJ_SUCCESS)
2253 pj_sockaddr_cp(&ssock->local_addr, localaddr);
2255 ssock->is_server = PJ_TRUE;
2260 reset_ssl_sock_state(ssock);
2266 * Starts asynchronous socket connect() operation.
2268 PJ_DECL(pj_status_t) pj_ssl_sock_start_connect(pj_ssl_sock_t *ssock,
2270 const pj_sockaddr_t *localaddr,
2271 const pj_sockaddr_t *remaddr,
2274 pj_activesock_cb asock_cb;
2275 pj_activesock_cfg asock_cfg;
2278 PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len,
2282 status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0,
2284 if (status != PJ_SUCCESS)
2287 /* Apply QoS, if specified */
2288 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
2289 &ssock->param.qos_params, 2,
2290 ssock->pool->obj_name, NULL);
2291 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
2295 status = pj_sock_bind(ssock->sock, localaddr, addr_len);
2296 if (status != PJ_SUCCESS)
2299 /* Create active socket */
2300 pj_activesock_cfg_default(&asock_cfg);
2301 asock_cfg.async_cnt = ssock->param.async_cnt;
2302 asock_cfg.concurrency = ssock->param.concurrency;
2303 asock_cfg.whole_data = PJ_TRUE;
2305 pj_bzero(&asock_cb, sizeof(asock_cb));
2306 asock_cb.on_connect_complete = asock_on_connect_complete;
2307 asock_cb.on_data_read = asock_on_data_read;
2308 asock_cb.on_data_sent = asock_on_data_sent;
2310 status = pj_activesock_create(pool,
2312 ssock->param.sock_type,
2314 ssock->param.ioqueue,
2319 if (status != PJ_SUCCESS)
2322 /* Save remote address */
2323 pj_sockaddr_cp(&ssock->rem_addr, remaddr);
2326 if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
2327 ssock->param.timeout.msec != 0))
2329 pj_assert(ssock->timer.id == TIMER_NONE);
2330 ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
2331 status = pj_timer_heap_schedule(ssock->param.timer_heap,
2333 &ssock->param.timeout);
2334 if (status != PJ_SUCCESS)
2335 ssock->timer.id = TIMER_NONE;
2338 status = pj_activesock_start_connect(ssock->asock, pool, remaddr,
2341 if (status == PJ_SUCCESS)
2342 asock_on_connect_complete(ssock->asock, PJ_SUCCESS);
2343 else if (status != PJ_EPENDING)
2346 /* Update local address */
2347 ssock->addr_len = addr_len;
2348 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
2350 /* Note that we may not get an IP address here. This can
2351 * happen for example on Windows, where getsockname()
2352 * would return 0.0.0.0 if socket has just started the
2353 * async connect. In this case, just leave the local
2354 * address with 0.0.0.0 for now; it will be updated
2355 * once the socket is established.
2358 /* Update SSL state */
2359 ssock->is_server = PJ_FALSE;
2364 reset_ssl_sock_state(ssock);
2369 PJ_DEF(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock)
2374 PJ_ASSERT_RETURN(ssock->ssl_state == SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2376 if (SSL_renegotiate_pending(ssock->ossl_ssl))
2379 ret = SSL_renegotiate(ssock->ossl_ssl);
2381 GET_SSL_STATUS(status);
2383 status = do_handshake(ssock);
2389 #endif /* PJ_HAS_SSL_SOCK */