blob: 10ca392af725597950bc402f4659dbd7dea00a09 [file] [log] [blame]
Tristan Matthews0a329cc2013-07-17 13:20:14 -04001/* $Id: ssl_sock_ossl.c 4537 2013-06-19 06:47:43Z riza $ */
2/*
3 * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com)
4 *
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.
9 *
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.
14 *
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
18 */
19#include <pj/ssl_sock.h>
20#include <pj/activesock.h>
21#include <pj/compat/socket.h>
22#include <pj/assert.h>
23#include <pj/errno.h>
24#include <pj/list.h>
25#include <pj/lock.h>
26#include <pj/log.h>
27#include <pj/math.h>
28#include <pj/os.h>
29#include <pj/pool.h>
30#include <pj/string.h>
31#include <pj/timer.h>
32
33
34/* Only build when PJ_HAS_SSL_SOCK is enabled */
35#if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK!=0
36
37#define THIS_FILE "ssl_sock_ossl.c"
38
39/* Workaround for ticket #985 */
40#define DELAYED_CLOSE_TIMEOUT 200
41
42/* Maximum ciphers */
43#define MAX_CIPHERS 100
44
45/*
46 * Include OpenSSL headers
47 */
48#include <openssl/bio.h>
49#include <openssl/ssl.h>
50#include <openssl/err.h>
51#include <openssl/x509v3.h>
52
53
54#ifdef _MSC_VER
55# pragma comment( lib, "libeay32")
56# pragma comment( lib, "ssleay32")
57#endif
58
59
60/*
61 * SSL/TLS state enumeration.
62 */
63enum ssl_state {
64 SSL_STATE_NULL,
65 SSL_STATE_HANDSHAKING,
66 SSL_STATE_ESTABLISHED
67};
68
69/*
70 * Internal timer types.
71 */
72enum timer_id
73{
74 TIMER_NONE,
75 TIMER_HANDSHAKE_TIMEOUT,
76 TIMER_CLOSE
77};
78
79/*
80 * Structure of SSL socket read buffer.
81 */
82typedef struct read_data_t
83{
84 void *data;
85 pj_size_t len;
86} read_data_t;
87
88/*
89 * Get the offset of pointer to read-buffer of SSL socket from read-buffer
90 * of active socket. Note that both SSL socket and active socket employ
91 * different but correlated read-buffers (as much as async_cnt for each),
92 * and to make it easier/faster to find corresponding SSL socket's read-buffer
93 * from known active socket's read-buffer, the pointer of corresponding
94 * SSL socket's read-buffer is stored right after the end of active socket's
95 * read-buffer.
96 */
97#define OFFSET_OF_READ_DATA_PTR(ssock, asock_rbuf) \
98 (read_data_t**) \
99 ((pj_int8_t*)(asock_rbuf) + \
100 ssock->param.read_buffer_size)
101
102/*
103 * Structure of SSL socket write data.
104 */
105typedef struct write_data_t {
106 PJ_DECL_LIST_MEMBER(struct write_data_t);
107 pj_ioqueue_op_key_t key;
108 pj_size_t record_len;
109 pj_ioqueue_op_key_t *app_key;
110 pj_size_t plain_data_len;
111 pj_size_t data_len;
112 unsigned flags;
113 union {
114 char content[1];
115 const char *ptr;
116 } data;
117} write_data_t;
118
119/*
120 * Structure of SSL socket write buffer (circular buffer).
121 */
122typedef struct send_buf_t {
123 char *buf;
124 pj_size_t max_len;
125 char *start;
126 pj_size_t len;
127} send_buf_t;
128
129/*
130 * Secure socket structure definition.
131 */
132struct pj_ssl_sock_t
133{
134 pj_pool_t *pool;
135 pj_ssl_sock_t *parent;
136 pj_ssl_sock_param param;
137 pj_ssl_cert_t *cert;
138
139 pj_ssl_cert_info local_cert_info;
140 pj_ssl_cert_info remote_cert_info;
141
142 pj_bool_t is_server;
143 enum ssl_state ssl_state;
144 pj_ioqueue_op_key_t handshake_op_key;
145 pj_timer_entry timer;
146 pj_status_t verify_status;
147
148 unsigned long last_err;
149
150 pj_sock_t sock;
151 pj_activesock_t *asock;
152
153 pj_sockaddr local_addr;
154 pj_sockaddr rem_addr;
155 int addr_len;
156
157 pj_bool_t read_started;
158 pj_size_t read_size;
159 pj_uint32_t read_flags;
160 void **asock_rbuf;
161 read_data_t *ssock_rbuf;
162
163 write_data_t write_pending;/* list of pending write to OpenSSL */
164 write_data_t write_pending_empty; /* cache for write_pending */
165 pj_bool_t flushing_write_pend; /* flag of flushing is ongoing*/
166 send_buf_t send_buf;
167 write_data_t send_pending; /* list of pending write to network */
168 pj_lock_t *write_mutex; /* protect write BIO and send_buf */
169
170 SSL_CTX *ossl_ctx;
171 SSL *ossl_ssl;
172 BIO *ossl_rbio;
173 BIO *ossl_wbio;
174};
175
176
177/*
178 * Certificate/credential structure definition.
179 */
180struct pj_ssl_cert_t
181{
182 pj_str_t CA_file;
183 pj_str_t cert_file;
184 pj_str_t privkey_file;
185 pj_str_t privkey_pass;
186};
187
188
189static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len);
190static void free_send_data(pj_ssl_sock_t *ssock, write_data_t *wdata);
191static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock);
192
193/*
194 *******************************************************************
195 * Static/internal functions.
196 *******************************************************************
197 */
198
199/**
200 * Mapping from OpenSSL error codes to pjlib error space.
201 */
202
203#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \
204 PJ_ERRNO_SPACE_SIZE*6)
205
206#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE
207
208/* Expected maximum value of reason component in OpenSSL error code */
209#define MAX_OSSL_ERR_REASON 1200
210
211static pj_status_t STATUS_FROM_SSL_ERR(pj_ssl_sock_t *ssock,
212 unsigned long err)
213{
214 pj_status_t status;
215
216 /* General SSL error, dig more from OpenSSL error queue */
217 if (err == SSL_ERROR_SSL)
218 err = ERR_get_error();
219
220 /* OpenSSL error range is much wider than PJLIB errno space, so
221 * if it exceeds the space, only the error reason will be kept.
222 * Note that the last native error will be kept as is and can be
223 * retrieved via SSL socket info.
224 */
225 status = ERR_GET_LIB(err)*MAX_OSSL_ERR_REASON + ERR_GET_REASON(err);
226 if (status > PJ_SSL_ERRNO_SPACE_SIZE)
227 status = ERR_GET_REASON(err);
228
229 status += PJ_SSL_ERRNO_START;
230 ssock->last_err = err;
231 return status;
232}
233
234static pj_status_t GET_SSL_STATUS(pj_ssl_sock_t *ssock)
235{
236 return STATUS_FROM_SSL_ERR(ssock, ERR_get_error());
237}
238
239
240/*
241 * Get error string of OpenSSL.
242 */
243static pj_str_t ssl_strerror(pj_status_t status,
244 char *buf, pj_size_t bufsize)
245{
246 pj_str_t errstr;
247 unsigned long ssl_err = status;
248
249 if (ssl_err) {
250 unsigned long l, r;
251 ssl_err -= PJ_SSL_ERRNO_START;
252 l = ssl_err / MAX_OSSL_ERR_REASON;
253 r = ssl_err % MAX_OSSL_ERR_REASON;
254 ssl_err = ERR_PACK(l, 0, r);
255 }
256
257#if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0)
258
259 {
260 const char *tmp = NULL;
261 tmp = ERR_reason_error_string(ssl_err);
262 if (tmp) {
263 pj_ansi_strncpy(buf, tmp, bufsize);
264 errstr = pj_str(buf);
265 return errstr;
266 }
267 }
268
269#endif /* PJ_HAS_ERROR_STRING */
270
271 errstr.ptr = buf;
272 errstr.slen = pj_ansi_snprintf(buf, bufsize,
273 "Unknown OpenSSL error %lu",
274 ssl_err);
275
276 return errstr;
277}
278
279
280/* OpenSSL library initialization counter */
281static int openssl_init_count;
282
283/* OpenSSL available ciphers */
284static unsigned openssl_cipher_num;
285static struct openssl_ciphers_t {
286 pj_ssl_cipher id;
287 const char *name;
288} openssl_ciphers[MAX_CIPHERS];
289
290/* OpenSSL application data index */
291static int sslsock_idx;
292
293
294/* Initialize OpenSSL */
295static pj_status_t init_openssl(void)
296{
297 pj_status_t status;
298
299 if (openssl_init_count)
300 return PJ_SUCCESS;
301
302 openssl_init_count = 1;
303
304 /* Register error subsystem */
305 status = pj_register_strerror(PJ_SSL_ERRNO_START,
306 PJ_SSL_ERRNO_SPACE_SIZE,
307 &ssl_strerror);
308 pj_assert(status == PJ_SUCCESS);
309
310 /* Init OpenSSL lib */
311 SSL_library_init();
312 SSL_load_error_strings();
313 OpenSSL_add_all_algorithms();
314
315 /* Init available ciphers */
316 if (openssl_cipher_num == 0) {
317 SSL_METHOD *meth = NULL;
318 SSL_CTX *ctx;
319 SSL *ssl;
320 STACK_OF(SSL_CIPHER) *sk_cipher;
321 unsigned i, n;
322
323 meth = (SSL_METHOD*)SSLv23_server_method();
324 if (!meth)
325 meth = (SSL_METHOD*)TLSv1_server_method();
326 if (!meth)
327 meth = (SSL_METHOD*)SSLv3_server_method();
328#ifndef OPENSSL_NO_SSL2
329 if (!meth)
330 meth = (SSL_METHOD*)SSLv2_server_method();
331#endif
332 pj_assert(meth);
333
334 ctx=SSL_CTX_new(meth);
335 SSL_CTX_set_cipher_list(ctx, "ALL");
336
337 ssl = SSL_new(ctx);
338 sk_cipher = SSL_get_ciphers(ssl);
339
340 n = sk_SSL_CIPHER_num(sk_cipher);
341 if (n > PJ_ARRAY_SIZE(openssl_ciphers))
342 n = PJ_ARRAY_SIZE(openssl_ciphers);
343
344 for (i = 0; i < n; ++i) {
345 SSL_CIPHER *c;
346 c = sk_SSL_CIPHER_value(sk_cipher,i);
347 openssl_ciphers[i].id = (pj_ssl_cipher)
348 (pj_uint32_t)c->id & 0x00FFFFFF;
349 openssl_ciphers[i].name = SSL_CIPHER_get_name(c);
350 }
351
352 SSL_free(ssl);
353 SSL_CTX_free(ctx);
354
355 openssl_cipher_num = n;
356 }
357
358 /* Create OpenSSL application data index for SSL socket */
359 sslsock_idx = SSL_get_ex_new_index(0, "SSL socket", NULL, NULL, NULL);
360
361 return PJ_SUCCESS;
362}
363
364
365/* Shutdown OpenSSL */
366static void shutdown_openssl(void)
367{
368 PJ_UNUSED_ARG(openssl_init_count);
369}
370
371
372/* SSL password callback. */
373static int password_cb(char *buf, int num, int rwflag, void *user_data)
374{
375 pj_ssl_cert_t *cert = (pj_ssl_cert_t*) user_data;
376
377 PJ_UNUSED_ARG(rwflag);
378
379 if(num < cert->privkey_pass.slen)
380 return 0;
381
382 pj_memcpy(buf, cert->privkey_pass.ptr, cert->privkey_pass.slen);
383 return (int)cert->privkey_pass.slen;
384}
385
386
387/* SSL password callback. */
388static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
389{
390 pj_ssl_sock_t *ssock;
391 SSL *ossl_ssl;
392 int err;
393
394 /* Get SSL instance */
395 ossl_ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
396 SSL_get_ex_data_X509_STORE_CTX_idx());
397 pj_assert(ossl_ssl);
398
399 /* Get SSL socket instance */
400 ssock = SSL_get_ex_data(ossl_ssl, sslsock_idx);
401 pj_assert(ssock);
402
403 /* Store verification status */
404 err = X509_STORE_CTX_get_error(x509_ctx);
405 switch (err) {
406 case X509_V_OK:
407 break;
408
409 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
410 ssock->verify_status |= PJ_SSL_CERT_EISSUER_NOT_FOUND;
411 break;
412
413 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
414 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
415 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
416 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
417 ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
418 break;
419
420 case X509_V_ERR_CERT_NOT_YET_VALID:
421 case X509_V_ERR_CERT_HAS_EXPIRED:
422 ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
423 break;
424
425 case X509_V_ERR_UNABLE_TO_GET_CRL:
426 case X509_V_ERR_CRL_NOT_YET_VALID:
427 case X509_V_ERR_CRL_HAS_EXPIRED:
428 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
429 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
430 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
431 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
432 ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE;
433 break;
434
435 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
436 case X509_V_ERR_CERT_UNTRUSTED:
437 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
438 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
439 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
440 break;
441
442 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
443 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
444 case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
445 case X509_V_ERR_AKID_SKID_MISMATCH:
446 case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
447 case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
448 ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH;
449 break;
450
451 case X509_V_ERR_CERT_REVOKED:
452 ssock->verify_status |= PJ_SSL_CERT_EREVOKED;
453 break;
454
455 case X509_V_ERR_INVALID_PURPOSE:
456 case X509_V_ERR_CERT_REJECTED:
457 case X509_V_ERR_INVALID_CA:
458 ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE;
459 break;
460
461 case X509_V_ERR_CERT_CHAIN_TOO_LONG: /* not really used */
462 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
463 ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG;
464 break;
465
466 /* Unknown errors */
467 case X509_V_ERR_OUT_OF_MEM:
468 default:
469 ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
470 break;
471 }
472
473 /* When verification is not requested just return ok here, however
474 * application can still get the verification status.
475 */
476 if (PJ_FALSE == ssock->param.verify_peer)
477 preverify_ok = 1;
478
479 return preverify_ok;
480}
481
482/* Setting SSL sock cipher list */
483static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock);
484
485
486/* Create and initialize new SSL context and instance */
487static pj_status_t create_ssl(pj_ssl_sock_t *ssock)
488{
489 SSL_METHOD *ssl_method;
490 SSL_CTX *ctx;
491 pj_ssl_cert_t *cert;
492 int mode, rc;
493 pj_status_t status;
494
495 pj_assert(ssock);
496
497 cert = ssock->cert;
498
499 /* Make sure OpenSSL library has been initialized */
500 init_openssl();
501
502 /* Determine SSL method to use */
503 switch (ssock->param.proto) {
504 case PJ_SSL_SOCK_PROTO_DEFAULT:
505 case PJ_SSL_SOCK_PROTO_TLS1:
506 ssl_method = (SSL_METHOD*)TLSv1_method();
507 break;
508#ifndef OPENSSL_NO_SSL2
509 case PJ_SSL_SOCK_PROTO_SSL2:
510 ssl_method = (SSL_METHOD*)SSLv2_method();
511 break;
512#endif
513 case PJ_SSL_SOCK_PROTO_SSL3:
514 ssl_method = (SSL_METHOD*)SSLv3_method();
515 break;
516 case PJ_SSL_SOCK_PROTO_SSL23:
517 ssl_method = (SSL_METHOD*)SSLv23_method();
518 break;
519 //case PJ_SSL_SOCK_PROTO_DTLS1:
520 //ssl_method = (SSL_METHOD*)DTLSv1_method();
521 //break;
522 default:
523 return PJ_EINVAL;
524 }
525
526 /* Create SSL context */
527 ctx = SSL_CTX_new(ssl_method);
528 if (ctx == NULL) {
529 return GET_SSL_STATUS(ssock);
530 }
531
532 /* Apply credentials */
533 if (cert) {
534 /* Load CA list if one is specified. */
535 if (cert->CA_file.slen) {
536
537 rc = SSL_CTX_load_verify_locations(ctx, cert->CA_file.ptr, NULL);
538
539 if (rc != 1) {
540 status = GET_SSL_STATUS(ssock);
541 PJ_LOG(1,(ssock->pool->obj_name, "Error loading CA list file "
542 "'%s'", cert->CA_file.ptr));
543 SSL_CTX_free(ctx);
544 return status;
545 }
546 }
547
548 /* Set password callback */
549 if (cert->privkey_pass.slen) {
550 SSL_CTX_set_default_passwd_cb(ctx, password_cb);
551 SSL_CTX_set_default_passwd_cb_userdata(ctx, cert);
552 }
553
554
555 /* Load certificate if one is specified */
556 if (cert->cert_file.slen) {
557
558 /* Load certificate chain from file into ctx */
559 rc = SSL_CTX_use_certificate_chain_file(ctx, cert->cert_file.ptr);
560
561 if(rc != 1) {
562 status = GET_SSL_STATUS(ssock);
563 PJ_LOG(1,(ssock->pool->obj_name, "Error loading certificate "
564 "chain file '%s'", cert->cert_file.ptr));
565 SSL_CTX_free(ctx);
566 return status;
567 }
568 }
569
570
571 /* Load private key if one is specified */
572 if (cert->privkey_file.slen) {
573 /* Adds the first private key found in file to ctx */
574 rc = SSL_CTX_use_PrivateKey_file(ctx, cert->privkey_file.ptr,
575 SSL_FILETYPE_PEM);
576
577 if(rc != 1) {
578 status = GET_SSL_STATUS(ssock);
579 PJ_LOG(1,(ssock->pool->obj_name, "Error adding private key "
580 "from '%s'", cert->privkey_file.ptr));
581 SSL_CTX_free(ctx);
582 return status;
583 }
584 }
585 }
586
587 /* Create SSL instance */
588 ssock->ossl_ctx = ctx;
589 ssock->ossl_ssl = SSL_new(ssock->ossl_ctx);
590 if (ssock->ossl_ssl == NULL) {
591 return GET_SSL_STATUS(ssock);
592 }
593
594 /* Set SSL sock as application data of SSL instance */
595 SSL_set_ex_data(ssock->ossl_ssl, sslsock_idx, ssock);
596
597 /* SSL verification options */
598 mode = SSL_VERIFY_PEER;
599 if (ssock->is_server && ssock->param.require_client_cert)
600 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
601
602 SSL_set_verify(ssock->ossl_ssl, mode, &verify_cb);
603
604 /* Set cipher list */
605 status = set_cipher_list(ssock);
606 if (status != PJ_SUCCESS)
607 return status;
608
609 /* Setup SSL BIOs */
610 ssock->ossl_rbio = BIO_new(BIO_s_mem());
611 ssock->ossl_wbio = BIO_new(BIO_s_mem());
612 BIO_set_close(ssock->ossl_rbio, BIO_CLOSE);
613 BIO_set_close(ssock->ossl_wbio, BIO_CLOSE);
614 SSL_set_bio(ssock->ossl_ssl, ssock->ossl_rbio, ssock->ossl_wbio);
615
616 return PJ_SUCCESS;
617}
618
619
620/* Destroy SSL context and instance */
621static void destroy_ssl(pj_ssl_sock_t *ssock)
622{
623 /* Destroy SSL instance */
624 if (ssock->ossl_ssl) {
625 SSL_shutdown(ssock->ossl_ssl);
626 SSL_free(ssock->ossl_ssl); /* this will also close BIOs */
627 ssock->ossl_ssl = NULL;
628 }
629
630 /* Destroy SSL context */
631 if (ssock->ossl_ctx) {
632 SSL_CTX_free(ssock->ossl_ctx);
633 ssock->ossl_ctx = NULL;
634 }
635
636 /* Potentially shutdown OpenSSL library if this is the last
637 * context exists.
638 */
639 shutdown_openssl();
640}
641
642
643/* Reset SSL socket state */
644static void reset_ssl_sock_state(pj_ssl_sock_t *ssock)
645{
646 ssock->ssl_state = SSL_STATE_NULL;
647
648 destroy_ssl(ssock);
649
650 if (ssock->asock) {
651 pj_activesock_close(ssock->asock);
652 ssock->asock = NULL;
653 ssock->sock = PJ_INVALID_SOCKET;
654 }
655 if (ssock->sock != PJ_INVALID_SOCKET) {
656 pj_sock_close(ssock->sock);
657 ssock->sock = PJ_INVALID_SOCKET;
658 }
659
660 /* Upon error, OpenSSL may leave any error description in the thread
661 * error queue, which sometime may cause next call to SSL API returning
662 * false error alarm, e.g: in Linux, SSL_CTX_use_certificate_chain_file()
663 * returning false error after a handshake error (in different SSL_CTX!).
664 * For now, just clear thread error queue here.
665 */
666 ERR_clear_error();
667}
668
669
670/* Generate cipher list with user preference order in OpenSSL format */
671static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock)
672{
673 char buf[1024];
674 pj_str_t cipher_list;
675 STACK_OF(SSL_CIPHER) *sk_cipher;
676 unsigned i;
677 int j, ret;
678
679 if (ssock->param.ciphers_num == 0)
680 return PJ_SUCCESS;
681
682 pj_strset(&cipher_list, buf, 0);
683
684 /* Set SSL with ALL available ciphers */
685 SSL_set_cipher_list(ssock->ossl_ssl, "ALL");
686
687 /* Generate user specified cipher list in OpenSSL format */
688 sk_cipher = SSL_get_ciphers(ssock->ossl_ssl);
689 for (i = 0; i < ssock->param.ciphers_num; ++i) {
690 for (j = 0; j < sk_SSL_CIPHER_num(sk_cipher); ++j) {
691 SSL_CIPHER *c;
692 c = sk_SSL_CIPHER_value(sk_cipher, j);
693 if (ssock->param.ciphers[i] == (pj_ssl_cipher)
694 ((pj_uint32_t)c->id & 0x00FFFFFF))
695 {
696 const char *c_name;
697
698 c_name = SSL_CIPHER_get_name(c);
699
700 /* Check buffer size */
701 if (cipher_list.slen + pj_ansi_strlen(c_name) + 2 > sizeof(buf)) {
702 pj_assert(!"Insufficient temporary buffer for cipher");
703 return PJ_ETOOMANY;
704 }
705
706 /* Add colon separator */
707 if (cipher_list.slen)
708 pj_strcat2(&cipher_list, ":");
709
710 /* Add the cipher */
711 pj_strcat2(&cipher_list, c_name);
712 break;
713 }
714 }
715 }
716
717 /* Put NULL termination in the generated cipher list */
718 cipher_list.ptr[cipher_list.slen] = '\0';
719
720 /* Finally, set chosen cipher list */
721 ret = SSL_set_cipher_list(ssock->ossl_ssl, buf);
722 if (ret < 1) {
723 return GET_SSL_STATUS(ssock);
724 }
725
726 return PJ_SUCCESS;
727}
728
729
730/* Parse OpenSSL ASN1_TIME to pj_time_val and GMT info */
731static pj_bool_t parse_ossl_asn1_time(pj_time_val *tv, pj_bool_t *gmt,
732 const ASN1_TIME *tm)
733{
734 unsigned long parts[7] = {0};
735 char *p, *end;
736 unsigned len;
737 pj_bool_t utc;
738 pj_parsed_time pt;
739 int i;
740
741 utc = tm->type == V_ASN1_UTCTIME;
742 p = (char*)tm->data;
743 len = tm->length;
744 end = p + len - 1;
745
746 /* GMT */
747 *gmt = (*end == 'Z');
748
749 /* parse parts */
750 for (i = 0; i < 7 && p < end; ++i) {
751 pj_str_t st;
752
753 if (i==0 && !utc) {
754 /* 4 digits year part for non-UTC time format */
755 st.slen = 4;
756 } else if (i==6) {
757 /* fraction of seconds */
758 if (*p == '.') ++p;
759 st.slen = end - p + 1;
760 } else {
761 /* other parts always 2 digits length */
762 st.slen = 2;
763 }
764 st.ptr = p;
765
766 parts[i] = pj_strtoul(&st);
767 p += st.slen;
768 }
769
770 /* encode parts to pj_time_val */
771 pt.year = parts[0];
772 if (utc)
773 pt.year += (pt.year < 50)? 2000:1900;
774 pt.mon = parts[1] - 1;
775 pt.day = parts[2];
776 pt.hour = parts[3];
777 pt.min = parts[4];
778 pt.sec = parts[5];
779 pt.msec = parts[6];
780
781 pj_time_encode(&pt, tv);
782
783 return PJ_TRUE;
784}
785
786
787/* Get Common Name field string from a general name string */
788static void get_cn_from_gen_name(const pj_str_t *gen_name, pj_str_t *cn)
789{
790 pj_str_t CN_sign = {"/CN=", 4};
791 char *p, *q;
792
793 pj_bzero(cn, sizeof(cn));
794
795 p = pj_strstr(gen_name, &CN_sign);
796 if (!p)
797 return;
798
799 p += 4; /* shift pointer to value part */
800 pj_strset(cn, p, gen_name->slen - (p - gen_name->ptr));
801 q = pj_strchr(cn, '/');
802 if (q)
803 cn->slen = q - p;
804}
805
806
807/* Get certificate info from OpenSSL X509, in case the certificate info
808 * hal already populated, this function will check if the contents need
809 * to be updated by inspecting the issuer and the serial number.
810 */
811static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, X509 *x)
812{
813 pj_bool_t update_needed;
814 char buf[512];
815 pj_uint8_t serial_no[64] = {0}; /* should be >= sizeof(ci->serial_no) */
816 pj_uint8_t *p;
817 unsigned len;
818 GENERAL_NAMES *names = NULL;
819
820 pj_assert(pool && ci && x);
821
822 /* Get issuer */
823 X509_NAME_oneline(X509_get_issuer_name(x), buf, sizeof(buf));
824
825 /* Get serial no */
826 p = (pj_uint8_t*) M_ASN1_STRING_data(X509_get_serialNumber(x));
827 len = M_ASN1_STRING_length(X509_get_serialNumber(x));
828 if (len > sizeof(ci->serial_no))
829 len = sizeof(ci->serial_no);
830 pj_memcpy(serial_no + sizeof(ci->serial_no) - len, p, len);
831
832 /* Check if the contents need to be updated. */
833 update_needed = pj_strcmp2(&ci->issuer.info, buf) ||
834 pj_memcmp(ci->serial_no, serial_no, sizeof(ci->serial_no));
835 if (!update_needed)
836 return;
837
838 /* Update cert info */
839
840 pj_bzero(ci, sizeof(pj_ssl_cert_info));
841
842 /* Version */
843 ci->version = X509_get_version(x) + 1;
844
845 /* Issuer */
846 pj_strdup2(pool, &ci->issuer.info, buf);
847 get_cn_from_gen_name(&ci->issuer.info, &ci->issuer.cn);
848
849 /* Serial number */
850 pj_memcpy(ci->serial_no, serial_no, sizeof(ci->serial_no));
851
852 /* Subject */
853 pj_strdup2(pool, &ci->subject.info,
854 X509_NAME_oneline(X509_get_subject_name(x),
855 buf, sizeof(buf)));
856 get_cn_from_gen_name(&ci->subject.info, &ci->subject.cn);
857
858 /* Validity */
859 parse_ossl_asn1_time(&ci->validity.start, &ci->validity.gmt,
860 X509_get_notBefore(x));
861 parse_ossl_asn1_time(&ci->validity.end, &ci->validity.gmt,
862 X509_get_notAfter(x));
863
864 /* Subject Alternative Name extension */
865 if (ci->version >= 3) {
866 names = (GENERAL_NAMES*) X509_get_ext_d2i(x, NID_subject_alt_name,
867 NULL, NULL);
868 }
869 if (names) {
870 unsigned i, cnt;
871
872 cnt = sk_GENERAL_NAME_num(names);
873 ci->subj_alt_name.entry = pj_pool_calloc(pool, cnt,
874 sizeof(*ci->subj_alt_name.entry));
875
876 for (i = 0; i < cnt; ++i) {
877 unsigned char *p = 0;
878 pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN;
879 const GENERAL_NAME *name;
880
881 name = sk_GENERAL_NAME_value(names, i);
882
883 switch (name->type) {
884 case GEN_EMAIL:
885 len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
886 type = PJ_SSL_CERT_NAME_RFC822;
887 break;
888 case GEN_DNS:
889 len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
890 type = PJ_SSL_CERT_NAME_DNS;
891 break;
892 case GEN_URI:
893 len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
894 type = PJ_SSL_CERT_NAME_URI;
895 break;
896 case GEN_IPADD:
897 p = ASN1_STRING_data(name->d.ip);
898 len = ASN1_STRING_length(name->d.ip);
899 type = PJ_SSL_CERT_NAME_IP;
900 break;
901 default:
902 break;
903 }
904
905 if (p && len && type != PJ_SSL_CERT_NAME_UNKNOWN) {
906 ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type;
907 if (type == PJ_SSL_CERT_NAME_IP) {
908 int af = pj_AF_INET();
909 if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6();
910 pj_inet_ntop2(af, p, buf, sizeof(buf));
911 pj_strdup2(pool,
912 &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
913 buf);
914 } else {
915 pj_strdup2(pool,
916 &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
917 (char*)p);
918 OPENSSL_free(p);
919 }
920 ci->subj_alt_name.cnt++;
921 }
922 }
923 }
924}
925
926
927/* Update local & remote certificates info. This function should be
928 * called after handshake or renegotiation successfully completed.
929 */
930static void update_certs_info(pj_ssl_sock_t *ssock)
931{
932 X509 *x;
933
934 pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED);
935
936 /* Active local certificate */
937 x = SSL_get_certificate(ssock->ossl_ssl);
938 if (x) {
939 get_cert_info(ssock->pool, &ssock->local_cert_info, x);
940 /* Don't free local's X509! */
941 } else {
942 pj_bzero(&ssock->local_cert_info, sizeof(pj_ssl_cert_info));
943 }
944
945 /* Active remote certificate */
946 x = SSL_get_peer_certificate(ssock->ossl_ssl);
947 if (x) {
948 get_cert_info(ssock->pool, &ssock->remote_cert_info, x);
949 /* Free peer's X509 */
950 X509_free(x);
951 } else {
952 pj_bzero(&ssock->remote_cert_info, sizeof(pj_ssl_cert_info));
953 }
954}
955
956
957/* When handshake completed:
958 * - notify application
959 * - if handshake failed, reset SSL state
960 * - return PJ_FALSE when SSL socket instance is destroyed by application.
961 */
962static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock,
963 pj_status_t status)
964{
965 /* Cancel handshake timer */
966 if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) {
967 pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
968 ssock->timer.id = TIMER_NONE;
969 }
970
971 /* Update certificates info on successful handshake */
972 if (status == PJ_SUCCESS)
973 update_certs_info(ssock);
974
975 /* Accepting */
976 if (ssock->is_server) {
977 if (status != PJ_SUCCESS) {
978 /* Handshake failed in accepting, destroy our self silently. */
979
980 char errmsg[PJ_ERR_MSG_SIZE];
981 char buf[PJ_INET6_ADDRSTRLEN+10];
982
983 pj_strerror(status, errmsg, sizeof(errmsg));
984 PJ_LOG(3,(ssock->pool->obj_name, "Handshake failed in accepting "
985 "%s: %s",
986 pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3),
987 errmsg));
988
989 /* Workaround for ticket #985 */
990#if (defined(PJ_WIN32) && PJ_WIN32!=0) || (defined(PJ_WIN64) && PJ_WIN64!=0)
991 if (ssock->param.timer_heap) {
992 pj_time_val interval = {0, DELAYED_CLOSE_TIMEOUT};
993
994 reset_ssl_sock_state(ssock);
995
996 ssock->timer.id = TIMER_CLOSE;
997 pj_time_val_normalize(&interval);
998 if (pj_timer_heap_schedule(ssock->param.timer_heap,
999 &ssock->timer, &interval) != 0)
1000 {
1001 ssock->timer.id = TIMER_NONE;
1002 pj_ssl_sock_close(ssock);
1003 }
1004 } else
1005#endif /* PJ_WIN32 */
1006 {
1007 pj_ssl_sock_close(ssock);
1008 }
1009 return PJ_FALSE;
1010 }
1011 /* Notify application the newly accepted SSL socket */
1012 if (ssock->param.cb.on_accept_complete) {
1013 pj_bool_t ret;
1014 ret = (*ssock->param.cb.on_accept_complete)
1015 (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,
1016 pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr));
1017 if (ret == PJ_FALSE)
1018 return PJ_FALSE;
1019 }
1020 }
1021
1022 /* Connecting */
1023 else {
1024 /* On failure, reset SSL socket state first, as app may try to
1025 * reconnect in the callback.
1026 */
1027 if (status != PJ_SUCCESS) {
1028 /* Server disconnected us, possibly due to SSL nego failure */
1029 if (status == PJ_EEOF) {
1030 unsigned long err;
1031 err = ERR_get_error();
1032 if (err != SSL_ERROR_NONE)
1033 status = STATUS_FROM_SSL_ERR(ssock, err);
1034 }
1035 reset_ssl_sock_state(ssock);
1036 }
1037 if (ssock->param.cb.on_connect_complete) {
1038 pj_bool_t ret;
1039 ret = (*ssock->param.cb.on_connect_complete)(ssock, status);
1040 if (ret == PJ_FALSE)
1041 return PJ_FALSE;
1042 }
1043 }
1044
1045 return PJ_TRUE;
1046}
1047
1048static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len)
1049{
1050 send_buf_t *send_buf = &ssock->send_buf;
1051 pj_size_t avail_len, skipped_len = 0;
1052 char *reg1, *reg2;
1053 pj_size_t reg1_len, reg2_len;
1054 write_data_t *p;
1055
1056 /* Check buffer availability */
1057 avail_len = send_buf->max_len - send_buf->len;
1058 if (avail_len < len)
1059 return NULL;
1060
1061 /* If buffer empty, reset start pointer and return it */
1062 if (send_buf->len == 0) {
1063 send_buf->start = send_buf->buf;
1064 send_buf->len = len;
1065 p = (write_data_t*)send_buf->start;
1066 goto init_send_data;
1067 }
1068
1069 /* Free space may be wrapped/splitted into two regions, so let's
1070 * analyze them if any region can hold the write data.
1071 */
1072 reg1 = send_buf->start + send_buf->len;
1073 if (reg1 >= send_buf->buf + send_buf->max_len)
1074 reg1 -= send_buf->max_len;
1075 reg1_len = send_buf->max_len - send_buf->len;
1076 if (reg1 + reg1_len > send_buf->buf + send_buf->max_len) {
1077 reg1_len = send_buf->buf + send_buf->max_len - reg1;
1078 reg2 = send_buf->buf;
1079 reg2_len = send_buf->start - send_buf->buf;
1080 } else {
1081 reg2 = NULL;
1082 reg2_len = 0;
1083 }
1084
1085 /* More buffer availability check, note that the write data must be in
1086 * a contigue buffer.
1087 */
1088 avail_len = PJ_MAX(reg1_len, reg2_len);
1089 if (avail_len < len)
1090 return NULL;
1091
1092 /* Get the data slot */
1093 if (reg1_len >= len) {
1094 p = (write_data_t*)reg1;
1095 } else {
1096 p = (write_data_t*)reg2;
1097 skipped_len = reg1_len;
1098 }
1099
1100 /* Update buffer length */
1101 send_buf->len += len + skipped_len;
1102
1103init_send_data:
1104 /* Init the new send data */
1105 pj_bzero(p, sizeof(*p));
1106 pj_list_init(p);
1107 pj_list_push_back(&ssock->send_pending, p);
1108
1109 return p;
1110}
1111
1112static void free_send_data(pj_ssl_sock_t *ssock, write_data_t *wdata)
1113{
1114 send_buf_t *buf = &ssock->send_buf;
1115 write_data_t *spl = &ssock->send_pending;
1116
1117 pj_assert(!pj_list_empty(&ssock->send_pending));
1118
1119 /* Free slot from the buffer */
1120 if (spl->next == wdata && spl->prev == wdata) {
1121 /* This is the only data, reset the buffer */
1122 buf->start = buf->buf;
1123 buf->len = 0;
1124 } else if (spl->next == wdata) {
1125 /* This is the first data, shift start pointer of the buffer and
1126 * adjust the buffer length.
1127 */
1128 buf->start = (char*)wdata->next;
1129 if (wdata->next > wdata) {
1130 buf->len -= ((char*)wdata->next - buf->start);
1131 } else {
1132 /* Overlapped */
1133 pj_size_t right_len, left_len;
1134 right_len = buf->buf + buf->max_len - (char*)wdata;
1135 left_len = (char*)wdata->next - buf->buf;
1136 buf->len -= (right_len + left_len);
1137 }
1138 } else if (spl->prev == wdata) {
1139 /* This is the last data, just adjust the buffer length */
1140 if (wdata->prev < wdata) {
1141 pj_size_t jump_len;
1142 jump_len = (char*)wdata -
1143 ((char*)wdata->prev + wdata->prev->record_len);
1144 buf->len -= (wdata->record_len + jump_len);
1145 } else {
1146 /* Overlapped */
1147 pj_size_t right_len, left_len;
1148 right_len = buf->buf + buf->max_len -
1149 ((char*)wdata->prev + wdata->prev->record_len);
1150 left_len = (char*)wdata + wdata->record_len - buf->buf;
1151 buf->len -= (right_len + left_len);
1152 }
1153 }
1154 /* For data in the middle buffer, just do nothing on the buffer. The slot
1155 * will be freed later when freeing the first/last data.
1156 */
1157
1158 /* Remove the data from send pending list */
1159 pj_list_erase(wdata);
1160}
1161
1162#if 0
1163/* Just for testing send buffer alloc/free */
1164#include <pj/rand.h>
1165pj_status_t pj_ssl_sock_ossl_test_send_buf(pj_pool_t *pool)
1166{
1167 enum { MAX_CHUNK_NUM = 20 };
1168 unsigned chunk_size, chunk_cnt, i;
1169 write_data_t *wdata[MAX_CHUNK_NUM] = {0};
1170 pj_time_val now;
1171 pj_ssl_sock_t *ssock = NULL;
1172 pj_ssl_sock_param param;
1173 pj_status_t status;
1174
1175 pj_gettimeofday(&now);
1176 pj_srand((unsigned)now.sec);
1177
1178 pj_ssl_sock_param_default(&param);
1179 status = pj_ssl_sock_create(pool, &param, &ssock);
1180 if (status != PJ_SUCCESS) {
1181 return status;
1182 }
1183
1184 if (ssock->send_buf.max_len == 0) {
1185 ssock->send_buf.buf = (char*)
1186 pj_pool_alloc(ssock->pool,
1187 ssock->param.send_buffer_size);
1188 ssock->send_buf.max_len = ssock->param.send_buffer_size;
1189 ssock->send_buf.start = ssock->send_buf.buf;
1190 ssock->send_buf.len = 0;
1191 }
1192
1193 chunk_size = ssock->param.send_buffer_size / MAX_CHUNK_NUM / 2;
1194 chunk_cnt = 0;
1195 for (i = 0; i < MAX_CHUNK_NUM; i++) {
1196 wdata[i] = alloc_send_data(ssock, pj_rand() % chunk_size + 321);
1197 if (wdata[i])
1198 chunk_cnt++;
1199 else
1200 break;
1201 }
1202
1203 while (chunk_cnt) {
1204 i = pj_rand() % MAX_CHUNK_NUM;
1205 if (wdata[i]) {
1206 free_send_data(ssock, wdata[i]);
1207 wdata[i] = NULL;
1208 chunk_cnt--;
1209 }
1210 }
1211
1212 if (ssock->send_buf.len != 0)
1213 status = PJ_EBUG;
1214
1215 pj_ssl_sock_close(ssock);
1216 return status;
1217}
1218#endif
1219
1220
1221/* Flush write BIO to network socket. Note that any access to write BIO
1222 * MUST be serialized, so mutex protection must cover any call to OpenSSL
1223 * API (that possibly generate data for write BIO) along with the call to
1224 * this function (flushing all data in write BIO generated by above
1225 * OpenSSL API call).
1226 */
1227static pj_status_t flush_write_bio(pj_ssl_sock_t *ssock,
1228 pj_ioqueue_op_key_t *send_key,
1229 pj_size_t orig_len,
1230 unsigned flags)
1231{
1232 char *data;
1233 pj_ssize_t len;
1234 write_data_t *wdata;
1235 pj_size_t needed_len;
1236 pj_status_t status;
1237
1238 pj_lock_acquire(ssock->write_mutex);
1239
1240 /* Check if there is data in write BIO, flush it if any */
1241 if (!BIO_pending(ssock->ossl_wbio)) {
1242 pj_lock_release(ssock->write_mutex);
1243 return PJ_SUCCESS;
1244 }
1245
1246 /* Get data and its length */
1247 len = BIO_get_mem_data(ssock->ossl_wbio, &data);
1248 if (len == 0) {
1249 pj_lock_release(ssock->write_mutex);
1250 return PJ_SUCCESS;
1251 }
1252
1253 /* Calculate buffer size needed, and align it to 8 */
1254 needed_len = len + sizeof(write_data_t);
1255 needed_len = ((needed_len + 7) >> 3) << 3;
1256
1257 /* Allocate buffer for send data */
1258 wdata = alloc_send_data(ssock, needed_len);
1259 if (wdata == NULL) {
1260 pj_lock_release(ssock->write_mutex);
1261 return PJ_ENOMEM;
1262 }
1263
1264 /* Copy the data and set its properties into the send data */
1265 pj_ioqueue_op_key_init(&wdata->key, sizeof(pj_ioqueue_op_key_t));
1266 wdata->key.user_data = wdata;
1267 wdata->app_key = send_key;
1268 wdata->record_len = needed_len;
1269 wdata->data_len = len;
1270 wdata->plain_data_len = orig_len;
1271 wdata->flags = flags;
1272 pj_memcpy(&wdata->data, data, len);
1273
1274 /* Reset write BIO */
1275 BIO_reset(ssock->ossl_wbio);
1276
1277 /* Ticket #1573: Don't hold mutex while calling PJLIB socket send(). */
1278 pj_lock_release(ssock->write_mutex);
1279
1280 /* Send it */
1281 if (ssock->param.sock_type == pj_SOCK_STREAM()) {
1282 status = pj_activesock_send(ssock->asock, &wdata->key,
1283 wdata->data.content, &len,
1284 flags);
1285 } else {
1286 status = pj_activesock_sendto(ssock->asock, &wdata->key,
1287 wdata->data.content, &len,
1288 flags,
1289 (pj_sockaddr_t*)&ssock->rem_addr,
1290 ssock->addr_len);
1291 }
1292
1293 if (status != PJ_EPENDING) {
1294 /* When the sending is not pending, remove the wdata from send
1295 * pending list.
1296 */
1297 pj_lock_acquire(ssock->write_mutex);
1298 free_send_data(ssock, wdata);
1299 pj_lock_release(ssock->write_mutex);
1300 }
1301
1302 return status;
1303}
1304
1305
1306static void on_timer(pj_timer_heap_t *th, struct pj_timer_entry *te)
1307{
1308 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)te->user_data;
1309 int timer_id = te->id;
1310
1311 te->id = TIMER_NONE;
1312
1313 PJ_UNUSED_ARG(th);
1314
1315 switch (timer_id) {
1316 case TIMER_HANDSHAKE_TIMEOUT:
1317 PJ_LOG(1,(ssock->pool->obj_name, "SSL timeout after %d.%ds",
1318 ssock->param.timeout.sec, ssock->param.timeout.msec));
1319
1320 on_handshake_complete(ssock, PJ_ETIMEDOUT);
1321 break;
1322 case TIMER_CLOSE:
1323 pj_ssl_sock_close(ssock);
1324 break;
1325 default:
1326 pj_assert(!"Unknown timer");
1327 break;
1328 }
1329}
1330
1331
1332/* Asynchronouse handshake */
1333static pj_status_t do_handshake(pj_ssl_sock_t *ssock)
1334{
1335 pj_status_t status;
1336 int err;
1337
1338 /* Perform SSL handshake */
1339 pj_lock_acquire(ssock->write_mutex);
1340 err = SSL_do_handshake(ssock->ossl_ssl);
1341 pj_lock_release(ssock->write_mutex);
1342
1343 /* SSL_do_handshake() may put some pending data into SSL write BIO,
1344 * flush it if any.
1345 */
1346 status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
1347 if (status != PJ_SUCCESS && status != PJ_EPENDING) {
1348 return status;
1349 }
1350
1351 if (err < 0) {
1352 err = SSL_get_error(ssock->ossl_ssl, err);
1353 if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
1354 {
1355 /* Handshake fails */
1356 status = STATUS_FROM_SSL_ERR(ssock, err);
1357 return status;
1358 }
1359 }
1360
1361 /* Check if handshake has been completed */
1362 if (SSL_is_init_finished(ssock->ossl_ssl)) {
1363 ssock->ssl_state = SSL_STATE_ESTABLISHED;
1364 return PJ_SUCCESS;
1365 }
1366
1367 return PJ_EPENDING;
1368}
1369
1370
1371/*
1372 *******************************************************************
1373 * Active socket callbacks.
1374 *******************************************************************
1375 */
1376
1377static pj_bool_t asock_on_data_read (pj_activesock_t *asock,
1378 void *data,
1379 pj_size_t size,
1380 pj_status_t status,
1381 pj_size_t *remainder)
1382{
1383 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1384 pj_activesock_get_user_data(asock);
1385 pj_size_t nwritten;
1386
1387 /* Socket error or closed */
1388 if (data && size > 0) {
1389 /* Consume the whole data */
1390 nwritten = BIO_write(ssock->ossl_rbio, data, (int)size);
1391 if (nwritten < size) {
1392 status = GET_SSL_STATUS(ssock);
1393 goto on_error;
1394 }
1395 }
1396
1397 /* Check if SSL handshake hasn't finished yet */
1398 if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
1399 pj_bool_t ret = PJ_TRUE;
1400
1401 if (status == PJ_SUCCESS)
1402 status = do_handshake(ssock);
1403
1404 /* Not pending is either success or failed */
1405 if (status != PJ_EPENDING)
1406 ret = on_handshake_complete(ssock, status);
1407
1408 return ret;
1409 }
1410
1411 /* See if there is any decrypted data for the application */
1412 if (ssock->read_started) {
1413 do {
1414 read_data_t *buf = *(OFFSET_OF_READ_DATA_PTR(ssock, data));
1415 void *data_ = (pj_int8_t*)buf->data + buf->len;
1416 int size_ = (int)(ssock->read_size - buf->len);
1417
1418 /* SSL_read() may write some data to BIO write when re-negotiation
1419 * is on progress, so let's protect it with write mutex.
1420 */
1421 pj_lock_acquire(ssock->write_mutex);
1422 size_ = SSL_read(ssock->ossl_ssl, data_, size_);
1423 pj_lock_release(ssock->write_mutex);
1424
1425 if (size_ > 0 || status != PJ_SUCCESS) {
1426 if (ssock->param.cb.on_data_read) {
1427 pj_bool_t ret;
1428 pj_size_t remainder_ = 0;
1429
1430 if (size_ > 0)
1431 buf->len += size_;
1432
1433 ret = (*ssock->param.cb.on_data_read)(ssock, buf->data,
1434 buf->len, status,
1435 &remainder_);
1436 if (!ret) {
1437 /* We've been destroyed */
1438 return PJ_FALSE;
1439 }
1440
1441 /* Application may have left some data to be consumed
1442 * later.
1443 */
1444 buf->len = remainder_;
1445 }
1446
1447 /* Active socket signalled connection closed/error, this has
1448 * been signalled to the application along with any remaining
1449 * buffer. So, let's just reset SSL socket now.
1450 */
1451 if (status != PJ_SUCCESS) {
1452 reset_ssl_sock_state(ssock);
1453 return PJ_FALSE;
1454 }
1455
1456 } else {
1457
1458 int err = SSL_get_error(ssock->ossl_ssl, (int)size);
1459
1460 /* SSL might just return SSL_ERROR_WANT_READ in
1461 * re-negotiation.
1462 */
1463 if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
1464 {
1465 /* Reset SSL socket state, then return PJ_FALSE */
1466 status = STATUS_FROM_SSL_ERR(ssock, err);
1467 reset_ssl_sock_state(ssock);
1468 goto on_error;
1469 }
1470
1471 status = do_handshake(ssock);
1472 if (status == PJ_SUCCESS) {
1473 /* Renegotiation completed */
1474
1475 /* Update certificates */
1476 update_certs_info(ssock);
1477
1478 // Ticket #1573: Don't hold mutex while calling
1479 // PJLIB socket send().
1480 //pj_lock_acquire(ssock->write_mutex);
1481 status = flush_delayed_send(ssock);
1482 //pj_lock_release(ssock->write_mutex);
1483
1484 /* If flushing is ongoing, treat it as success */
1485 if (status == PJ_EBUSY)
1486 status = PJ_SUCCESS;
1487
1488 if (status != PJ_SUCCESS && status != PJ_EPENDING) {
1489 PJ_PERROR(1,(ssock->pool->obj_name, status,
1490 "Failed to flush delayed send"));
1491 goto on_error;
1492 }
1493 } else if (status != PJ_EPENDING) {
1494 PJ_PERROR(1,(ssock->pool->obj_name, status,
1495 "Renegotiation failed"));
1496 goto on_error;
1497 }
1498
1499 break;
1500 }
1501 } while (1);
1502 }
1503
1504 return PJ_TRUE;
1505
1506on_error:
1507 if (ssock->ssl_state == SSL_STATE_HANDSHAKING)
1508 return on_handshake_complete(ssock, status);
1509
1510 if (ssock->read_started && ssock->param.cb.on_data_read) {
1511 pj_bool_t ret;
1512 ret = (*ssock->param.cb.on_data_read)(ssock, NULL, 0, status,
1513 remainder);
1514 if (!ret) {
1515 /* We've been destroyed */
1516 return PJ_FALSE;
1517 }
1518 }
1519
1520 reset_ssl_sock_state(ssock);
1521 return PJ_FALSE;
1522}
1523
1524
1525static pj_bool_t asock_on_data_sent (pj_activesock_t *asock,
1526 pj_ioqueue_op_key_t *send_key,
1527 pj_ssize_t sent)
1528{
1529 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1530 pj_activesock_get_user_data(asock);
1531
1532 PJ_UNUSED_ARG(send_key);
1533 PJ_UNUSED_ARG(sent);
1534
1535 if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
1536 /* Initial handshaking */
1537 pj_status_t status;
1538
1539 status = do_handshake(ssock);
1540 /* Not pending is either success or failed */
1541 if (status != PJ_EPENDING)
1542 return on_handshake_complete(ssock, status);
1543
1544 } else if (send_key != &ssock->handshake_op_key) {
1545 /* Some data has been sent, notify application */
1546 write_data_t *wdata = (write_data_t*)send_key->user_data;
1547 if (ssock->param.cb.on_data_sent) {
1548 pj_bool_t ret;
1549 pj_ssize_t sent_len;
1550
1551 sent_len = (sent > 0)? wdata->plain_data_len : sent;
1552 ret = (*ssock->param.cb.on_data_sent)(ssock, wdata->app_key,
1553 sent_len);
1554 if (!ret) {
1555 /* We've been destroyed */
1556 return PJ_FALSE;
1557 }
1558 }
1559
1560 /* Update write buffer state */
1561 pj_lock_acquire(ssock->write_mutex);
1562 free_send_data(ssock, wdata);
1563 pj_lock_release(ssock->write_mutex);
1564
1565 } else {
1566 /* SSL re-negotiation is on-progress, just do nothing */
1567 }
1568
1569 return PJ_TRUE;
1570}
1571
1572
1573static pj_bool_t asock_on_accept_complete (pj_activesock_t *asock,
1574 pj_sock_t newsock,
1575 const pj_sockaddr_t *src_addr,
1576 int src_addr_len)
1577{
1578 pj_ssl_sock_t *ssock_parent = (pj_ssl_sock_t*)
1579 pj_activesock_get_user_data(asock);
1580 pj_ssl_sock_t *ssock;
1581 pj_activesock_cb asock_cb;
1582 pj_activesock_cfg asock_cfg;
1583 unsigned i;
1584 pj_status_t status;
1585
1586 PJ_UNUSED_ARG(src_addr_len);
1587
1588 /* Create new SSL socket instance */
1589 status = pj_ssl_sock_create(ssock_parent->pool, &ssock_parent->param,
1590 &ssock);
1591 if (status != PJ_SUCCESS)
1592 goto on_return;
1593
1594 /* Update new SSL socket attributes */
1595 ssock->sock = newsock;
1596 ssock->parent = ssock_parent;
1597 ssock->is_server = PJ_TRUE;
1598 if (ssock_parent->cert) {
1599 status = pj_ssl_sock_set_certificate(ssock, ssock->pool,
1600 ssock_parent->cert);
1601 if (status != PJ_SUCCESS)
1602 goto on_return;
1603 }
1604
1605 /* Apply QoS, if specified */
1606 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
1607 &ssock->param.qos_params, 1,
1608 ssock->pool->obj_name, NULL);
1609 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
1610 goto on_return;
1611
1612 /* Update local address */
1613 ssock->addr_len = src_addr_len;
1614 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
1615 &ssock->addr_len);
1616 if (status != PJ_SUCCESS) {
1617 /* This fails on few envs, e.g: win IOCP, just tolerate this and
1618 * use parent local address instead.
1619 */
1620 pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);
1621 }
1622
1623 /* Set remote address */
1624 pj_sockaddr_cp(&ssock->rem_addr, src_addr);
1625
1626 /* Create SSL context */
1627 status = create_ssl(ssock);
1628 if (status != PJ_SUCCESS)
1629 goto on_return;
1630
1631 /* Prepare read buffer */
1632 ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool,
1633 ssock->param.async_cnt,
1634 sizeof(void*));
1635 for (i = 0; i<ssock->param.async_cnt; ++i) {
1636 ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
1637 ssock->pool,
1638 ssock->param.read_buffer_size +
1639 sizeof(read_data_t*));
1640 }
1641
1642 /* Create active socket */
1643 pj_activesock_cfg_default(&asock_cfg);
1644 asock_cfg.async_cnt = ssock->param.async_cnt;
1645 asock_cfg.concurrency = ssock->param.concurrency;
1646 asock_cfg.whole_data = PJ_TRUE;
1647
1648 pj_bzero(&asock_cb, sizeof(asock_cb));
1649 asock_cb.on_data_read = asock_on_data_read;
1650 asock_cb.on_data_sent = asock_on_data_sent;
1651
1652 status = pj_activesock_create(ssock->pool,
1653 ssock->sock,
1654 ssock->param.sock_type,
1655 &asock_cfg,
1656 ssock->param.ioqueue,
1657 &asock_cb,
1658 ssock,
1659 &ssock->asock);
1660
1661 if (status != PJ_SUCCESS)
1662 goto on_return;
1663
1664 /* Start read */
1665 status = pj_activesock_start_read2(ssock->asock, ssock->pool,
1666 (unsigned)ssock->param.read_buffer_size,
1667 ssock->asock_rbuf,
1668 PJ_IOQUEUE_ALWAYS_ASYNC);
1669 if (status != PJ_SUCCESS)
1670 goto on_return;
1671
1672 /* Prepare write/send state */
1673 pj_assert(ssock->send_buf.max_len == 0);
1674 ssock->send_buf.buf = (char*)
1675 pj_pool_alloc(ssock->pool,
1676 ssock->param.send_buffer_size);
1677 ssock->send_buf.max_len = ssock->param.send_buffer_size;
1678 ssock->send_buf.start = ssock->send_buf.buf;
1679 ssock->send_buf.len = 0;
1680
1681 /* Start handshake timer */
1682 if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
1683 ssock->param.timeout.msec != 0))
1684 {
1685 pj_assert(ssock->timer.id == TIMER_NONE);
1686 ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
1687 status = pj_timer_heap_schedule(ssock->param.timer_heap,
1688 &ssock->timer,
1689 &ssock->param.timeout);
1690 if (status != PJ_SUCCESS)
1691 ssock->timer.id = TIMER_NONE;
1692 }
1693
1694 /* Start SSL handshake */
1695 ssock->ssl_state = SSL_STATE_HANDSHAKING;
1696 SSL_set_accept_state(ssock->ossl_ssl);
1697 status = do_handshake(ssock);
1698
1699on_return:
1700 if (ssock && status != PJ_EPENDING)
1701 on_handshake_complete(ssock, status);
1702
1703 /* Must return PJ_TRUE whatever happened, as active socket must
1704 * continue listening.
1705 */
1706 return PJ_TRUE;
1707}
1708
1709
1710static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock,
1711 pj_status_t status)
1712{
1713 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1714 pj_activesock_get_user_data(asock);
1715 unsigned i;
1716
1717 if (status != PJ_SUCCESS)
1718 goto on_return;
1719
1720 /* Update local address */
1721 ssock->addr_len = sizeof(pj_sockaddr);
1722 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
1723 &ssock->addr_len);
1724 if (status != PJ_SUCCESS)
1725 goto on_return;
1726
1727 /* Create SSL context */
1728 status = create_ssl(ssock);
1729 if (status != PJ_SUCCESS)
1730 goto on_return;
1731
1732 /* Prepare read buffer */
1733 ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool,
1734 ssock->param.async_cnt,
1735 sizeof(void*));
1736 for (i = 0; i<ssock->param.async_cnt; ++i) {
1737 ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
1738 ssock->pool,
1739 ssock->param.read_buffer_size +
1740 sizeof(read_data_t*));
1741 }
1742
1743 /* Start read */
1744 status = pj_activesock_start_read2(ssock->asock, ssock->pool,
1745 (unsigned)ssock->param.read_buffer_size,
1746 ssock->asock_rbuf,
1747 PJ_IOQUEUE_ALWAYS_ASYNC);
1748 if (status != PJ_SUCCESS)
1749 goto on_return;
1750
1751 /* Prepare write/send state */
1752 pj_assert(ssock->send_buf.max_len == 0);
1753 ssock->send_buf.buf = (char*)
1754 pj_pool_alloc(ssock->pool,
1755 ssock->param.send_buffer_size);
1756 ssock->send_buf.max_len = ssock->param.send_buffer_size;
1757 ssock->send_buf.start = ssock->send_buf.buf;
1758 ssock->send_buf.len = 0;
1759
1760#ifdef SSL_set_tlsext_host_name
1761 /* Set server name to connect */
1762 if (ssock->param.server_name.slen) {
1763 /* Server name is null terminated already */
1764 if (!SSL_set_tlsext_host_name(ssock->ossl_ssl,
1765 ssock->param.server_name.ptr))
1766 {
1767 char err_str[PJ_ERR_MSG_SIZE];
1768
1769 ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
1770 PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() "
1771 "failed: %s", err_str));
1772 }
1773 }
1774#endif
1775
1776 /* Start SSL handshake */
1777 ssock->ssl_state = SSL_STATE_HANDSHAKING;
1778 SSL_set_connect_state(ssock->ossl_ssl);
1779
1780 status = do_handshake(ssock);
1781 if (status != PJ_EPENDING)
1782 goto on_return;
1783
1784 return PJ_TRUE;
1785
1786on_return:
1787 return on_handshake_complete(ssock, status);
1788}
1789
1790
1791
1792/*
1793 *******************************************************************
1794 * API
1795 *******************************************************************
1796 */
1797
1798/* Load credentials from files. */
1799PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files (pj_pool_t *pool,
1800 const pj_str_t *CA_file,
1801 const pj_str_t *cert_file,
1802 const pj_str_t *privkey_file,
1803 const pj_str_t *privkey_pass,
1804 pj_ssl_cert_t **p_cert)
1805{
1806 pj_ssl_cert_t *cert;
1807
1808 PJ_ASSERT_RETURN(pool && CA_file && cert_file && privkey_file, PJ_EINVAL);
1809
1810 cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
1811 pj_strdup_with_null(pool, &cert->CA_file, CA_file);
1812 pj_strdup_with_null(pool, &cert->cert_file, cert_file);
1813 pj_strdup_with_null(pool, &cert->privkey_file, privkey_file);
1814 pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass);
1815
1816 *p_cert = cert;
1817
1818 return PJ_SUCCESS;
1819}
1820
1821
1822/* Set SSL socket credentials. */
1823PJ_DECL(pj_status_t) pj_ssl_sock_set_certificate(
1824 pj_ssl_sock_t *ssock,
1825 pj_pool_t *pool,
1826 const pj_ssl_cert_t *cert)
1827{
1828 pj_ssl_cert_t *cert_;
1829
1830 PJ_ASSERT_RETURN(ssock && pool && cert, PJ_EINVAL);
1831
1832 cert_ = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
1833 pj_memcpy(cert_, cert, sizeof(cert));
1834 pj_strdup_with_null(pool, &cert_->CA_file, &cert->CA_file);
1835 pj_strdup_with_null(pool, &cert_->cert_file, &cert->cert_file);
1836 pj_strdup_with_null(pool, &cert_->privkey_file, &cert->privkey_file);
1837 pj_strdup_with_null(pool, &cert_->privkey_pass, &cert->privkey_pass);
1838
1839 ssock->cert = cert_;
1840
1841 return PJ_SUCCESS;
1842}
1843
1844
1845/* Get available ciphers. */
1846PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[],
1847 unsigned *cipher_num)
1848{
1849 unsigned i;
1850
1851 PJ_ASSERT_RETURN(ciphers && cipher_num, PJ_EINVAL);
1852
1853 if (openssl_cipher_num == 0) {
1854 init_openssl();
1855 shutdown_openssl();
1856 }
1857
1858 if (openssl_cipher_num == 0) {
1859 *cipher_num = 0;
1860 return PJ_ENOTFOUND;
1861 }
1862
1863 *cipher_num = PJ_MIN(*cipher_num, openssl_cipher_num);
1864
1865 for (i = 0; i < *cipher_num; ++i)
1866 ciphers[i] = openssl_ciphers[i].id;
1867
1868 return PJ_SUCCESS;
1869}
1870
1871
1872/* Get cipher name string */
1873PJ_DEF(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher)
1874{
1875 unsigned i;
1876
1877 if (openssl_cipher_num == 0) {
1878 init_openssl();
1879 shutdown_openssl();
1880 }
1881
1882 for (i = 0; i < openssl_cipher_num; ++i) {
1883 if (cipher == openssl_ciphers[i].id)
1884 return openssl_ciphers[i].name;
1885 }
1886
1887 return NULL;
1888}
1889
1890/* Check if the specified cipher is supported by SSL/TLS backend. */
1891PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher)
1892{
1893 unsigned i;
1894
1895 if (openssl_cipher_num == 0) {
1896 init_openssl();
1897 shutdown_openssl();
1898 }
1899
1900 for (i = 0; i < openssl_cipher_num; ++i) {
1901 if (cipher == openssl_ciphers[i].id)
1902 return PJ_TRUE;
1903 }
1904
1905 return PJ_FALSE;
1906}
1907
1908
1909/*
1910 * Create SSL socket instance.
1911 */
1912PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool,
1913 const pj_ssl_sock_param *param,
1914 pj_ssl_sock_t **p_ssock)
1915{
1916 pj_ssl_sock_t *ssock;
1917 pj_status_t status;
1918
1919 PJ_ASSERT_RETURN(pool && param && p_ssock, PJ_EINVAL);
1920 PJ_ASSERT_RETURN(param->sock_type == pj_SOCK_STREAM(), PJ_ENOTSUP);
1921
1922 pool = pj_pool_create(pool->factory, "ssl%p", 512, 512, NULL);
1923
1924 /* Create secure socket */
1925 ssock = PJ_POOL_ZALLOC_T(pool, pj_ssl_sock_t);
1926 ssock->pool = pool;
1927 ssock->sock = PJ_INVALID_SOCKET;
1928 ssock->ssl_state = SSL_STATE_NULL;
1929 pj_list_init(&ssock->write_pending);
1930 pj_list_init(&ssock->write_pending_empty);
1931 pj_list_init(&ssock->send_pending);
1932 pj_timer_entry_init(&ssock->timer, 0, ssock, &on_timer);
1933 pj_ioqueue_op_key_init(&ssock->handshake_op_key,
1934 sizeof(pj_ioqueue_op_key_t));
1935
1936 /* Create secure socket mutex */
1937 status = pj_lock_create_recursive_mutex(pool, pool->obj_name,
1938 &ssock->write_mutex);
1939 if (status != PJ_SUCCESS)
1940 return status;
1941
1942 /* Init secure socket param */
1943 ssock->param = *param;
1944 ssock->param.read_buffer_size = ((ssock->param.read_buffer_size+7)>>3)<<3;
1945 if (param->ciphers_num > 0) {
1946 unsigned i;
1947 ssock->param.ciphers = (pj_ssl_cipher*)
1948 pj_pool_calloc(pool, param->ciphers_num,
1949 sizeof(pj_ssl_cipher));
1950 for (i = 0; i < param->ciphers_num; ++i)
1951 ssock->param.ciphers[i] = param->ciphers[i];
1952 }
1953
1954 /* Server name must be null-terminated */
1955 pj_strdup_with_null(pool, &ssock->param.server_name,
1956 &param->server_name);
1957
1958 /* Finally */
1959 *p_ssock = ssock;
1960
1961 return PJ_SUCCESS;
1962}
1963
1964
1965/*
1966 * Close the secure socket. This will unregister the socket from the
1967 * ioqueue and ultimately close the socket.
1968 */
1969PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock)
1970{
1971 pj_pool_t *pool;
1972
1973 PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
1974
1975 if (!ssock->pool)
1976 return PJ_SUCCESS;
1977
1978 if (ssock->timer.id != TIMER_NONE) {
1979 pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
1980 ssock->timer.id = TIMER_NONE;
1981 }
1982
1983 reset_ssl_sock_state(ssock);
1984 pj_lock_destroy(ssock->write_mutex);
1985
1986 pool = ssock->pool;
1987 ssock->pool = NULL;
1988 if (pool)
1989 pj_pool_release(pool);
1990
1991 return PJ_SUCCESS;
1992}
1993
1994
1995/*
1996 * Associate arbitrary data with the secure socket.
1997 */
1998PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock,
1999 void *user_data)
2000{
2001 PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
2002
2003 ssock->param.user_data = user_data;
2004 return PJ_SUCCESS;
2005}
2006
2007
2008/*
2009 * Retrieve the user data previously associated with this secure
2010 * socket.
2011 */
2012PJ_DEF(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock)
2013{
2014 PJ_ASSERT_RETURN(ssock, NULL);
2015
2016 return ssock->param.user_data;
2017}
2018
2019
2020/*
2021 * Retrieve the local address and port used by specified SSL socket.
2022 */
2023PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock,
2024 pj_ssl_sock_info *info)
2025{
2026 pj_bzero(info, sizeof(*info));
2027
2028 /* Established flag */
2029 info->established = (ssock->ssl_state == SSL_STATE_ESTABLISHED);
2030
2031 /* Protocol */
2032 info->proto = ssock->param.proto;
2033
2034 /* Local address */
2035 pj_sockaddr_cp(&info->local_addr, &ssock->local_addr);
2036
2037 if (info->established) {
2038 const SSL_CIPHER *cipher;
2039
2040 /* Current cipher */
2041 cipher = SSL_get_current_cipher(ssock->ossl_ssl);
2042 info->cipher = (cipher->id & 0x00FFFFFF);
2043
2044 /* Remote address */
2045 pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr);
2046
2047 /* Certificates info */
2048 info->local_cert_info = &ssock->local_cert_info;
2049 info->remote_cert_info = &ssock->remote_cert_info;
2050
2051 /* Verification status */
2052 info->verify_status = ssock->verify_status;
2053 }
2054
2055 /* Last known OpenSSL error code */
2056 info->last_native_err = ssock->last_err;
2057
2058 return PJ_SUCCESS;
2059}
2060
2061
2062/*
2063 * Starts read operation on this secure socket.
2064 */
2065PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock,
2066 pj_pool_t *pool,
2067 unsigned buff_size,
2068 pj_uint32_t flags)
2069{
2070 void **readbuf;
2071 unsigned i;
2072
2073 PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL);
2074 PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2075
2076 readbuf = (void**) pj_pool_calloc(pool, ssock->param.async_cnt,
2077 sizeof(void*));
2078
2079 for (i=0; i<ssock->param.async_cnt; ++i) {
2080 readbuf[i] = pj_pool_alloc(pool, buff_size);
2081 }
2082
2083 return pj_ssl_sock_start_read2(ssock, pool, buff_size,
2084 readbuf, flags);
2085}
2086
2087
2088/*
2089 * Same as #pj_ssl_sock_start_read(), except that the application
2090 * supplies the buffers for the read operation so that the acive socket
2091 * does not have to allocate the buffers.
2092 */
2093PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock,
2094 pj_pool_t *pool,
2095 unsigned buff_size,
2096 void *readbuf[],
2097 pj_uint32_t flags)
2098{
2099 unsigned i;
2100
2101 PJ_ASSERT_RETURN(ssock && pool && buff_size && readbuf, PJ_EINVAL);
2102 PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2103
2104 /* Create SSL socket read buffer */
2105 ssock->ssock_rbuf = (read_data_t*)pj_pool_calloc(pool,
2106 ssock->param.async_cnt,
2107 sizeof(read_data_t));
2108
2109 /* Store SSL socket read buffer pointer in the activesock read buffer */
2110 for (i=0; i<ssock->param.async_cnt; ++i) {
2111 read_data_t **p_ssock_rbuf =
2112 OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]);
2113
2114 ssock->ssock_rbuf[i].data = readbuf[i];
2115 ssock->ssock_rbuf[i].len = 0;
2116
2117 *p_ssock_rbuf = &ssock->ssock_rbuf[i];
2118 }
2119
2120 ssock->read_size = buff_size;
2121 ssock->read_started = PJ_TRUE;
2122 ssock->read_flags = flags;
2123
2124 return PJ_SUCCESS;
2125}
2126
2127
2128/*
2129 * Same as pj_ssl_sock_start_read(), except that this function is used
2130 * only for datagram sockets, and it will trigger \a on_data_recvfrom()
2131 * callback instead.
2132 */
2133PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock,
2134 pj_pool_t *pool,
2135 unsigned buff_size,
2136 pj_uint32_t flags)
2137{
2138 PJ_UNUSED_ARG(ssock);
2139 PJ_UNUSED_ARG(pool);
2140 PJ_UNUSED_ARG(buff_size);
2141 PJ_UNUSED_ARG(flags);
2142
2143 return PJ_ENOTSUP;
2144}
2145
2146
2147/*
2148 * Same as #pj_ssl_sock_start_recvfrom() except that the recvfrom()
2149 * operation takes the buffer from the argument rather than creating
2150 * new ones.
2151 */
2152PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock,
2153 pj_pool_t *pool,
2154 unsigned buff_size,
2155 void *readbuf[],
2156 pj_uint32_t flags)
2157{
2158 PJ_UNUSED_ARG(ssock);
2159 PJ_UNUSED_ARG(pool);
2160 PJ_UNUSED_ARG(buff_size);
2161 PJ_UNUSED_ARG(readbuf);
2162 PJ_UNUSED_ARG(flags);
2163
2164 return PJ_ENOTSUP;
2165}
2166
2167/* Write plain data to SSL and flush write BIO. */
2168static pj_status_t ssl_write(pj_ssl_sock_t *ssock,
2169 pj_ioqueue_op_key_t *send_key,
2170 const void *data,
2171 pj_ssize_t size,
2172 unsigned flags)
2173{
2174 pj_status_t status;
2175 int nwritten;
2176
2177 /* Write the plain data to SSL, after SSL encrypts it, write BIO will
2178 * contain the secured data to be sent via socket. Note that re-
2179 * negotitation may be on progress, so sending data should be delayed
2180 * until re-negotiation is completed.
2181 */
2182 pj_lock_acquire(ssock->write_mutex);
2183 nwritten = SSL_write(ssock->ossl_ssl, data, (int)size);
2184 pj_lock_release(ssock->write_mutex);
2185
2186 if (nwritten == size) {
2187 /* All data written, flush write BIO to network socket */
2188 status = flush_write_bio(ssock, send_key, size, flags);
2189 } else if (nwritten <= 0) {
2190 /* SSL failed to process the data, it may just that re-negotiation
2191 * is on progress.
2192 */
2193 int err;
2194 err = SSL_get_error(ssock->ossl_ssl, nwritten);
2195 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_NONE) {
2196 /* Re-negotiation is on progress, flush re-negotiation data */
2197 status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
2198 if (status == PJ_SUCCESS || status == PJ_EPENDING)
2199 /* Just return PJ_EBUSY when re-negotiation is on progress */
2200 status = PJ_EBUSY;
2201 } else {
2202 /* Some problem occured */
2203 status = STATUS_FROM_SSL_ERR(ssock, err);
2204 }
2205 } else {
2206 /* nwritten < *size, shouldn't happen, unless write BIO cannot hold
2207 * the whole secured data, perhaps because of insufficient memory.
2208 */
2209 status = PJ_ENOMEM;
2210 }
2211
2212 return status;
2213}
2214
2215/* Flush delayed data sending in the write pending list. */
2216static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock)
2217{
2218 /* Check for another ongoing flush */
2219 if (ssock->flushing_write_pend)
2220 return PJ_EBUSY;
2221
2222 pj_lock_acquire(ssock->write_mutex);
2223
2224 /* Again, check for another ongoing flush */
2225 if (ssock->flushing_write_pend) {
2226 pj_lock_release(ssock->write_mutex);
2227 return PJ_EBUSY;
2228 }
2229
2230 /* Set ongoing flush flag */
2231 ssock->flushing_write_pend = PJ_TRUE;
2232
2233 while (!pj_list_empty(&ssock->write_pending)) {
2234 write_data_t *wp;
2235 pj_status_t status;
2236
2237 wp = ssock->write_pending.next;
2238
2239 /* Ticket #1573: Don't hold mutex while calling socket send. */
2240 pj_lock_release(ssock->write_mutex);
2241
2242 status = ssl_write(ssock, &wp->key, wp->data.ptr,
2243 wp->plain_data_len, wp->flags);
2244 if (status != PJ_SUCCESS) {
2245 /* Reset ongoing flush flag first. */
2246 ssock->flushing_write_pend = PJ_FALSE;
2247 return status;
2248 }
2249
2250 pj_lock_acquire(ssock->write_mutex);
2251 pj_list_erase(wp);
2252 pj_list_push_back(&ssock->write_pending_empty, wp);
2253 }
2254
2255 /* Reset ongoing flush flag */
2256 ssock->flushing_write_pend = PJ_FALSE;
2257
2258 pj_lock_release(ssock->write_mutex);
2259
2260 return PJ_SUCCESS;
2261}
2262
2263/* Sending is delayed, push back the sending data into pending list. */
2264static pj_status_t delay_send (pj_ssl_sock_t *ssock,
2265 pj_ioqueue_op_key_t *send_key,
2266 const void *data,
2267 pj_ssize_t size,
2268 unsigned flags)
2269{
2270 write_data_t *wp;
2271
2272 pj_lock_acquire(ssock->write_mutex);
2273
2274 /* Init write pending instance */
2275 if (!pj_list_empty(&ssock->write_pending_empty)) {
2276 wp = ssock->write_pending_empty.next;
2277 pj_list_erase(wp);
2278 } else {
2279 wp = PJ_POOL_ZALLOC_T(ssock->pool, write_data_t);
2280 }
2281
2282 wp->app_key = send_key;
2283 wp->plain_data_len = size;
2284 wp->data.ptr = data;
2285 wp->flags = flags;
2286
2287 pj_list_push_back(&ssock->write_pending, wp);
2288
2289 pj_lock_release(ssock->write_mutex);
2290
2291 /* Must return PJ_EPENDING */
2292 return PJ_EPENDING;
2293}
2294
2295/**
2296 * Send data using the socket.
2297 */
2298PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock,
2299 pj_ioqueue_op_key_t *send_key,
2300 const void *data,
2301 pj_ssize_t *size,
2302 unsigned flags)
2303{
2304 pj_status_t status;
2305
2306 PJ_ASSERT_RETURN(ssock && data && size && (*size>0), PJ_EINVAL);
2307 PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2308
2309 // Ticket #1573: Don't hold mutex while calling PJLIB socket send().
2310 //pj_lock_acquire(ssock->write_mutex);
2311
2312 /* Flush delayed send first. Sending data might be delayed when
2313 * re-negotiation is on-progress.
2314 */
2315 status = flush_delayed_send(ssock);
2316 if (status == PJ_EBUSY) {
2317 /* Re-negotiation or flushing is on progress, delay sending */
2318 status = delay_send(ssock, send_key, data, *size, flags);
2319 goto on_return;
2320 } else if (status != PJ_SUCCESS) {
2321 goto on_return;
2322 }
2323
2324 /* Write data to SSL */
2325 status = ssl_write(ssock, send_key, data, *size, flags);
2326 if (status == PJ_EBUSY) {
2327 /* Re-negotiation is on progress, delay sending */
2328 status = delay_send(ssock, send_key, data, *size, flags);
2329 }
2330
2331on_return:
2332 //pj_lock_release(ssock->write_mutex);
2333 return status;
2334}
2335
2336
2337/**
2338 * Send datagram using the socket.
2339 */
2340PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock,
2341 pj_ioqueue_op_key_t *send_key,
2342 const void *data,
2343 pj_ssize_t *size,
2344 unsigned flags,
2345 const pj_sockaddr_t *addr,
2346 int addr_len)
2347{
2348 PJ_UNUSED_ARG(ssock);
2349 PJ_UNUSED_ARG(send_key);
2350 PJ_UNUSED_ARG(data);
2351 PJ_UNUSED_ARG(size);
2352 PJ_UNUSED_ARG(flags);
2353 PJ_UNUSED_ARG(addr);
2354 PJ_UNUSED_ARG(addr_len);
2355
2356 return PJ_ENOTSUP;
2357}
2358
2359
2360/**
2361 * Starts asynchronous socket accept() operations on this secure socket.
2362 */
2363PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock,
2364 pj_pool_t *pool,
2365 const pj_sockaddr_t *localaddr,
2366 int addr_len)
2367{
2368 pj_activesock_cb asock_cb;
2369 pj_activesock_cfg asock_cfg;
2370 pj_status_t status;
2371
2372 PJ_ASSERT_RETURN(ssock && pool && localaddr && addr_len, PJ_EINVAL);
2373
2374 /* Create socket */
2375 status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0,
2376 &ssock->sock);
2377 if (status != PJ_SUCCESS)
2378 goto on_error;
2379
2380 /* Apply SO_REUSEADDR */
2381 if (ssock->param.reuse_addr) {
2382 int enabled = 1;
2383 status = pj_sock_setsockopt(ssock->sock, pj_SOL_SOCKET(),
2384 pj_SO_REUSEADDR(),
2385 &enabled, sizeof(enabled));
2386 if (status != PJ_SUCCESS) {
2387 PJ_PERROR(4,(ssock->pool->obj_name, status,
2388 "Warning: error applying SO_REUSEADDR"));
2389 }
2390 }
2391
2392 /* Apply QoS, if specified */
2393 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
2394 &ssock->param.qos_params, 2,
2395 ssock->pool->obj_name, NULL);
2396 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
2397 goto on_error;
2398
2399 /* Bind socket */
2400 status = pj_sock_bind(ssock->sock, localaddr, addr_len);
2401 if (status != PJ_SUCCESS)
2402 goto on_error;
2403
2404 /* Start listening to the address */
2405 status = pj_sock_listen(ssock->sock, PJ_SOMAXCONN);
2406 if (status != PJ_SUCCESS)
2407 goto on_error;
2408
2409 /* Create active socket */
2410 pj_activesock_cfg_default(&asock_cfg);
2411 asock_cfg.async_cnt = ssock->param.async_cnt;
2412 asock_cfg.concurrency = ssock->param.concurrency;
2413 asock_cfg.whole_data = PJ_TRUE;
2414
2415 pj_bzero(&asock_cb, sizeof(asock_cb));
2416 asock_cb.on_accept_complete = asock_on_accept_complete;
2417
2418 status = pj_activesock_create(pool,
2419 ssock->sock,
2420 ssock->param.sock_type,
2421 &asock_cfg,
2422 ssock->param.ioqueue,
2423 &asock_cb,
2424 ssock,
2425 &ssock->asock);
2426
2427 if (status != PJ_SUCCESS)
2428 goto on_error;
2429
2430 /* Start accepting */
2431 status = pj_activesock_start_accept(ssock->asock, pool);
2432 if (status != PJ_SUCCESS)
2433 goto on_error;
2434
2435 /* Update local address */
2436 ssock->addr_len = addr_len;
2437 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
2438 &ssock->addr_len);
2439 if (status != PJ_SUCCESS)
2440 pj_sockaddr_cp(&ssock->local_addr, localaddr);
2441
2442 ssock->is_server = PJ_TRUE;
2443
2444 return PJ_SUCCESS;
2445
2446on_error:
2447 reset_ssl_sock_state(ssock);
2448 return status;
2449}
2450
2451
2452/**
2453 * Starts asynchronous socket connect() operation.
2454 */
2455PJ_DECL(pj_status_t) pj_ssl_sock_start_connect(pj_ssl_sock_t *ssock,
2456 pj_pool_t *pool,
2457 const pj_sockaddr_t *localaddr,
2458 const pj_sockaddr_t *remaddr,
2459 int addr_len)
2460{
2461 pj_activesock_cb asock_cb;
2462 pj_activesock_cfg asock_cfg;
2463 pj_status_t status;
2464
2465 PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len,
2466 PJ_EINVAL);
2467
2468 /* Create socket */
2469 status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0,
2470 &ssock->sock);
2471 if (status != PJ_SUCCESS)
2472 goto on_error;
2473
2474 /* Apply QoS, if specified */
2475 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
2476 &ssock->param.qos_params, 2,
2477 ssock->pool->obj_name, NULL);
2478 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
2479 goto on_error;
2480
2481 /* Bind socket */
2482 status = pj_sock_bind(ssock->sock, localaddr, addr_len);
2483 if (status != PJ_SUCCESS)
2484 goto on_error;
2485
2486 /* Create active socket */
2487 pj_activesock_cfg_default(&asock_cfg);
2488 asock_cfg.async_cnt = ssock->param.async_cnt;
2489 asock_cfg.concurrency = ssock->param.concurrency;
2490 asock_cfg.whole_data = PJ_TRUE;
2491
2492 pj_bzero(&asock_cb, sizeof(asock_cb));
2493 asock_cb.on_connect_complete = asock_on_connect_complete;
2494 asock_cb.on_data_read = asock_on_data_read;
2495 asock_cb.on_data_sent = asock_on_data_sent;
2496
2497 status = pj_activesock_create(pool,
2498 ssock->sock,
2499 ssock->param.sock_type,
2500 &asock_cfg,
2501 ssock->param.ioqueue,
2502 &asock_cb,
2503 ssock,
2504 &ssock->asock);
2505
2506 if (status != PJ_SUCCESS)
2507 goto on_error;
2508
2509 /* Save remote address */
2510 pj_sockaddr_cp(&ssock->rem_addr, remaddr);
2511
2512 /* Start timer */
2513 if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
2514 ssock->param.timeout.msec != 0))
2515 {
2516 pj_assert(ssock->timer.id == TIMER_NONE);
2517 ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
2518 status = pj_timer_heap_schedule(ssock->param.timer_heap,
2519 &ssock->timer,
2520 &ssock->param.timeout);
2521 if (status != PJ_SUCCESS)
2522 ssock->timer.id = TIMER_NONE;
2523 }
2524
2525 status = pj_activesock_start_connect(ssock->asock, pool, remaddr,
2526 addr_len);
2527
2528 if (status == PJ_SUCCESS)
2529 asock_on_connect_complete(ssock->asock, PJ_SUCCESS);
2530 else if (status != PJ_EPENDING)
2531 goto on_error;
2532
2533 /* Update local address */
2534 ssock->addr_len = addr_len;
2535 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
2536 &ssock->addr_len);
2537 /* Note that we may not get an IP address here. This can
2538 * happen for example on Windows, where getsockname()
2539 * would return 0.0.0.0 if socket has just started the
2540 * async connect. In this case, just leave the local
2541 * address with 0.0.0.0 for now; it will be updated
2542 * once the socket is established.
2543 */
2544
2545 /* Update SSL state */
2546 ssock->is_server = PJ_FALSE;
2547
2548 return PJ_EPENDING;
2549
2550on_error:
2551 reset_ssl_sock_state(ssock);
2552 return status;
2553}
2554
2555
2556PJ_DEF(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock)
2557{
2558 int ret;
2559 pj_status_t status;
2560
2561 PJ_ASSERT_RETURN(ssock->ssl_state == SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2562
2563 if (SSL_renegotiate_pending(ssock->ossl_ssl))
2564 return PJ_EPENDING;
2565
2566 ret = SSL_renegotiate(ssock->ossl_ssl);
2567 if (ret <= 0) {
2568 status = GET_SSL_STATUS(ssock);
2569 } else {
2570 status = do_handshake(ssock);
2571 }
2572
2573 return status;
2574}
2575
2576#endif /* PJ_HAS_SSL_SOCK */
2577