1
/* $Id: ssl_sock_ossl.c 3553 2011-05-05 06:14:19Z nanang $ */
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
* Include OpenSSL headers
45
#include <openssl/bio.h>
46
#include <openssl/ssl.h>
47
#include <openssl/err.h>
48
#include <openssl/x509v3.h>
53
# pragma comment( lib, "libeay32MTd")
54
# pragma comment( lib, "ssleay32MTd")
56
# pragma comment( lib, "libeay32MT")
57
# pragma comment( lib, "ssleay32MT")
63
* SSL/TLS state enumeration.
67
SSL_STATE_HANDSHAKING,
72
* Internal timer types.
77
TIMER_HANDSHAKE_TIMEOUT,
82
* Structure of SSL socket read buffer.
84
typedef struct read_data_t
91
* Get the offset of pointer to read-buffer of SSL socket from read-buffer
92
* of active socket. Note that both SSL socket and active socket employ
93
* different but correlated read-buffers (as much as async_cnt for each),
94
* and to make it easier/faster to find corresponding SSL socket's read-buffer
95
* from known active socket's read-buffer, the pointer of corresponding
96
* SSL socket's read-buffer is stored right after the end of active socket's
99
#define OFFSET_OF_READ_DATA_PTR(ssock, asock_rbuf) \
101
((pj_int8_t*)(asock_rbuf) + \
102
ssock->param.read_buffer_size)
105
* Structure of SSL socket write buffer.
107
typedef struct write_data_t {
108
pj_ioqueue_op_key_t key;
109
pj_size_t record_len;
110
pj_ioqueue_op_key_t *app_key;
111
pj_size_t plain_data_len;
121
* Structure of SSL socket write state.
123
typedef struct write_state_t {
128
write_data_t *last_data;
132
* Structure of write data pending.
134
typedef struct write_pending_t {
135
PJ_DECL_LIST_MEMBER(struct write_pending_t);
140
* Secure socket structure definition.
145
pj_ssl_sock_t *parent;
146
pj_ssl_sock_param param;
149
pj_ssl_cert_info local_cert_info;
150
pj_ssl_cert_info remote_cert_info;
153
enum ssl_state ssl_state;
154
pj_ioqueue_op_key_t handshake_op_key;
155
pj_timer_entry timer;
156
pj_status_t verify_status;
159
pj_activesock_t *asock;
161
pj_sockaddr local_addr;
162
pj_sockaddr rem_addr;
165
pj_bool_t read_started;
167
pj_uint32_t read_flags;
169
read_data_t *ssock_rbuf;
171
write_state_t write_state;
172
write_pending_t write_pending;
173
write_pending_t write_pending_empty;
174
pj_lock_t *write_mutex; /* protect write BIO and write_state */
184
* Certificate/credential structure definition.
190
pj_str_t privkey_file;
191
pj_str_t privkey_pass;
195
static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock);
198
*******************************************************************
199
* Static/internal functions.
200
*******************************************************************
204
* Mapping from OpenSSL error codes to pjlib error space.
207
#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \
208
PJ_ERRNO_SPACE_SIZE*6)
210
#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE
212
#define STATUS_FROM_SSL_ERR(err, status) { \
213
status = ERR_GET_LIB(err)*300 + ERR_GET_REASON(err);\
214
pj_assert(status < PJ_SSL_ERRNO_SPACE_SIZE);\
215
if (status) status += PJ_SSL_ERRNO_START;\
218
#define GET_SSL_STATUS(status) { \
219
unsigned long e = ERR_get_error();\
220
STATUS_FROM_SSL_ERR(e, status);\
224
* Get error string of OpenSSL.
226
static pj_str_t ssl_strerror(pj_status_t status,
227
char *buf, pj_size_t bufsize)
230
unsigned long ssl_err = status;
234
ssl_err -= PJ_SSL_ERRNO_START;
237
ssl_err = ERR_PACK(l, 0, r);
240
#if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0)
243
const char *tmp = NULL;
246
tmp = ERR_reason_error_string(ssl_err);
248
tmp = X509_verify_cert_error_string(ssl_err);
251
pj_ansi_strncpy(buf, tmp, bufsize);
252
errstr = pj_str(buf);
257
#endif /* PJ_HAS_ERROR_STRING */
260
errstr.slen = pj_ansi_snprintf(buf, bufsize,
261
"Unknown OpenSSL error %lu",
268
/* OpenSSL library initialization counter */
269
static int openssl_init_count;
271
/* OpenSSL available ciphers */
272
static pj_ssl_cipher openssl_ciphers[100];
273
static unsigned openssl_cipher_num;
275
/* OpenSSL application data index */
276
static int sslsock_idx;
279
/* Initialize OpenSSL */
280
static pj_status_t init_openssl(void)
284
if (openssl_init_count)
287
openssl_init_count = 1;
289
/* Register error subsystem */
290
status = pj_register_strerror(PJ_SSL_ERRNO_START,
291
PJ_SSL_ERRNO_SPACE_SIZE,
293
pj_assert(status == PJ_SUCCESS);
295
/* Init OpenSSL lib */
297
SSL_load_error_strings();
298
OpenSSL_add_all_algorithms();
300
/* Init available ciphers */
301
if (openssl_cipher_num == 0) {
302
SSL_METHOD *meth = NULL;
305
STACK_OF(SSL_CIPHER) *sk_cipher;
308
meth = (SSL_METHOD*)SSLv23_server_method();
310
meth = (SSL_METHOD*)TLSv1_server_method();
312
meth = (SSL_METHOD*)SSLv3_server_method();
315
ctx=SSL_CTX_new(meth);
316
SSL_CTX_set_cipher_list(ctx, "ALL");
319
sk_cipher = SSL_get_ciphers(ssl);
321
n = sk_SSL_CIPHER_num(sk_cipher);
322
if (n > PJ_ARRAY_SIZE(openssl_ciphers))
323
n = PJ_ARRAY_SIZE(openssl_ciphers);
325
for (i = 0; i < n; ++i) {
327
c = sk_SSL_CIPHER_value(sk_cipher,i);
328
openssl_ciphers[i] = (pj_ssl_cipher)
329
(pj_uint32_t)c->id & 0x00FFFFFF;
330
//printf("%3u: %08x=%s\n", i+1, c->id, SSL_CIPHER_get_name(c));
336
openssl_cipher_num = n;
339
/* Create OpenSSL application data index for SSL socket */
340
sslsock_idx = SSL_get_ex_new_index(0, "SSL socket", NULL, NULL, NULL);
346
/* Shutdown OpenSSL */
347
static void shutdown_openssl(void)
349
PJ_UNUSED_ARG(openssl_init_count);
353
/* SSL password callback. */
354
static int password_cb(char *buf, int num, int rwflag, void *user_data)
356
pj_ssl_cert_t *cert = (pj_ssl_cert_t*) user_data;
358
PJ_UNUSED_ARG(rwflag);
360
if(num < cert->privkey_pass.slen)
363
pj_memcpy(buf, cert->privkey_pass.ptr, cert->privkey_pass.slen);
364
return cert->privkey_pass.slen;
368
/* SSL password callback. */
369
static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
371
pj_ssl_sock_t *ssock;
375
/* Get SSL instance */
376
ossl_ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
377
SSL_get_ex_data_X509_STORE_CTX_idx());
380
/* Get SSL socket instance */
381
ssock = SSL_get_ex_data(ossl_ssl, sslsock_idx);
384
/* Store verification status */
385
err = X509_STORE_CTX_get_error(x509_ctx);
390
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
391
ssock->verify_status |= PJ_SSL_CERT_EISSUER_NOT_FOUND;
394
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
395
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
396
case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
397
case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
398
ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
401
case X509_V_ERR_CERT_NOT_YET_VALID:
402
case X509_V_ERR_CERT_HAS_EXPIRED:
403
ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
406
case X509_V_ERR_UNABLE_TO_GET_CRL:
407
case X509_V_ERR_CRL_NOT_YET_VALID:
408
case X509_V_ERR_CRL_HAS_EXPIRED:
409
case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
410
case X509_V_ERR_CRL_SIGNATURE_FAILURE:
411
case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
412
case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
413
ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE;
416
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
417
case X509_V_ERR_CERT_UNTRUSTED:
418
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
419
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
420
ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
423
case X509_V_ERR_CERT_SIGNATURE_FAILURE:
424
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
425
case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
426
case X509_V_ERR_AKID_SKID_MISMATCH:
427
case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
428
case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
429
ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH;
432
case X509_V_ERR_CERT_REVOKED:
433
ssock->verify_status |= PJ_SSL_CERT_EREVOKED;
436
case X509_V_ERR_INVALID_PURPOSE:
437
case X509_V_ERR_CERT_REJECTED:
438
case X509_V_ERR_INVALID_CA:
439
ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE;
442
case X509_V_ERR_CERT_CHAIN_TOO_LONG: /* not really used */
443
case X509_V_ERR_PATH_LENGTH_EXCEEDED:
444
ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG;
448
case X509_V_ERR_OUT_OF_MEM:
450
ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
454
/* When verification is not requested just return ok here, however
455
* application can still get the verification status.
457
if (PJ_FALSE == ssock->param.verify_peer)
463
/* Setting SSL sock cipher list */
464
static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock);
467
/* Create and initialize new SSL context and instance */
468
static pj_status_t create_ssl(pj_ssl_sock_t *ssock)
470
SSL_METHOD *ssl_method;
480
/* Make sure OpenSSL library has been initialized */
483
/* Determine SSL method to use */
484
switch (ssock->param.proto) {
485
case PJ_SSL_SOCK_PROTO_DEFAULT:
486
case PJ_SSL_SOCK_PROTO_TLS1:
487
ssl_method = (SSL_METHOD*)TLSv1_method();
489
case PJ_SSL_SOCK_PROTO_SSL3:
490
ssl_method = (SSL_METHOD*)SSLv3_method();
492
case PJ_SSL_SOCK_PROTO_SSL23:
493
ssl_method = (SSL_METHOD*)SSLv23_method();
495
//case PJ_SSL_SOCK_PROTO_DTLS1:
496
//ssl_method = (SSL_METHOD*)DTLSv1_method();
502
/* Create SSL context */
503
ctx = SSL_CTX_new(ssl_method);
505
GET_SSL_STATUS(status);
509
/* Apply credentials */
511
/* Load CA list if one is specified. */
512
if (cert->CA_file.slen) {
514
rc = SSL_CTX_load_verify_locations(ctx, cert->CA_file.ptr, NULL);
517
GET_SSL_STATUS(status);
518
PJ_LOG(1,(ssock->pool->obj_name, "Error loading CA list file "
519
"'%s'", cert->CA_file.ptr));
525
/* Set password callback */
526
if (cert->privkey_pass.slen) {
527
SSL_CTX_set_default_passwd_cb(ctx, password_cb);
528
SSL_CTX_set_default_passwd_cb_userdata(ctx, cert);
532
/* Load certificate if one is specified */
533
if (cert->cert_file.slen) {
535
/* Load certificate chain from file into ctx */
536
rc = SSL_CTX_use_certificate_chain_file(ctx, cert->cert_file.ptr);
539
GET_SSL_STATUS(status);
540
PJ_LOG(1,(ssock->pool->obj_name, "Error loading certificate "
541
"chain file '%s'", cert->cert_file.ptr));
548
/* Load private key if one is specified */
549
if (cert->privkey_file.slen) {
550
/* Adds the first private key found in file to ctx */
551
rc = SSL_CTX_use_PrivateKey_file(ctx, cert->privkey_file.ptr,
555
GET_SSL_STATUS(status);
556
PJ_LOG(1,(ssock->pool->obj_name, "Error adding private key "
557
"from '%s'", cert->privkey_file.ptr));
564
/* Create SSL instance */
565
ssock->ossl_ctx = ctx;
566
ssock->ossl_ssl = SSL_new(ssock->ossl_ctx);
567
if (ssock->ossl_ssl == NULL) {
568
GET_SSL_STATUS(status);
572
/* Set SSL sock as application data of SSL instance */
573
SSL_set_ex_data(ssock->ossl_ssl, sslsock_idx, ssock);
575
/* SSL verification options */
576
mode = SSL_VERIFY_PEER;
577
if (ssock->is_server && ssock->param.require_client_cert)
578
mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
580
SSL_set_verify(ssock->ossl_ssl, mode, &verify_cb);
582
/* Set cipher list */
583
status = set_cipher_list(ssock);
584
if (status != PJ_SUCCESS)
588
ssock->ossl_rbio = BIO_new(BIO_s_mem());
589
ssock->ossl_wbio = BIO_new(BIO_s_mem());
590
BIO_set_close(ssock->ossl_rbio, BIO_CLOSE);
591
BIO_set_close(ssock->ossl_wbio, BIO_CLOSE);
592
SSL_set_bio(ssock->ossl_ssl, ssock->ossl_rbio, ssock->ossl_wbio);
598
/* Destroy SSL context and instance */
599
static void destroy_ssl(pj_ssl_sock_t *ssock)
601
/* Destroy SSL instance */
602
if (ssock->ossl_ssl) {
603
SSL_shutdown(ssock->ossl_ssl);
604
SSL_free(ssock->ossl_ssl); /* this will also close BIOs */
605
ssock->ossl_ssl = NULL;
608
/* Destroy SSL context */
609
if (ssock->ossl_ctx) {
610
SSL_CTX_free(ssock->ossl_ctx);
611
ssock->ossl_ctx = NULL;
614
/* Potentially shutdown OpenSSL library if this is the last
621
/* Reset SSL socket state */
622
static void reset_ssl_sock_state(pj_ssl_sock_t *ssock)
624
ssock->ssl_state = SSL_STATE_NULL;
629
pj_activesock_close(ssock->asock);
631
ssock->sock = PJ_INVALID_SOCKET;
633
if (ssock->sock != PJ_INVALID_SOCKET) {
634
pj_sock_close(ssock->sock);
635
ssock->sock = PJ_INVALID_SOCKET;
638
/* Upon error, OpenSSL may leave any error description in the thread
639
* error queue, which sometime may cause next call to SSL API returning
640
* false error alarm, e.g: in Linux, SSL_CTX_use_certificate_chain_file()
641
* returning false error after a handshake error (in different SSL_CTX!).
642
* For now, just clear thread error queue here.
648
/* Generate cipher list with user preference order in OpenSSL format */
649
static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock)
652
pj_str_t cipher_list;
653
STACK_OF(SSL_CIPHER) *sk_cipher;
657
if (ssock->param.ciphers_num == 0)
660
pj_strset(&cipher_list, buf, 0);
662
/* Set SSL with ALL available ciphers */
663
SSL_set_cipher_list(ssock->ossl_ssl, "ALL");
665
/* Generate user specified cipher list in OpenSSL format */
666
sk_cipher = SSL_get_ciphers(ssock->ossl_ssl);
667
for (i = 0; i < ssock->param.ciphers_num; ++i) {
668
for (j = 0; j < sk_SSL_CIPHER_num(sk_cipher); ++j) {
670
c = sk_SSL_CIPHER_value(sk_cipher, j);
671
if (ssock->param.ciphers[i] == (pj_ssl_cipher)
672
((pj_uint32_t)c->id & 0x00FFFFFF))
676
c_name = SSL_CIPHER_get_name(c);
678
/* Check buffer size */
679
if (cipher_list.slen + pj_ansi_strlen(c_name) + 2 > sizeof(buf)) {
680
pj_assert(!"Insufficient temporary buffer for cipher");
684
/* Add colon separator */
685
if (cipher_list.slen)
686
pj_strcat2(&cipher_list, ":");
689
pj_strcat2(&cipher_list, c_name);
695
/* Put NULL termination in the generated cipher list */
696
cipher_list.ptr[cipher_list.slen] = '\0';
698
/* Finally, set chosen cipher list */
699
ret = SSL_set_cipher_list(ssock->ossl_ssl, buf);
702
GET_SSL_STATUS(status);
710
/* Parse OpenSSL ASN1_TIME to pj_time_val and GMT info */
711
static pj_bool_t parse_ossl_asn1_time(pj_time_val *tv, pj_bool_t *gmt,
714
unsigned long parts[7] = {0};
721
utc = tm->type == V_ASN1_UTCTIME;
727
*gmt = (*end == 'Z');
730
for (i = 0; i < 7 && p < end; ++i) {
734
/* 4 digits year part for non-UTC time format */
737
/* fraction of seconds */
739
st.slen = end - p + 1;
741
/* other parts always 2 digits length */
746
parts[i] = pj_strtoul(&st);
750
/* encode parts to pj_time_val */
753
pt.year += (pt.year < 50)? 2000:1900;
754
pt.mon = parts[1] - 1;
761
pj_time_encode(&pt, tv);
767
/* Get Common Name field string from a general name string */
768
static void get_cn_from_gen_name(const pj_str_t *gen_name, pj_str_t *cn)
770
pj_str_t CN_sign = {"/CN=", 4};
773
pj_bzero(cn, sizeof(cn));
775
p = pj_strstr(gen_name, &CN_sign);
779
p += 4; /* shift pointer to value part */
780
pj_strset(cn, p, gen_name->slen - (p - gen_name->ptr));
781
q = pj_strchr(cn, '/');
787
/* Get certificate info from OpenSSL X509, in case the certificate info
788
* hal already populated, this function will check if the contents need
789
* to be updated by inspecting the issuer and the serial number.
791
static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, X509 *x)
793
pj_bool_t update_needed;
795
pj_uint8_t serial_no[64] = {0}; /* should be >= sizeof(ci->serial_no) */
798
GENERAL_NAMES *names = NULL;
800
pj_assert(pool && ci && x);
803
X509_NAME_oneline(X509_get_issuer_name(x), buf, sizeof(buf));
806
p = (pj_uint8_t*) M_ASN1_STRING_data(X509_get_serialNumber(x));
807
len = M_ASN1_STRING_length(X509_get_serialNumber(x));
808
if (len > sizeof(ci->serial_no))
809
len = sizeof(ci->serial_no);
810
pj_memcpy(serial_no + sizeof(ci->serial_no) - len, p, len);
812
/* Check if the contents need to be updated. */
813
update_needed = pj_strcmp2(&ci->issuer.info, buf) ||
814
pj_memcmp(ci->serial_no, serial_no, sizeof(ci->serial_no));
818
/* Update cert info */
820
pj_bzero(ci, sizeof(pj_ssl_cert_info));
823
ci->version = X509_get_version(x) + 1;
826
pj_strdup2(pool, &ci->issuer.info, buf);
827
get_cn_from_gen_name(&ci->issuer.info, &ci->issuer.cn);
830
pj_memcpy(ci->serial_no, serial_no, sizeof(ci->serial_no));
833
pj_strdup2(pool, &ci->subject.info,
834
X509_NAME_oneline(X509_get_subject_name(x),
836
get_cn_from_gen_name(&ci->subject.info, &ci->subject.cn);
839
parse_ossl_asn1_time(&ci->validity.start, &ci->validity.gmt,
840
X509_get_notBefore(x));
841
parse_ossl_asn1_time(&ci->validity.end, &ci->validity.gmt,
842
X509_get_notAfter(x));
844
/* Subject Alternative Name extension */
845
if (ci->version >= 3) {
846
names = (GENERAL_NAMES*) X509_get_ext_d2i(x, NID_subject_alt_name,
852
cnt = sk_GENERAL_NAME_num(names);
853
ci->subj_alt_name.entry = pj_pool_calloc(pool, cnt,
854
sizeof(*ci->subj_alt_name.entry));
856
for (i = 0; i < cnt; ++i) {
857
unsigned char *p = 0;
858
pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN;
859
const GENERAL_NAME *name;
861
name = sk_GENERAL_NAME_value(names, i);
863
switch (name->type) {
865
len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
866
type = PJ_SSL_CERT_NAME_RFC822;
869
len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
870
type = PJ_SSL_CERT_NAME_DNS;
873
len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
874
type = PJ_SSL_CERT_NAME_URI;
877
p = ASN1_STRING_data(name->d.ip);
878
len = ASN1_STRING_length(name->d.ip);
879
type = PJ_SSL_CERT_NAME_IP;
885
if (p && len && type != PJ_SSL_CERT_NAME_UNKNOWN) {
886
ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type;
887
if (type == PJ_SSL_CERT_NAME_IP) {
888
int af = pj_AF_INET();
889
if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6();
890
pj_inet_ntop2(af, p, buf, sizeof(buf));
892
&ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
896
&ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
900
ci->subj_alt_name.cnt++;
907
/* Update local & remote certificates info. This function should be
908
* called after handshake or renegotiation successfully completed.
910
static void update_certs_info(pj_ssl_sock_t *ssock)
914
pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED);
916
/* Active local certificate */
917
x = SSL_get_certificate(ssock->ossl_ssl);
919
get_cert_info(ssock->pool, &ssock->local_cert_info, x);
920
/* Don't free local's X509! */
922
pj_bzero(&ssock->local_cert_info, sizeof(pj_ssl_cert_info));
925
/* Active remote certificate */
926
x = SSL_get_peer_certificate(ssock->ossl_ssl);
928
get_cert_info(ssock->pool, &ssock->remote_cert_info, x);
929
/* Free peer's X509 */
932
pj_bzero(&ssock->remote_cert_info, sizeof(pj_ssl_cert_info));
937
/* When handshake completed:
938
* - notify application
939
* - if handshake failed, reset SSL state
940
* - return PJ_FALSE when SSL socket instance is destroyed by application.
942
static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock,
945
/* Cancel handshake timer */
946
if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) {
947
pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
948
ssock->timer.id = TIMER_NONE;
951
/* Update certificates info on successful handshake */
952
if (status == PJ_SUCCESS)
953
update_certs_info(ssock);
956
if (ssock->is_server) {
957
if (status != PJ_SUCCESS) {
958
/* Handshake failed in accepting, destroy our self silently. */
960
char errmsg[PJ_ERR_MSG_SIZE];
961
char buf[PJ_INET6_ADDRSTRLEN+10];
963
pj_strerror(status, errmsg, sizeof(errmsg));
964
PJ_LOG(3,(ssock->pool->obj_name, "Handshake failed in accepting "
966
pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3),
969
/* Workaround for ticket #985 */
970
#if defined(PJ_WIN32) && PJ_WIN32!=0
971
if (ssock->param.timer_heap) {
972
pj_time_val interval = {0, DELAYED_CLOSE_TIMEOUT};
974
reset_ssl_sock_state(ssock);
976
ssock->timer.id = TIMER_CLOSE;
977
pj_time_val_normalize(&interval);
978
if (pj_timer_heap_schedule(ssock->param.timer_heap,
979
&ssock->timer, &interval) != 0)
981
ssock->timer.id = TIMER_NONE;
982
pj_ssl_sock_close(ssock);
985
#endif /* PJ_WIN32 */
987
pj_ssl_sock_close(ssock);
991
/* Notify application the newly accepted SSL socket */
992
if (ssock->param.cb.on_accept_complete) {
994
ret = (*ssock->param.cb.on_accept_complete)
995
(ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,
996
pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr));
1004
/* On failure, reset SSL socket state first, as app may try to
1005
* reconnect in the callback.
1007
if (status != PJ_SUCCESS) {
1008
reset_ssl_sock_state(ssock);
1010
if (ssock->param.cb.on_connect_complete) {
1012
ret = (*ssock->param.cb.on_connect_complete)(ssock, status);
1013
if (ret == PJ_FALSE)
1021
/* Flush write BIO to network socket. Note that any access to write BIO
1022
* MUST be serialized, so mutex protection must cover any call to OpenSSL
1023
* API (that possibly generate data for write BIO) along with the call to
1024
* this function (flushing all data in write BIO generated by above
1025
* OpenSSL API call).
1027
static pj_status_t flush_write_bio(pj_ssl_sock_t *ssock,
1028
pj_ioqueue_op_key_t *send_key,
1035
write_state_t *write_st = &ssock->write_state;
1036
write_data_t *wdata;
1037
pj_size_t avail_len, needed_len, skipped_len = 0;
1040
/* Check if there is data in write BIO, flush it if any */
1041
if (!BIO_pending(ssock->ossl_wbio))
1044
/* Get data and its length */
1045
len = BIO_get_mem_data(ssock->ossl_wbio, &data);
1049
/* Calculate buffer size needed, and align it to 8 */
1050
needed_len = len + sizeof(write_data_t);
1051
needed_len = ((needed_len + 7) >> 3) << 3;
1053
/* Check buffer availability */
1054
avail_len = write_st->max_len - write_st->len;
1055
if (avail_len < needed_len)
1058
/* More buffer availability check, note that the write data must be in
1059
* a contigue buffer.
1061
if (write_st->len == 0) {
1063
write_st->start = write_st->buf;
1064
wdata = (write_data_t*)write_st->start;
1069
pj_size_t reg1_len, reg2_len;
1071
/* Unused slots may be wrapped/splitted into two regions, so let's
1072
* analyze them if any region can hold the write data.
1074
reg1 = write_st->start + write_st->len;
1075
if (reg1 >= write_st->buf + write_st->max_len)
1076
reg1 -= write_st->max_len;
1077
reg1_len = write_st->max_len - write_st->len;
1078
if (reg1 + reg1_len > write_st->buf + write_st->max_len) {
1079
reg1_len = write_st->buf + write_st->max_len - reg1;
1080
reg2 = write_st->buf;
1081
reg2_len = write_st->start - write_st->buf;
1086
avail_len = PJ_MAX(reg1_len, reg2_len);
1087
if (avail_len < needed_len)
1090
/* Get write data pointer and update buffer length */
1091
if (reg1_len >= needed_len) {
1092
wdata = (write_data_t*)reg1;
1094
wdata = (write_data_t*)reg2;
1095
/* Unused slot in region 1 is skipped as current write data
1098
skipped_len = reg1_len;
1102
/* Copy the data and set its properties into the buffer */
1103
pj_bzero(wdata, sizeof(write_data_t));
1104
wdata->app_key = send_key;
1105
wdata->record_len = needed_len;
1106
wdata->data_len = len;
1107
wdata->plain_data_len = orig_len;
1108
wdata->flags = flags;
1109
pj_memcpy(&wdata->data, data, len);
1112
if (ssock->param.sock_type == pj_SOCK_STREAM()) {
1113
status = pj_activesock_send(ssock->asock, &wdata->key,
1114
wdata->data.content, &len,
1117
status = pj_activesock_sendto(ssock->asock, &wdata->key,
1118
wdata->data.content, &len,
1120
(pj_sockaddr_t*)&ssock->rem_addr,
1124
/* Oh no, EWOULDBLOCK! */
1125
if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) {
1126
/* Just return PJ_SUCCESS here, the pending data will be sent in next
1127
* call of this function since the data is still stored in write BIO.
1132
/* Reset write BIO after flushed */
1133
BIO_reset(ssock->ossl_wbio);
1135
if (status == PJ_EPENDING) {
1136
/* Update write state */
1137
pj_assert(skipped_len==0 || write_st->last_data);
1138
write_st->len += needed_len + skipped_len;
1139
if (write_st->last_data)
1140
write_st->last_data->record_len += skipped_len;
1141
write_st->last_data = wdata;
1148
static void on_timer(pj_timer_heap_t *th, struct pj_timer_entry *te)
1150
pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)te->user_data;
1151
int timer_id = te->id;
1153
te->id = TIMER_NONE;
1158
case TIMER_HANDSHAKE_TIMEOUT:
1159
PJ_LOG(1,(ssock->pool->obj_name, "SSL timeout after %d.%ds",
1160
ssock->param.timeout.sec, ssock->param.timeout.msec));
1162
on_handshake_complete(ssock, PJ_ETIMEDOUT);
1165
pj_ssl_sock_close(ssock);
1168
pj_assert(!"Unknown timer");
1174
/* Asynchronouse handshake */
1175
static pj_status_t do_handshake(pj_ssl_sock_t *ssock)
1180
pj_lock_acquire(ssock->write_mutex);
1182
/* Perform SSL handshake */
1183
err = SSL_do_handshake(ssock->ossl_ssl);
1185
err = SSL_get_error(ssock->ossl_ssl, err);
1186
if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
1188
/* Handshake fails */
1189
GET_SSL_STATUS(status);
1190
pj_lock_release(ssock->write_mutex);
1195
/* SSL_do_handshake() may put some pending data into SSL write BIO,
1198
status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
1199
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
1200
pj_lock_release(ssock->write_mutex);
1204
pj_lock_release(ssock->write_mutex);
1206
/* Check if handshake has been completed */
1207
if (SSL_is_init_finished(ssock->ossl_ssl)) {
1208
ssock->ssl_state = SSL_STATE_ESTABLISHED;
1217
*******************************************************************
1218
* Active socket callbacks.
1219
*******************************************************************
1222
static pj_bool_t asock_on_data_read (pj_activesock_t *asock,
1226
pj_size_t *remainder)
1228
pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1229
pj_activesock_get_user_data(asock);
1232
/* Socket error or closed */
1233
if (data && size > 0) {
1234
/* Consume the whole data */
1235
nwritten = BIO_write(ssock->ossl_rbio, data, size);
1236
if (nwritten < size) {
1237
GET_SSL_STATUS(status);
1242
/* Check if SSL handshake hasn't finished yet */
1243
if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
1244
pj_bool_t ret = PJ_TRUE;
1246
if (status == PJ_SUCCESS)
1247
status = do_handshake(ssock);
1249
/* Not pending is either success or failed */
1250
if (status != PJ_EPENDING)
1251
ret = on_handshake_complete(ssock, status);
1256
/* See if there is any decrypted data for the application */
1257
if (ssock->read_started) {
1259
read_data_t *buf = *(OFFSET_OF_READ_DATA_PTR(ssock, data));
1260
void *data_ = (pj_int8_t*)buf->data + buf->len;
1261
int size_ = ssock->read_size - buf->len;
1263
/* SSL_read() may write some data to BIO write when re-negotiation
1264
* is on progress, so let's protect it with write mutex.
1266
pj_lock_acquire(ssock->write_mutex);
1267
size_ = SSL_read(ssock->ossl_ssl, data_, size_);
1268
pj_lock_release(ssock->write_mutex);
1270
if (size_ > 0 || status != PJ_SUCCESS) {
1271
if (ssock->param.cb.on_data_read) {
1273
pj_size_t remainder_ = 0;
1278
ret = (*ssock->param.cb.on_data_read)(ssock, buf->data,
1282
/* We've been destroyed */
1286
/* Application may have left some data to be consumed
1289
buf->len = remainder_;
1292
/* Active socket signalled connection closed/error, this has
1293
* been signalled to the application along with any remaining
1294
* buffer. So, let's just reset SSL socket now.
1296
if (status != PJ_SUCCESS) {
1297
reset_ssl_sock_state(ssock);
1303
int err = SSL_get_error(ssock->ossl_ssl, size);
1305
/* SSL might just return SSL_ERROR_WANT_READ in
1308
if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
1310
/* Reset SSL socket state, then return PJ_FALSE */
1311
GET_SSL_STATUS(status);
1312
reset_ssl_sock_state(ssock);
1316
status = do_handshake(ssock);
1317
if (status == PJ_SUCCESS) {
1318
/* Renegotiation completed */
1320
/* Update certificates */
1321
update_certs_info(ssock);
1323
pj_lock_acquire(ssock->write_mutex);
1324
status = flush_delayed_send(ssock);
1325
pj_lock_release(ssock->write_mutex);
1327
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
1328
PJ_PERROR(1,(ssock->pool->obj_name, status,
1329
"Failed to flush delayed send"));
1332
} else if (status != PJ_EPENDING) {
1333
PJ_PERROR(1,(ssock->pool->obj_name, status,
1334
"Renegotiation failed"));
1346
if (ssock->ssl_state == SSL_STATE_HANDSHAKING)
1347
return on_handshake_complete(ssock, status);
1349
if (ssock->read_started && ssock->param.cb.on_data_read) {
1351
ret = (*ssock->param.cb.on_data_read)(ssock, NULL, 0, status,
1354
/* We've been destroyed */
1359
reset_ssl_sock_state(ssock);
1364
static pj_bool_t asock_on_data_sent (pj_activesock_t *asock,
1365
pj_ioqueue_op_key_t *send_key,
1368
pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1369
pj_activesock_get_user_data(asock);
1371
PJ_UNUSED_ARG(send_key);
1372
PJ_UNUSED_ARG(sent);
1374
if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
1375
/* Initial handshaking */
1378
status = do_handshake(ssock);
1379
/* Not pending is either success or failed */
1380
if (status != PJ_EPENDING)
1381
return on_handshake_complete(ssock, status);
1383
} else if (send_key != &ssock->handshake_op_key) {
1384
/* Some data has been sent, notify application */
1385
write_data_t *wdata = (write_data_t*)send_key;
1386
if (ssock->param.cb.on_data_sent) {
1388
ret = (*ssock->param.cb.on_data_sent)(ssock, wdata->app_key,
1389
wdata->plain_data_len);
1391
/* We've been destroyed */
1396
/* Update write buffer state */
1397
pj_lock_acquire(ssock->write_mutex);
1398
ssock->write_state.start += wdata->record_len;
1399
ssock->write_state.len -= wdata->record_len;
1400
if (ssock->write_state.last_data == wdata) {
1401
pj_assert(ssock->write_state.len == 0);
1402
ssock->write_state.last_data = NULL;
1404
pj_lock_release(ssock->write_mutex);
1407
/* SSL re-negotiation is on-progress, just do nothing */
1414
static pj_bool_t asock_on_accept_complete (pj_activesock_t *asock,
1416
const pj_sockaddr_t *src_addr,
1419
pj_ssl_sock_t *ssock_parent = (pj_ssl_sock_t*)
1420
pj_activesock_get_user_data(asock);
1421
pj_ssl_sock_t *ssock;
1422
pj_activesock_cb asock_cb;
1423
pj_activesock_cfg asock_cfg;
1427
PJ_UNUSED_ARG(src_addr_len);
1429
/* Create new SSL socket instance */
1430
status = pj_ssl_sock_create(ssock_parent->pool, &ssock_parent->param,
1432
if (status != PJ_SUCCESS)
1435
/* Update new SSL socket attributes */
1436
ssock->sock = newsock;
1437
ssock->parent = ssock_parent;
1438
ssock->is_server = PJ_TRUE;
1439
if (ssock_parent->cert) {
1440
status = pj_ssl_sock_set_certificate(ssock, ssock->pool,
1441
ssock_parent->cert);
1442
if (status != PJ_SUCCESS)
1446
/* Apply QoS, if specified */
1447
status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
1448
&ssock->param.qos_params, 1,
1449
ssock->pool->obj_name, NULL);
1450
if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
1453
/* Update local address */
1454
ssock->addr_len = src_addr_len;
1455
status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
1457
if (status != PJ_SUCCESS) {
1458
/* This fails on few envs, e.g: win IOCP, just tolerate this and
1459
* use parent local address instead.
1461
pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);
1464
/* Set remote address */
1465
pj_sockaddr_cp(&ssock->rem_addr, src_addr);
1467
/* Create SSL context */
1468
status = create_ssl(ssock);
1469
if (status != PJ_SUCCESS)
1472
/* Prepare read buffer */
1473
ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool,
1474
ssock->param.async_cnt,
1476
for (i = 0; i<ssock->param.async_cnt; ++i) {
1477
ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
1479
ssock->param.read_buffer_size +
1480
sizeof(read_data_t*));
1483
/* Create active socket */
1484
pj_activesock_cfg_default(&asock_cfg);
1485
asock_cfg.async_cnt = ssock->param.async_cnt;
1486
asock_cfg.concurrency = ssock->param.concurrency;
1487
asock_cfg.whole_data = PJ_TRUE;
1489
pj_bzero(&asock_cb, sizeof(asock_cb));
1490
asock_cb.on_data_read = asock_on_data_read;
1491
asock_cb.on_data_sent = asock_on_data_sent;
1493
status = pj_activesock_create(ssock->pool,
1495
ssock->param.sock_type,
1497
ssock->param.ioqueue,
1502
if (status != PJ_SUCCESS)
1506
status = pj_activesock_start_read2(ssock->asock, ssock->pool,
1507
ssock->param.read_buffer_size,
1509
PJ_IOQUEUE_ALWAYS_ASYNC);
1510
if (status != PJ_SUCCESS)
1513
/* Prepare write/send state */
1514
pj_assert(ssock->write_state.max_len == 0);
1515
ssock->write_state.buf = (char*)
1516
pj_pool_alloc(ssock->pool,
1517
ssock->param.send_buffer_size);
1518
ssock->write_state.max_len = ssock->param.send_buffer_size;
1519
ssock->write_state.start = ssock->write_state.buf;
1520
ssock->write_state.len = 0;
1522
/* Start handshake timer */
1523
if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
1524
ssock->param.timeout.msec != 0))
1526
pj_assert(ssock->timer.id == TIMER_NONE);
1527
ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
1528
status = pj_timer_heap_schedule(ssock->param.timer_heap,
1530
&ssock->param.timeout);
1531
if (status != PJ_SUCCESS)
1532
ssock->timer.id = TIMER_NONE;
1535
/* Start SSL handshake */
1536
ssock->ssl_state = SSL_STATE_HANDSHAKING;
1537
SSL_set_accept_state(ssock->ossl_ssl);
1538
status = do_handshake(ssock);
1541
if (ssock && status != PJ_EPENDING)
1542
on_handshake_complete(ssock, status);
1544
/* Must return PJ_TRUE whatever happened, as active socket must
1545
* continue listening.
1551
static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock,
1554
pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1555
pj_activesock_get_user_data(asock);
1558
if (status != PJ_SUCCESS)
1561
/* Update local address */
1562
ssock->addr_len = sizeof(pj_sockaddr);
1563
status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
1565
if (status != PJ_SUCCESS)
1568
/* Create SSL context */
1569
status = create_ssl(ssock);
1570
if (status != PJ_SUCCESS)
1573
/* Prepare read buffer */
1574
ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool,
1575
ssock->param.async_cnt,
1577
for (i = 0; i<ssock->param.async_cnt; ++i) {
1578
ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
1580
ssock->param.read_buffer_size +
1581
sizeof(read_data_t*));
1585
status = pj_activesock_start_read2(ssock->asock, ssock->pool,
1586
ssock->param.read_buffer_size,
1588
PJ_IOQUEUE_ALWAYS_ASYNC);
1589
if (status != PJ_SUCCESS)
1592
/* Prepare write/send state */
1593
pj_assert(ssock->write_state.max_len == 0);
1594
ssock->write_state.buf = (char*)
1595
pj_pool_alloc(ssock->pool,
1596
ssock->param.send_buffer_size);
1597
ssock->write_state.max_len = ssock->param.send_buffer_size;
1598
ssock->write_state.start = ssock->write_state.buf;
1599
ssock->write_state.len = 0;
1601
#ifdef SSL_set_tlsext_host_name
1602
/* Set server name to connect */
1603
if (ssock->param.server_name.slen) {
1604
/* Server name is null terminated already */
1605
if (!SSL_set_tlsext_host_name(ssock->ossl_ssl,
1606
ssock->param.server_name.ptr))
1608
char err_str[PJ_ERR_MSG_SIZE];
1610
ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
1611
PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() "
1612
"failed: %s", err_str));
1617
/* Start SSL handshake */
1618
ssock->ssl_state = SSL_STATE_HANDSHAKING;
1619
SSL_set_connect_state(ssock->ossl_ssl);
1621
status = do_handshake(ssock);
1622
if (status != PJ_EPENDING)
1628
return on_handshake_complete(ssock, status);
1634
*******************************************************************
1636
*******************************************************************
1639
/* Load credentials from files. */
1640
PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files (pj_pool_t *pool,
1641
const pj_str_t *CA_file,
1642
const pj_str_t *cert_file,
1643
const pj_str_t *privkey_file,
1644
const pj_str_t *privkey_pass,
1645
pj_ssl_cert_t **p_cert)
1647
pj_ssl_cert_t *cert;
1649
PJ_ASSERT_RETURN(pool && CA_file && cert_file && privkey_file, PJ_EINVAL);
1651
cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
1652
pj_strdup_with_null(pool, &cert->CA_file, CA_file);
1653
pj_strdup_with_null(pool, &cert->cert_file, cert_file);
1654
pj_strdup_with_null(pool, &cert->privkey_file, privkey_file);
1655
pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass);
1663
/* Set SSL socket credentials. */
1664
PJ_DECL(pj_status_t) pj_ssl_sock_set_certificate(
1665
pj_ssl_sock_t *ssock,
1667
const pj_ssl_cert_t *cert)
1669
pj_ssl_cert_t *cert_;
1671
PJ_ASSERT_RETURN(ssock && pool && cert, PJ_EINVAL);
1673
cert_ = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
1674
pj_memcpy(cert_, cert, sizeof(cert));
1675
pj_strdup_with_null(pool, &cert_->CA_file, &cert->CA_file);
1676
pj_strdup_with_null(pool, &cert_->cert_file, &cert->cert_file);
1677
pj_strdup_with_null(pool, &cert_->privkey_file, &cert->privkey_file);
1678
pj_strdup_with_null(pool, &cert_->privkey_pass, &cert->privkey_pass);
1680
ssock->cert = cert_;
1686
/* Get available ciphers. */
1687
PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[],
1688
unsigned *cipher_num)
1692
PJ_ASSERT_RETURN(ciphers && cipher_num, PJ_EINVAL);
1694
if (openssl_cipher_num == 0) {
1699
if (openssl_cipher_num == 0)
1700
return PJ_ENOTFOUND;
1702
*cipher_num = PJ_MIN(*cipher_num, openssl_cipher_num);
1704
for (i = 0; i < *cipher_num; ++i)
1705
ciphers[i] = openssl_ciphers[i];
1712
* Create SSL socket instance.
1714
PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool,
1715
const pj_ssl_sock_param *param,
1716
pj_ssl_sock_t **p_ssock)
1718
pj_ssl_sock_t *ssock;
1721
PJ_ASSERT_RETURN(pool && param && p_ssock, PJ_EINVAL);
1722
PJ_ASSERT_RETURN(param->sock_type == pj_SOCK_STREAM(), PJ_ENOTSUP);
1724
pool = pj_pool_create(pool->factory, "ssl%p", 512, 512, NULL);
1726
/* Create secure socket */
1727
ssock = PJ_POOL_ZALLOC_T(pool, pj_ssl_sock_t);
1729
ssock->sock = PJ_INVALID_SOCKET;
1730
ssock->ssl_state = SSL_STATE_NULL;
1731
pj_list_init(&ssock->write_pending);
1732
pj_list_init(&ssock->write_pending_empty);
1733
pj_timer_entry_init(&ssock->timer, 0, ssock, &on_timer);
1735
/* Create secure socket mutex */
1736
status = pj_lock_create_recursive_mutex(pool, pool->obj_name,
1737
&ssock->write_mutex);
1738
if (status != PJ_SUCCESS)
1741
/* Init secure socket param */
1742
ssock->param = *param;
1743
ssock->param.read_buffer_size = ((ssock->param.read_buffer_size+7)>>3)<<3;
1744
if (param->ciphers_num > 0) {
1746
ssock->param.ciphers = (pj_ssl_cipher*)
1747
pj_pool_calloc(pool, param->ciphers_num,
1748
sizeof(pj_ssl_cipher));
1749
for (i = 0; i < param->ciphers_num; ++i)
1750
ssock->param.ciphers[i] = param->ciphers[i];
1753
/* Server name must be null-terminated */
1754
pj_strdup_with_null(pool, &ssock->param.server_name,
1755
¶m->server_name);
1765
* Close the secure socket. This will unregister the socket from the
1766
* ioqueue and ultimately close the socket.
1768
PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock)
1772
PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
1777
if (ssock->timer.id != TIMER_NONE) {
1778
pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
1779
ssock->timer.id = TIMER_NONE;
1782
reset_ssl_sock_state(ssock);
1783
pj_lock_destroy(ssock->write_mutex);
1788
pj_pool_release(pool);
1795
* Associate arbitrary data with the secure socket.
1797
PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock,
1800
PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
1802
ssock->param.user_data = user_data;
1808
* Retrieve the user data previously associated with this secure
1811
PJ_DEF(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock)
1813
PJ_ASSERT_RETURN(ssock, NULL);
1815
return ssock->param.user_data;
1820
* Retrieve the local address and port used by specified SSL socket.
1822
PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock,
1823
pj_ssl_sock_info *info)
1825
pj_bzero(info, sizeof(*info));
1827
/* Established flag */
1828
info->established = (ssock->ssl_state == SSL_STATE_ESTABLISHED);
1831
info->proto = ssock->param.proto;
1834
pj_sockaddr_cp(&info->local_addr, &ssock->local_addr);
1836
if (info->established) {
1837
const SSL_CIPHER *cipher;
1839
/* Current cipher */
1840
cipher = SSL_get_current_cipher(ssock->ossl_ssl);
1841
info->cipher = (cipher->id & 0x00FFFFFF);
1843
/* Remote address */
1844
pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr);
1846
/* Certificates info */
1847
info->local_cert_info = &ssock->local_cert_info;
1848
info->remote_cert_info = &ssock->remote_cert_info;
1850
/* Verification status */
1851
info->verify_status = ssock->verify_status;
1859
* Starts read operation on this secure socket.
1861
PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock,
1869
PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL);
1870
PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
1872
readbuf = (void**) pj_pool_calloc(pool, ssock->param.async_cnt,
1875
for (i=0; i<ssock->param.async_cnt; ++i) {
1876
readbuf[i] = pj_pool_alloc(pool, buff_size);
1879
return pj_ssl_sock_start_read2(ssock, pool, buff_size,
1885
* Same as #pj_ssl_sock_start_read(), except that the application
1886
* supplies the buffers for the read operation so that the acive socket
1887
* does not have to allocate the buffers.
1889
PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock,
1897
PJ_ASSERT_RETURN(ssock && pool && buff_size && readbuf, PJ_EINVAL);
1898
PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
1900
/* Create SSL socket read buffer */
1901
ssock->ssock_rbuf = (read_data_t*)pj_pool_calloc(pool,
1902
ssock->param.async_cnt,
1903
sizeof(read_data_t));
1905
/* Store SSL socket read buffer pointer in the activesock read buffer */
1906
for (i=0; i<ssock->param.async_cnt; ++i) {
1907
read_data_t **p_ssock_rbuf =
1908
OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]);
1910
ssock->ssock_rbuf[i].data = readbuf[i];
1911
ssock->ssock_rbuf[i].len = 0;
1913
*p_ssock_rbuf = &ssock->ssock_rbuf[i];
1916
ssock->read_size = buff_size;
1917
ssock->read_started = PJ_TRUE;
1918
ssock->read_flags = flags;
1925
* Same as pj_ssl_sock_start_read(), except that this function is used
1926
* only for datagram sockets, and it will trigger \a on_data_recvfrom()
1929
PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock,
1934
PJ_UNUSED_ARG(ssock);
1935
PJ_UNUSED_ARG(pool);
1936
PJ_UNUSED_ARG(buff_size);
1937
PJ_UNUSED_ARG(flags);
1944
* Same as #pj_ssl_sock_start_recvfrom() except that the recvfrom()
1945
* operation takes the buffer from the argument rather than creating
1948
PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock,
1954
PJ_UNUSED_ARG(ssock);
1955
PJ_UNUSED_ARG(pool);
1956
PJ_UNUSED_ARG(buff_size);
1957
PJ_UNUSED_ARG(readbuf);
1958
PJ_UNUSED_ARG(flags);
1963
/* Write plain data to SSL and flush write BIO. Note that accessing
1964
* write BIO must be serialized, so a call to this function must be
1965
* protected by write mutex of SSL socket.
1967
static pj_status_t ssl_write(pj_ssl_sock_t *ssock,
1968
pj_ioqueue_op_key_t *send_key,
1976
/* Write the plain data to SSL, after SSL encrypts it, write BIO will
1977
* contain the secured data to be sent via socket. Note that re-
1978
* negotitation may be on progress, so sending data should be delayed
1979
* until re-negotiation is completed.
1981
nwritten = SSL_write(ssock->ossl_ssl, data, size);
1983
if (nwritten == size) {
1984
/* All data written, flush write BIO to network socket */
1985
status = flush_write_bio(ssock, send_key, size, flags);
1986
} else if (nwritten <= 0) {
1987
/* SSL failed to process the data, it may just that re-negotiation
1991
err = SSL_get_error(ssock->ossl_ssl, nwritten);
1992
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_NONE) {
1993
/* Re-negotiation is on progress, flush re-negotiation data */
1994
status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
1995
if (status == PJ_SUCCESS || status == PJ_EPENDING)
1996
/* Just return PJ_EBUSY when re-negotiation is on progress */
1999
/* Some problem occured */
2000
GET_SSL_STATUS(status);
2003
/* nwritten < *size, shouldn't happen, unless write BIO cannot hold
2004
* the whole secured data, perhaps because of insufficient memory.
2012
/* Flush delayed data sending in the write pending list. Note that accessing
2013
* write pending list must be serialized, so a call to this function must be
2014
* protected by write mutex of SSL socket.
2016
static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock)
2018
while (!pj_list_empty(&ssock->write_pending)) {
2019
write_pending_t *wp;
2022
wp = ssock->write_pending.next;
2024
status = ssl_write(ssock, &wp->data.key, wp->data.data.ptr,
2025
wp->data.plain_data_len, wp->data.flags);
2026
if (status != PJ_SUCCESS)
2030
pj_list_push_back(&ssock->write_pending_empty, wp);
2036
/* Sending is delayed, push back the sending data into pending list. Note that
2037
* accessing write pending list must be serialized, so a call to this function
2038
* must be protected by write mutex of SSL socket.
2040
static pj_status_t delay_send (pj_ssl_sock_t *ssock,
2041
pj_ioqueue_op_key_t *send_key,
2046
write_pending_t *wp;
2048
/* Init write pending instance */
2049
if (!pj_list_empty(&ssock->write_pending_empty)) {
2050
wp = ssock->write_pending_empty.next;
2053
wp = PJ_POOL_ZALLOC_T(ssock->pool, write_pending_t);
2056
wp->data.app_key = send_key;
2057
wp->data.plain_data_len = size;
2058
wp->data.data.ptr = data;
2059
wp->data.flags = flags;
2061
pj_list_push_back(&ssock->write_pending, wp);
2063
/* Must return PJ_EPENDING */
2068
* Send data using the socket.
2070
PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock,
2071
pj_ioqueue_op_key_t *send_key,
2078
PJ_ASSERT_RETURN(ssock && data && size && (*size>0), PJ_EINVAL);
2079
PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2081
pj_lock_acquire(ssock->write_mutex);
2083
/* Flush delayed send first. Sending data might be delayed when
2084
* re-negotiation is on-progress.
2086
status = flush_delayed_send(ssock);
2087
if (status == PJ_EBUSY) {
2088
/* Re-negotiation is on progress, delay sending */
2089
status = delay_send(ssock, send_key, data, *size, flags);
2091
} else if (status != PJ_SUCCESS) {
2095
/* Write data to SSL */
2096
status = ssl_write(ssock, send_key, data, *size, flags);
2097
if (status == PJ_EBUSY) {
2098
/* Re-negotiation is on progress, delay sending */
2099
status = delay_send(ssock, send_key, data, *size, flags);
2103
pj_lock_release(ssock->write_mutex);
2109
* Send datagram using the socket.
2111
PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock,
2112
pj_ioqueue_op_key_t *send_key,
2116
const pj_sockaddr_t *addr,
2119
PJ_UNUSED_ARG(ssock);
2120
PJ_UNUSED_ARG(send_key);
2121
PJ_UNUSED_ARG(data);
2122
PJ_UNUSED_ARG(size);
2123
PJ_UNUSED_ARG(flags);
2124
PJ_UNUSED_ARG(addr);
2125
PJ_UNUSED_ARG(addr_len);
2132
* Starts asynchronous socket accept() operations on this secure socket.
2134
PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock,
2136
const pj_sockaddr_t *localaddr,
2139
pj_activesock_cb asock_cb;
2140
pj_activesock_cfg asock_cfg;
2143
PJ_ASSERT_RETURN(ssock && pool && localaddr && addr_len, PJ_EINVAL);
2146
status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0,
2148
if (status != PJ_SUCCESS)
2151
/* Apply QoS, if specified */
2152
status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
2153
&ssock->param.qos_params, 2,
2154
ssock->pool->obj_name, NULL);
2155
if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
2159
status = pj_sock_bind(ssock->sock, localaddr, addr_len);
2160
if (status != PJ_SUCCESS)
2163
/* Start listening to the address */
2164
status = pj_sock_listen(ssock->sock, PJ_SOMAXCONN);
2165
if (status != PJ_SUCCESS)
2168
/* Create active socket */
2169
pj_activesock_cfg_default(&asock_cfg);
2170
asock_cfg.async_cnt = ssock->param.async_cnt;
2171
asock_cfg.concurrency = ssock->param.concurrency;
2172
asock_cfg.whole_data = PJ_TRUE;
2174
pj_bzero(&asock_cb, sizeof(asock_cb));
2175
asock_cb.on_accept_complete = asock_on_accept_complete;
2177
status = pj_activesock_create(pool,
2179
ssock->param.sock_type,
2181
ssock->param.ioqueue,
2186
if (status != PJ_SUCCESS)
2189
/* Start accepting */
2190
status = pj_activesock_start_accept(ssock->asock, pool);
2191
if (status != PJ_SUCCESS)
2194
/* Update local address */
2195
ssock->addr_len = addr_len;
2196
status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
2198
if (status != PJ_SUCCESS)
2199
pj_sockaddr_cp(&ssock->local_addr, localaddr);
2201
ssock->is_server = PJ_TRUE;
2206
reset_ssl_sock_state(ssock);
2212
* Starts asynchronous socket connect() operation.
2214
PJ_DECL(pj_status_t) pj_ssl_sock_start_connect(pj_ssl_sock_t *ssock,
2216
const pj_sockaddr_t *localaddr,
2217
const pj_sockaddr_t *remaddr,
2220
pj_activesock_cb asock_cb;
2221
pj_activesock_cfg asock_cfg;
2224
PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len,
2228
status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0,
2230
if (status != PJ_SUCCESS)
2233
/* Apply QoS, if specified */
2234
status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
2235
&ssock->param.qos_params, 2,
2236
ssock->pool->obj_name, NULL);
2237
if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
2241
status = pj_sock_bind(ssock->sock, localaddr, addr_len);
2242
if (status != PJ_SUCCESS)
2245
/* Create active socket */
2246
pj_activesock_cfg_default(&asock_cfg);
2247
asock_cfg.async_cnt = ssock->param.async_cnt;
2248
asock_cfg.concurrency = ssock->param.concurrency;
2249
asock_cfg.whole_data = PJ_TRUE;
2251
pj_bzero(&asock_cb, sizeof(asock_cb));
2252
asock_cb.on_connect_complete = asock_on_connect_complete;
2253
asock_cb.on_data_read = asock_on_data_read;
2254
asock_cb.on_data_sent = asock_on_data_sent;
2256
status = pj_activesock_create(pool,
2258
ssock->param.sock_type,
2260
ssock->param.ioqueue,
2265
if (status != PJ_SUCCESS)
2268
/* Save remote address */
2269
pj_sockaddr_cp(&ssock->rem_addr, remaddr);
2272
if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
2273
ssock->param.timeout.msec != 0))
2275
pj_assert(ssock->timer.id == TIMER_NONE);
2276
ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
2277
status = pj_timer_heap_schedule(ssock->param.timer_heap,
2279
&ssock->param.timeout);
2280
if (status != PJ_SUCCESS)
2281
ssock->timer.id = TIMER_NONE;
2284
status = pj_activesock_start_connect(ssock->asock, pool, remaddr,
2287
if (status == PJ_SUCCESS)
2288
asock_on_connect_complete(ssock->asock, PJ_SUCCESS);
2289
else if (status != PJ_EPENDING)
2292
/* Update local address */
2293
ssock->addr_len = addr_len;
2294
status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
2296
/* Note that we may not get an IP address here. This can
2297
* happen for example on Windows, where getsockname()
2298
* would return 0.0.0.0 if socket has just started the
2299
* async connect. In this case, just leave the local
2300
* address with 0.0.0.0 for now; it will be updated
2301
* once the socket is established.
2304
/* Update SSL state */
2305
ssock->is_server = PJ_FALSE;
2310
reset_ssl_sock_state(ssock);
2315
PJ_DEF(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock)
2320
PJ_ASSERT_RETURN(ssock->ssl_state == SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2322
if (SSL_renegotiate_pending(ssock->ossl_ssl))
2325
ret = SSL_renegotiate(ssock->ossl_ssl);
2327
GET_SSL_STATUS(status);
2329
status = do_handshake(ssock);
2335
#endif /* PJ_HAS_SSL_SOCK */