Changeset 5938
- Timestamp:
- Mar 4, 2019 9:47:25 AM (6 years ago)
- Location:
- pjproject/trunk/pjlib
- Files:
-
- 2 added
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
pjproject/trunk/pjlib/include/pj/ssl_sock.h
r5885 r5938 706 706 */ 707 707 PJ_SSL_SOCK_PROTO_SSL23 = (1 << 16) - 1, 708 PJ_SSL_SOCK_PROTO_ALL = PJ_SSL_SOCK_PROTO_SSL23, 708 709 709 710 /** -
pjproject/trunk/pjlib/src/pj/ssl_sock_gtls.c
r5929 r5938 45 45 (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_GNUTLS) 46 46 47 #define SSL_SOCK_IMP_USE_CIRC_BUF 48 49 #include "ssl_sock_imp_common.h" 50 #include "ssl_sock_imp_common.c" 51 47 52 #define THIS_FILE "ssl_sock_gtls.c" 48 49 /* Workaround for ticket #985 */50 #define DELAYED_CLOSE_TIMEOUT 20051 53 52 54 /* Maximum ciphers */ … … 70 72 71 73 72 /* TLS state enumeration. */73 enum tls_connection_state {74 TLS_STATE_NULL,75 TLS_STATE_HANDSHAKING,76 TLS_STATE_ESTABLISHED77 };78 79 /* Internal timer types. */80 enum timer_id {81 TIMER_NONE,82 TIMER_HANDSHAKE_TIMEOUT,83 TIMER_CLOSE84 };85 86 /* Structure of SSL socket read buffer. */87 typedef struct read_data_t {88 void *data;89 pj_size_t len;90 } read_data_t;91 92 /*93 * Get the offset of pointer to read-buffer of SSL socket from read-buffer94 * of active socket. Note that both SSL socket and active socket employ95 * different but correlated read-buffers (as much as async_cnt for each),96 * and to make it easier/faster to find corresponding SSL socket's read-buffer97 * from known active socket's read-buffer, the pointer of corresponding98 * SSL socket's read-buffer is stored right after the end of active socket's99 * read-buffer.100 */101 #define OFFSET_OF_READ_DATA_PTR(ssock, asock_rbuf) \102 (read_data_t**) \103 ((pj_int8_t *)(asock_rbuf) + \104 ssock->param.read_buffer_size)105 106 /* Structure of SSL socket write data. */107 typedef struct write_data_t {108 PJ_DECL_LIST_MEMBER(struct write_data_t);109 pj_ioqueue_op_key_t key;110 pj_size_t record_len;111 pj_ioqueue_op_key_t *app_key;112 pj_size_t plain_data_len;113 pj_size_t data_len;114 unsigned flags;115 union {116 char content[1];117 const char *ptr;118 } data;119 } write_data_t;120 121 122 /* Structure of SSL socket write buffer (circular buffer). */123 typedef struct send_buf_t {124 char *buf;125 pj_size_t max_len;126 char *start;127 pj_size_t len;128 } send_buf_t;129 130 131 /* Circular buffer object */132 typedef struct circ_buf_t {133 pj_size_t cap; /* maximum number of elements (must be power of 2) */134 pj_size_t readp; /* index of oldest element */135 pj_size_t writep; /* index at which to write new element */136 pj_size_t size; /* number of elements */137 pj_uint8_t *buf; /* data buffer */138 pj_pool_t *pool; /* where new allocations will take place */139 } circ_buf_t;140 141 142 74 /* Secure socket structure definition. */ 143 struct pj_ssl_sock_t { 144 pj_pool_t *pool; 145 pj_ssl_sock_t *parent; 146 pj_ssl_sock_param param; 147 pj_ssl_sock_param newsock_param; 148 pj_ssl_cert_t *cert; 149 150 pj_ssl_cert_info local_cert_info; 151 pj_ssl_cert_info remote_cert_info; 152 153 pj_bool_t is_server; 154 enum tls_connection_state connection_state; 155 pj_ioqueue_op_key_t handshake_op_key; 156 pj_timer_entry timer; 157 pj_status_t verify_status; 158 159 int last_err; 160 161 pj_sock_t sock; 162 pj_activesock_t *asock; 163 164 pj_sockaddr local_addr; 165 pj_sockaddr rem_addr; 166 int addr_len; 167 168 pj_bool_t read_started; 169 pj_size_t read_size; 170 pj_uint32_t read_flags; 171 void **asock_rbuf; 172 read_data_t *ssock_rbuf; 173 174 write_data_t write_pending; /* list of pending writes */ 175 write_data_t write_pending_empty; /* cache for write_pending */ 176 pj_bool_t flushing_write_pend; /* flag of flushing is ongoing */ 177 send_buf_t send_buf; 178 write_data_t send_pending; /* list of pending write to network */ 75 typedef struct gnutls_sock_t { 76 pj_ssl_sock_t base; 179 77 180 78 gnutls_session_t session; 181 79 gnutls_certificate_credentials_t xcred; 182 80 183 circ_buf_t circ_buf_input;184 pj_lock_t *circ_buf_input_mutex;185 186 circ_buf_t circ_buf_output;187 pj_lock_t *circ_buf_output_mutex;188 189 81 int tls_init_count; /* library initialization counter */ 190 }; 191 192 /* 193 * Certificate/credential structure definition. 194 */ 195 struct pj_ssl_cert_t 196 { 197 pj_str_t CA_file; 198 pj_str_t CA_path; 199 pj_str_t cert_file; 200 pj_str_t privkey_file; 201 pj_str_t privkey_pass; 202 203 /* Certificate buffer. */ 204 pj_ssl_cert_buffer CA_buf; 205 pj_ssl_cert_buffer cert_buf; 206 pj_ssl_cert_buffer privkey_buf; 207 }; 208 209 210 /* GnuTLS available ciphers */ 211 static unsigned tls_available_ciphers; 212 213 /* Array of id/names for available ciphers */ 214 static struct tls_ciphers_t { 215 pj_ssl_cipher id; 216 const char *name; 217 } tls_ciphers[MAX_CIPHERS]; 82 } gnutls_sock_t; 218 83 219 84 /* Last error reported somehow */ 220 85 static int tls_last_error; 221 222 223 /*224 *******************************************************************225 * Circular buffer functions.226 *******************************************************************227 */228 229 static pj_status_t circ_init(pj_pool_factory *factory,230 circ_buf_t *cb, pj_size_t cap)231 {232 cb->cap = cap;233 cb->readp = 0;234 cb->writep = 0;235 cb->size = 0;236 237 /* Initial pool holding the buffer elements */238 cb->pool = pj_pool_create(factory, "tls-circ%p", cap, cap, NULL);239 if (!cb->pool)240 return PJ_ENOMEM;241 242 /* Allocate circular buffer */243 cb->buf = pj_pool_alloc(cb->pool, cap);244 if (!cb->buf) {245 pj_pool_release(cb->pool);246 return PJ_ENOMEM;247 }248 249 return PJ_SUCCESS;250 }251 252 static void circ_deinit(circ_buf_t *cb)253 {254 if (cb->pool) {255 pj_pool_release(cb->pool);256 cb->pool = NULL;257 }258 }259 260 static pj_bool_t circ_empty(const circ_buf_t *cb)261 {262 return cb->size == 0;263 }264 265 static pj_size_t circ_size(const circ_buf_t *cb)266 {267 return cb->size;268 }269 270 static pj_size_t circ_avail(const circ_buf_t *cb)271 {272 return cb->cap - cb->size;273 }274 275 static void circ_read(circ_buf_t *cb, pj_uint8_t *dst, pj_size_t len)276 {277 pj_size_t size_after = cb->cap - cb->readp;278 pj_size_t tbc = PJ_MIN(size_after, len);279 pj_size_t rem = len - tbc;280 281 pj_memcpy(dst, cb->buf + cb->readp, tbc);282 pj_memcpy(dst + tbc, cb->buf, rem);283 284 cb->readp += len;285 cb->readp &= (cb->cap - 1);286 287 cb->size -= len;288 }289 290 static pj_status_t circ_write(circ_buf_t *cb,291 const pj_uint8_t *src, pj_size_t len)292 {293 /* Overflow condition: resize */294 if (len > circ_avail(cb)) {295 /* Minimum required capacity */296 pj_size_t min_cap = len + cb->size;297 298 /* Next 32-bit power of two */299 min_cap--;300 min_cap |= min_cap >> 1;301 min_cap |= min_cap >> 2;302 min_cap |= min_cap >> 4;303 min_cap |= min_cap >> 8;304 min_cap |= min_cap >> 16;305 min_cap++;306 307 /* Create a new pool to hold a bigger buffer, using the same factory */308 pj_pool_t *pool = pj_pool_create(cb->pool->factory, "tls-circ%p",309 min_cap, min_cap, NULL);310 if (!pool)311 return PJ_ENOMEM;312 313 /* Allocate our new buffer */314 pj_uint8_t *buf = pj_pool_alloc(pool, min_cap);315 if (!buf) {316 pj_pool_release(pool);317 return PJ_ENOMEM;318 }319 320 /* Save old size, which we shall restore after the next read */321 pj_size_t old_size = cb->size;322 323 /* Copy old data into beginning of new buffer */324 circ_read(cb, buf, cb->size);325 326 /* Restore old size now */327 cb->size = old_size;328 329 /* Release the previous pool */330 pj_pool_release(cb->pool);331 332 /* Update circular buffer members */333 cb->pool = pool;334 cb->buf = buf;335 cb->readp = 0;336 cb->writep = cb->size;337 cb->cap = min_cap;338 }339 340 pj_size_t size_after = cb->cap - cb->writep;341 pj_size_t tbc = PJ_MIN(size_after, len);342 pj_size_t rem = len - tbc;343 344 pj_memcpy(cb->buf + cb->writep, src, tbc);345 pj_memcpy(cb->buf, src + tbc, rem);346 347 cb->writep += len;348 cb->writep &= (cb->cap - 1);349 350 cb->size += len;351 352 return PJ_SUCCESS;353 }354 86 355 87 … … 491 223 492 224 /* Init available ciphers */ 493 if (! tls_available_ciphers) {225 if (!ssl_cipher_num) { 494 226 unsigned int i; 495 227 496 for (i = 0; i<PJ_ARRAY_SIZE( tls_ciphers); i++) {228 for (i = 0; i<PJ_ARRAY_SIZE(ssl_ciphers); i++) { 497 229 unsigned char id[2]; 498 230 const char *suite; … … 500 232 suite = gnutls_cipher_suite_info(i, (unsigned char *)id, 501 233 NULL, NULL, NULL, NULL); 502 tls_ciphers[i].id = 0;234 ssl_ciphers[i].id = 0; 503 235 /* usually the array size is bigger than the number of available 504 236 * ciphers anyway, so by checking here we can exit the loop as soon 505 237 * as either all ciphers have been added or the array is full */ 506 238 if (suite) { 507 tls_ciphers[i].id = (pj_ssl_cipher)239 ssl_ciphers[i].id = (pj_ssl_cipher) 508 240 (pj_uint32_t) ((id[0] << 8) | id[1]); 509 tls_ciphers[i].name = suite;241 ssl_ciphers[i].name = suite; 510 242 } else 511 243 break; 512 244 } 513 245 514 tls_available_ciphers= i;246 ssl_cipher_num = i; 515 247 } 516 248 … … 623 355 { 624 356 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)ptr; 357 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 625 358 626 359 pj_lock_acquire(ssock->circ_buf_output_mutex); … … 628 361 pj_lock_release(ssock->circ_buf_output_mutex); 629 362 630 gnutls_transport_set_errno( ssock->session, ENOMEM);363 gnutls_transport_set_errno(gssock->session, ENOMEM); 631 364 return -1; 632 365 } … … 644 377 { 645 378 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)ptr; 379 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 646 380 647 381 pj_lock_acquire(ssock->circ_buf_input_mutex); … … 651 385 652 386 /* Data buffers not yet filled */ 653 gnutls_transport_set_errno( ssock->session, EAGAIN);387 gnutls_transport_set_errno(gssock->session, EAGAIN); 654 388 return -1; 655 389 } … … 684 418 static pj_status_t tls_priorities_set(pj_ssl_sock_t *ssock) 685 419 { 420 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 686 421 char buf[1024]; 687 422 char priority_buf[256]; … … 783 518 784 519 /* Set our priority string */ 785 ret = gnutls_priority_set_direct( ssock->session,520 ret = gnutls_priority_set_direct(gssock->session, 786 521 cipher_list.ptr, &err); 787 522 if (ret < 0) { … … 797 532 static pj_status_t tls_trust_set(pj_ssl_sock_t *ssock) 798 533 { 534 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 799 535 int ntrusts = 0; 800 536 int err; 801 537 802 err = gnutls_certificate_set_x509_system_trust( ssock->xcred);538 err = gnutls_certificate_set_x509_system_trust(gssock->xcred); 803 539 if (err > 0) 804 540 ntrusts += err; 805 err = gnutls_certificate_set_x509_trust_file( ssock->xcred,541 err = gnutls_certificate_set_x509_trust_file(gssock->xcred, 806 542 TRUST_STORE_FILE1, 807 543 GNUTLS_X509_FMT_PEM); … … 809 545 ntrusts += err; 810 546 811 err = gnutls_certificate_set_x509_trust_file( ssock->xcred,547 err = gnutls_certificate_set_x509_trust_file(gssock->xcred, 812 548 TRUST_STORE_FILE2, 813 549 GNUTLS_X509_FMT_PEM); … … 875 611 #endif 876 612 613 static pj_ssl_sock_t *ssl_alloc(pj_pool_t *pool) 614 { 615 return (pj_ssl_sock_t *)PJ_POOL_ZALLOC_T(pool, gnutls_sock_t); 616 } 617 877 618 /* Create and initialize new GnuTLS context and instance */ 878 static pj_status_t tls_open(pj_ssl_sock_t *ssock) 879 { 619 static pj_status_t ssl_create(pj_ssl_sock_t *ssock) 620 { 621 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 880 622 pj_ssl_cert_t *cert; 881 623 pj_status_t status; … … 888 630 /* Even if reopening is harmless, having one instance only simplifies 889 631 * deallocating it later on */ 890 if (! ssock->tls_init_count) {891 ssock->tls_init_count++;632 if (!gssock->tls_init_count) { 633 gssock->tls_init_count++; 892 634 ret = tls_init(); 893 635 if (ret < 0) … … 897 639 898 640 /* Start this socket session */ 899 ret = gnutls_init(& ssock->session, ssock->is_server ? GNUTLS_SERVER641 ret = gnutls_init(&gssock->session, ssock->is_server ? GNUTLS_SERVER 900 642 : GNUTLS_CLIENT); 901 643 if (ret < 0) … … 904 646 /* Set the ssock object to be retrieved by transport (send/recv) and by 905 647 * user data from this session */ 906 gnutls_transport_set_ptr( ssock->session,648 gnutls_transport_set_ptr(gssock->session, 907 649 (gnutls_transport_ptr_t) (uintptr_t) ssock); 908 gnutls_session_set_ptr( ssock->session,650 gnutls_session_set_ptr(gssock->session, 909 651 (gnutls_transport_ptr_t) (uintptr_t) ssock); 910 652 … … 921 663 /* Set the callback that allows GnuTLS to PUSH and PULL data 922 664 * TO and FROM the transport layer */ 923 gnutls_transport_set_push_function( ssock->session, tls_data_push);924 gnutls_transport_set_pull_function( ssock->session, tls_data_pull);665 gnutls_transport_set_push_function(gssock->session, tls_data_push); 666 gnutls_transport_set_pull_function(gssock->session, tls_data_pull); 925 667 926 668 /* Determine which cipher suite to support */ … … 930 672 931 673 /* Allocate credentials for handshaking and transmission */ 932 ret = gnutls_certificate_allocate_credentials(& ssock->xcred);674 ret = gnutls_certificate_allocate_credentials(&gssock->xcred); 933 675 if (ret < 0) 934 676 goto out; 935 gnutls_certificate_set_verify_function( ssock->xcred, tls_cert_verify_cb);677 gnutls_certificate_set_verify_function(gssock->xcred, tls_cert_verify_cb); 936 678 937 679 /* Load system trust file(s) */ … … 944 686 /* Load CA if one is specified. */ 945 687 if (cert->CA_file.slen) { 946 ret = gnutls_certificate_set_x509_trust_file( ssock->xcred,688 ret = gnutls_certificate_set_x509_trust_file(gssock->xcred, 947 689 cert->CA_file.ptr, 948 690 GNUTLS_X509_FMT_PEM); 949 691 if (ret < 0) 950 692 ret = gnutls_certificate_set_x509_trust_file( 951 ssock->xcred,693 gssock->xcred, 952 694 cert->CA_file.ptr, 953 695 GNUTLS_X509_FMT_DER); … … 956 698 } 957 699 if (cert->CA_path.slen) { 958 ret = gnutls_certificate_set_x509_trust_dir( ssock->xcred,700 ret = gnutls_certificate_set_x509_trust_dir(gssock->xcred, 959 701 cert->CA_path.ptr, 960 702 GNUTLS_X509_FMT_PEM); 961 703 if (ret < 0) 962 704 ret = gnutls_certificate_set_x509_trust_dir( 963 ssock->xcred,705 gssock->xcred, 964 706 cert->CA_path.ptr, 965 707 GNUTLS_X509_FMT_DER); … … 974 716 ? cert->privkey_pass.ptr 975 717 : NULL; 976 ret = gnutls_certificate_set_x509_key_file2( ssock->xcred,718 ret = gnutls_certificate_set_x509_key_file2(gssock->xcred, 977 719 cert->cert_file.ptr, 978 720 prikey_file, … … 981 723 0); 982 724 if (ret != GNUTLS_E_SUCCESS) 983 ret = gnutls_certificate_set_x509_key_file2( ssock->xcred,725 ret = gnutls_certificate_set_x509_key_file2(gssock->xcred, 984 726 cert->cert_file.ptr, 985 727 prikey_file, … … 995 737 ca.data = (unsigned char*)cert->CA_buf.ptr; 996 738 ca.size = cert->CA_buf.slen; 997 ret = gnutls_certificate_set_x509_trust_mem( ssock->xcred,739 ret = gnutls_certificate_set_x509_trust_mem(gssock->xcred, 998 740 &ca, 999 741 GNUTLS_X509_FMT_PEM); 1000 742 if (ret < 0) 1001 743 ret = gnutls_certificate_set_x509_trust_mem( 1002 ssock->xcred, &ca, GNUTLS_X509_FMT_DER);744 gssock->xcred, &ca, GNUTLS_X509_FMT_DER); 1003 745 if (ret < 0) 1004 746 goto out; … … 1017 759 ? cert->privkey_pass.ptr 1018 760 : NULL; 1019 ret = gnutls_certificate_set_x509_key_mem2( ssock->xcred,761 ret = gnutls_certificate_set_x509_key_mem2(gssock->xcred, 1020 762 &cert_buf, 1021 763 &privkey_buf, … … 1026 768 /* 1027 769 if (ret != GNUTLS_E_SUCCESS) 1028 ret = gnutls_certificate_set_x509_key_mem2( ssock->xcred,770 ret = gnutls_certificate_set_x509_key_mem2(gssock->xcred, 1029 771 &cert_buf, 1030 772 &privkey_buf, … … 1040 782 /* Require client certificate if asked */ 1041 783 if (ssock->is_server && ssock->param.require_client_cert) 1042 gnutls_certificate_server_set_request( ssock->session,784 gnutls_certificate_server_set_request(gssock->session, 1043 785 GNUTLS_CERT_REQUIRE); 1044 786 1045 787 /* Finally set credentials for this session */ 1046 ret = gnutls_credentials_set( ssock->session,1047 GNUTLS_CRD_CERTIFICATE, ssock->xcred);788 ret = gnutls_credentials_set(gssock->session, 789 GNUTLS_CRD_CERTIFICATE, gssock->xcred); 1048 790 if (ret < 0) 1049 791 goto out; … … 1056 798 1057 799 /* Destroy GnuTLS credentials and session. */ 1058 static void tls_close(pj_ssl_sock_t *ssock) 1059 { 1060 if (ssock->session) { 1061 gnutls_bye(ssock->session, GNUTLS_SHUT_RDWR); 1062 gnutls_deinit(ssock->session); 1063 ssock->session = NULL; 1064 } 1065 1066 if (ssock->xcred) { 1067 gnutls_certificate_free_credentials(ssock->xcred); 1068 ssock->xcred = NULL; 800 static void ssl_destroy(pj_ssl_sock_t *ssock) 801 { 802 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 803 804 if (gssock->session) { 805 gnutls_bye(gssock->session, GNUTLS_SHUT_RDWR); 806 gnutls_deinit(gssock->session); 807 gssock->session = NULL; 808 } 809 810 if (gssock->xcred) { 811 gnutls_certificate_free_credentials(gssock->xcred); 812 gssock->xcred = NULL; 1069 813 } 1070 814 1071 815 /* Free GnuTLS library */ 1072 if ( ssock->tls_init_count) {1073 ssock->tls_init_count--;816 if (gssock->tls_init_count) { 817 gssock->tls_init_count--; 1074 818 tls_deinit(); 1075 819 } … … 1082 826 1083 827 /* Reset socket state. */ 1084 static void tls_sock_reset(pj_ssl_sock_t *ssock) 1085 { 1086 ssock->connection_state = TLS_STATE_NULL; 1087 1088 tls_close(ssock); 1089 1090 if (ssock->asock) { 1091 pj_activesock_close(ssock->asock); 1092 ssock->asock = NULL; 1093 ssock->sock = PJ_INVALID_SOCKET; 1094 } 1095 if (ssock->sock != PJ_INVALID_SOCKET) { 1096 pj_sock_close(ssock->sock); 1097 ssock->sock = PJ_INVALID_SOCKET; 1098 } 828 static void ssl_reset_sock_state(pj_ssl_sock_t *ssock) 829 { 830 pj_lock_acquire(ssock->circ_buf_output_mutex); 831 ssock->ssl_state = SSL_STATE_NULL; 832 pj_lock_release(ssock->circ_buf_output_mutex); 833 834 ssl_close_sockets(ssock); 1099 835 1100 836 ssock->last_err = tls_last_error = GNUTLS_E_SUCCESS; 837 } 838 839 840 static void ssl_ciphers_populate(void) 841 { 842 if (!ssl_cipher_num) { 843 tls_init(); 844 tls_deinit(); 845 } 846 } 847 848 849 static pj_ssl_cipher ssl_get_cipher(pj_ssl_sock_t *ssock) 850 { 851 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 852 int i; 853 gnutls_cipher_algorithm_t lookup; 854 gnutls_cipher_algorithm_t cipher; 855 856 /* Current cipher */ 857 cipher = gnutls_cipher_get(gssock->session); 858 for (i = 0; ; i++) { 859 unsigned char id[2]; 860 const char *suite; 861 862 suite = gnutls_cipher_suite_info(i,(unsigned char *)id, NULL, 863 &lookup, NULL, NULL); 864 if (suite) { 865 if (lookup == cipher) { 866 return (pj_uint32_t) ((id[0] << 8) | id[1]); 867 } 868 } else { 869 break; 870 } 871 } 872 873 return PJ_TLS_UNKNOWN_CIPHER; 1101 874 } 1102 875 … … 1252 1025 /* Update local & remote certificates info. This function should be 1253 1026 * called after handshake or renegotiation successfully completed. */ 1254 static void tls_cert_update(pj_ssl_sock_t *ssock) 1255 { 1027 static void ssl_update_certs_info(pj_ssl_sock_t *ssock) 1028 { 1029 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 1256 1030 gnutls_x509_crt_t cert = NULL; 1257 1031 const gnutls_datum_t *us; … … 1260 1034 int ret = GNUTLS_CERT_INVALID; 1261 1035 1262 pj_assert(ssock-> connection_state == TLS_STATE_ESTABLISHED);1036 pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED); 1263 1037 1264 1038 /* Get active local certificate */ 1265 us = gnutls_certificate_get_ours( ssock->session);1039 us = gnutls_certificate_get_ours(gssock->session); 1266 1040 if (!us) 1267 1041 goto us_out; … … 1289 1063 1290 1064 /* Get active remote certificate */ 1291 certs = gnutls_certificate_get_peers( ssock->session, &certslen);1065 certs = gnutls_certificate_get_peers(gssock->session, &certslen); 1292 1066 if (certs == NULL || certslen == 0) 1293 1067 goto peer_out; … … 1315 1089 } 1316 1090 1317 1318 /* When handshake completed: 1319 * - notify application 1320 * - if handshake failed, reset SSL state 1321 * - return PJ_FALSE when SSL socket instance is destroyed by application. */ 1322 static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock, 1323 pj_status_t status) 1324 { 1325 pj_bool_t ret = PJ_TRUE; 1326 1327 /* Cancel handshake timer */ 1328 if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) { 1329 pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer); 1330 ssock->timer.id = TIMER_NONE; 1331 } 1332 1333 /* Update certificates info on successful handshake */ 1334 if (status == PJ_SUCCESS) 1335 tls_cert_update(ssock); 1336 1337 /* Accepting */ 1338 if (ssock->is_server) { 1339 if (status != PJ_SUCCESS) { 1340 /* Handshake failed in accepting, destroy our self silently. */ 1341 1342 char errmsg[PJ_ERR_MSG_SIZE]; 1343 char buf[PJ_INET6_ADDRSTRLEN + 10]; 1344 1345 pj_strerror(status, errmsg, sizeof(errmsg)); 1091 static void ssl_set_state(pj_ssl_sock_t *ssock, pj_bool_t is_server) 1092 { 1093 PJ_UNUSED_ARG(ssock); 1094 PJ_UNUSED_ARG(is_server); 1095 } 1096 1097 static void ssl_set_peer_name(pj_ssl_sock_t *ssock) 1098 { 1099 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 1100 1101 /* Set server name to connect */ 1102 if (ssock->param.server_name.slen) { 1103 int ret; 1104 /* Server name is null terminated already */ 1105 ret = gnutls_server_name_set(gssock->session, GNUTLS_NAME_DNS, 1106 ssock->param.server_name.ptr, 1107 ssock->param.server_name.slen); 1108 if (ret < 0) { 1346 1109 PJ_LOG(3, (ssock->pool->obj_name, 1347 "Handshake failed in accepting %s: %s", 1348 pj_sockaddr_print(&ssock->rem_addr, buf,sizeof(buf),3), 1349 errmsg)); 1350 1351 /* Workaround for ticket #985 */ 1352 #if (defined(PJ_WIN32)&& PJ_WIN32 != 0) || (defined(PJ_WIN64)&& PJ_WIN64 != 0) 1353 if (ssock->param.timer_heap) { 1354 pj_time_val interval = {0, DELAYED_CLOSE_TIMEOUT}; 1355 1356 tls_sock_reset(ssock); 1357 1358 ssock->timer.id = TIMER_CLOSE; 1359 pj_time_val_normalize(&interval); 1360 if (pj_timer_heap_schedule(ssock->param.timer_heap, 1361 &ssock->timer, &interval) != 0) 1362 { 1363 ssock->timer.id = TIMER_NONE; 1364 pj_ssl_sock_close(ssock); 1365 } 1366 } else 1367 #endif /* PJ_WIN32 */ 1368 { 1369 pj_ssl_sock_close(ssock); 1370 } 1371 1372 return PJ_FALSE; 1373 } 1374 /* Notify application the newly accepted SSL socket */ 1375 if (ssock->param.cb.on_accept_complete) 1376 ret = (*ssock->param.cb.on_accept_complete) 1377 (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr, 1378 pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr)); 1379 1380 } else { /* Connecting */ 1381 /* On failure, reset SSL socket state first, as app may try to 1382 * reconnect in the callback. */ 1383 if (status != PJ_SUCCESS) { 1384 /* Server disconnected us, possibly due to negotiation failure */ 1385 tls_sock_reset(ssock); 1386 } 1387 if (ssock->param.cb.on_connect_complete) { 1388 1389 ret = (*ssock->param.cb.on_connect_complete)(ssock, status); 1390 } 1391 } 1392 1393 return ret; 1394 } 1395 1396 static write_data_t *alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len) 1397 { 1398 send_buf_t *send_buf = &ssock->send_buf; 1399 pj_size_t avail_len, skipped_len = 0; 1400 char *reg1, *reg2; 1401 pj_size_t reg1_len, reg2_len; 1402 write_data_t *p; 1403 1404 /* Check buffer availability */ 1405 avail_len = send_buf->max_len - send_buf->len; 1406 if (avail_len < len) 1407 return NULL; 1408 1409 /* If buffer empty, reset start pointer and return it */ 1410 if (send_buf->len == 0) { 1411 send_buf->start = send_buf->buf; 1412 send_buf->len = len; 1413 p = (write_data_t*)send_buf->start; 1414 goto init_send_data; 1415 } 1416 1417 /* Free space may be wrapped/splitted into two regions, so let's 1418 * analyze them if any region can hold the write data. */ 1419 reg1 = send_buf->start + send_buf->len; 1420 if (reg1 >= send_buf->buf + send_buf->max_len) 1421 reg1 -= send_buf->max_len; 1422 reg1_len = send_buf->max_len - send_buf->len; 1423 if (reg1 + reg1_len > send_buf->buf + send_buf->max_len) { 1424 reg1_len = send_buf->buf + send_buf->max_len - reg1; 1425 reg2 = send_buf->buf; 1426 reg2_len = send_buf->start - send_buf->buf; 1427 } else { 1428 reg2 = NULL; 1429 reg2_len = 0; 1430 } 1431 1432 /* More buffer availability check, note that the write data must be in 1433 * a contigue buffer. */ 1434 avail_len = PJ_MAX(reg1_len, reg2_len); 1435 if (avail_len < len) 1436 return NULL; 1437 1438 /* Get the data slot */ 1439 if (reg1_len >= len) { 1440 p = (write_data_t*)reg1; 1441 } else { 1442 p = (write_data_t*)reg2; 1443 skipped_len = reg1_len; 1444 } 1445 1446 /* Update buffer length */ 1447 send_buf->len += len + skipped_len; 1448 1449 init_send_data: 1450 /* Init the new send data */ 1451 pj_bzero(p, sizeof(*p)); 1452 pj_list_init(p); 1453 pj_list_push_back(&ssock->send_pending, p); 1454 1455 return p; 1456 } 1457 1458 static void free_send_data(pj_ssl_sock_t *ssock, write_data_t *wdata) 1459 { 1460 send_buf_t *buf = &ssock->send_buf; 1461 write_data_t *spl = &ssock->send_pending; 1462 1463 pj_assert(!pj_list_empty(&ssock->send_pending)); 1464 1465 /* Free slot from the buffer */ 1466 if (spl->next == wdata && spl->prev == wdata) { 1467 /* This is the only data, reset the buffer */ 1468 buf->start = buf->buf; 1469 buf->len = 0; 1470 } else if (spl->next == wdata) { 1471 /* This is the first data, shift start pointer of the buffer and 1472 * adjust the buffer length. 1473 */ 1474 buf->start = (char*)wdata->next; 1475 if (wdata->next > wdata) { 1476 buf->len -= ((char*)wdata->next - buf->start); 1477 } else { 1478 /* Overlapped */ 1479 pj_size_t right_len, left_len; 1480 right_len = buf->buf + buf->max_len - (char*)wdata; 1481 left_len = (char*)wdata->next - buf->buf; 1482 buf->len -= (right_len + left_len); 1483 } 1484 } else if (spl->prev == wdata) { 1485 /* This is the last data, just adjust the buffer length */ 1486 if (wdata->prev < wdata) { 1487 pj_size_t jump_len; 1488 jump_len = (char*)wdata - 1489 ((char*)wdata->prev + wdata->prev->record_len); 1490 buf->len -= (wdata->record_len + jump_len); 1491 } else { 1492 /* Overlapped */ 1493 pj_size_t right_len, left_len; 1494 right_len = buf->buf + buf->max_len - 1495 ((char*)wdata->prev + wdata->prev->record_len); 1496 left_len = (char*)wdata + wdata->record_len - buf->buf; 1497 buf->len -= (right_len + left_len); 1498 } 1499 } 1500 /* For data in the middle buffer, just do nothing on the buffer. The slot 1501 * will be freed later when freeing the first/last data. */ 1502 1503 /* Remove the data from send pending list */ 1504 pj_list_erase(wdata); 1505 } 1506 1507 #if 0 1508 /* Just for testing send buffer alloc/free */ 1509 #include <pj/rand.h> 1510 pj_status_t pj_ssl_sock_ossl_test_send_buf(pj_pool_t *pool) 1511 { 1512 enum { MAX_CHUNK_NUM = 20 }; 1513 unsigned chunk_size, chunk_cnt, i; 1514 write_data_t *wdata[MAX_CHUNK_NUM] = {0}; 1515 pj_time_val now; 1516 pj_ssl_sock_t *ssock = NULL; 1517 pj_ssl_sock_param param; 1518 pj_status_t status; 1519 1520 pj_gettimeofday(&now); 1521 pj_srand((unsigned)now.sec); 1522 1523 pj_ssl_sock_param_default(¶m); 1524 status = pj_ssl_sock_create(pool, ¶m, &ssock); 1525 if (status != PJ_SUCCESS) { 1526 return status; 1527 } 1528 1529 if (ssock->send_buf.max_len == 0) { 1530 ssock->send_buf.buf = (char *) 1531 pj_pool_alloc(ssock->pool, 1532 ssock->param.send_buffer_size); 1533 ssock->send_buf.max_len = ssock->param.send_buffer_size; 1534 ssock->send_buf.start = ssock->send_buf.buf; 1535 ssock->send_buf.len = 0; 1536 } 1537 1538 chunk_size = ssock->param.send_buffer_size / MAX_CHUNK_NUM / 2; 1539 chunk_cnt = 0; 1540 for (i = 0; i < MAX_CHUNK_NUM; i++) { 1541 wdata[i] = alloc_send_data(ssock, pj_rand() % chunk_size + 321); 1542 if (wdata[i]) 1543 chunk_cnt++; 1544 else 1545 break; 1546 } 1547 1548 while (chunk_cnt) { 1549 i = pj_rand() % MAX_CHUNK_NUM; 1550 if (wdata[i]) { 1551 free_send_data(ssock, wdata[i]); 1552 wdata[i] = NULL; 1553 chunk_cnt--; 1554 } 1555 } 1556 1557 if (ssock->send_buf.len != 0) 1558 status = PJ_EBUG; 1559 1560 pj_ssl_sock_close(ssock); 1561 return status; 1562 } 1563 #endif 1564 1565 /* Flush write circular buffer to network socket. */ 1566 static pj_status_t flush_circ_buf_output(pj_ssl_sock_t *ssock, 1567 pj_ioqueue_op_key_t *send_key, 1568 pj_size_t orig_len, unsigned flags) 1569 { 1570 pj_ssize_t len; 1571 write_data_t *wdata; 1572 pj_size_t needed_len; 1573 pj_status_t status; 1574 1575 pj_lock_acquire(ssock->circ_buf_output_mutex); 1576 1577 /* Check if there is data in the circular buffer, flush it if any */ 1578 if (circ_empty(&ssock->circ_buf_output)) { 1579 pj_lock_release(ssock->circ_buf_output_mutex); 1580 1581 return PJ_SUCCESS; 1582 } 1583 1584 len = circ_size(&ssock->circ_buf_output); 1585 1586 /* Calculate buffer size needed, and align it to 8 */ 1587 needed_len = len + sizeof(write_data_t); 1588 needed_len = ((needed_len + 7) >> 3) << 3; 1589 1590 /* Allocate buffer for send data */ 1591 wdata = alloc_send_data(ssock, needed_len); 1592 if (wdata == NULL) { 1593 pj_lock_release(ssock->circ_buf_output_mutex); 1594 return PJ_ENOMEM; 1595 } 1596 1597 /* Copy the data and set its properties into the send data */ 1598 pj_ioqueue_op_key_init(&wdata->key, sizeof(pj_ioqueue_op_key_t)); 1599 wdata->key.user_data = wdata; 1600 wdata->app_key = send_key; 1601 wdata->record_len = needed_len; 1602 wdata->data_len = len; 1603 wdata->plain_data_len = orig_len; 1604 wdata->flags = flags; 1605 circ_read(&ssock->circ_buf_output, (pj_uint8_t *)&wdata->data, len); 1606 1607 /* Ticket #1573: Don't hold mutex while calling PJLIB socket send(). */ 1608 pj_lock_release(ssock->circ_buf_output_mutex); 1609 1610 /* Send it */ 1611 if (ssock->param.sock_type == pj_SOCK_STREAM()) { 1612 status = pj_activesock_send(ssock->asock, &wdata->key, 1613 wdata->data.content, &len, 1614 flags); 1615 } else { 1616 status = pj_activesock_sendto(ssock->asock, &wdata->key, 1617 wdata->data.content, &len, 1618 flags, 1619 (pj_sockaddr_t*)&ssock->rem_addr, 1620 ssock->addr_len); 1621 } 1622 1623 if (status != PJ_EPENDING) { 1624 /* When the sending is not pending, remove the wdata from send 1625 * pending list. */ 1626 pj_lock_acquire(ssock->circ_buf_output_mutex); 1627 free_send_data(ssock, wdata); 1628 pj_lock_release(ssock->circ_buf_output_mutex); 1629 } 1630 1631 return status; 1632 } 1633 1634 static void on_timer(pj_timer_heap_t *th, struct pj_timer_entry *te) 1635 { 1636 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)te->user_data; 1637 int timer_id = te->id; 1638 1639 te->id = TIMER_NONE; 1640 1641 PJ_UNUSED_ARG(th); 1642 1643 switch (timer_id) { 1644 case TIMER_HANDSHAKE_TIMEOUT: 1645 PJ_LOG(1, (ssock->pool->obj_name, "TLS timeout after %d.%ds", 1646 ssock->param.timeout.sec, ssock->param.timeout.msec)); 1647 1648 on_handshake_complete(ssock, PJ_ETIMEDOUT); 1649 break; 1650 case TIMER_CLOSE: 1651 pj_ssl_sock_close(ssock); 1652 break; 1653 default: 1654 pj_assert(!"Unknown timer"); 1655 break; 1656 } 1657 } 1658 1110 "gnutls_server_name_set() failed: %s", 1111 gnutls_strerror(ret))); 1112 } 1113 } 1114 } 1659 1115 1660 1116 /* Try to perform an asynchronous handshake */ 1661 static pj_status_t tls_try_handshake(pj_ssl_sock_t *ssock) 1662 { 1117 static pj_status_t ssl_do_handshake(pj_ssl_sock_t *ssock) 1118 { 1119 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 1663 1120 int ret; 1664 1121 pj_status_t status; 1665 1122 1666 1123 /* Perform SSL handshake */ 1667 ret = gnutls_handshake( ssock->session);1124 ret = gnutls_handshake(gssock->session); 1668 1125 1669 1126 status = flush_circ_buf_output(ssock, &ssock->handshake_op_key, 0, 0); … … 1673 1130 if (ret == GNUTLS_E_SUCCESS) { 1674 1131 /* System are GO */ 1675 ssock-> connection_state = TLS_STATE_ESTABLISHED;1132 ssock->ssl_state = SSL_STATE_ESTABLISHED; 1676 1133 status = PJ_SUCCESS; 1677 1134 } else if (!gnutls_error_is_fatal(ret)) { … … 1688 1145 } 1689 1146 1690 1691 /* 1692 ******************************************************************* 1693 * Active socket callbacks. 1694 ******************************************************************* 1695 */ 1696 1697 /* PJ_TRUE asks the socket to read more data, PJ_FALSE takes it off the queue */ 1698 static pj_bool_t asock_on_data_read(pj_activesock_t *asock, void *data, 1699 pj_size_t size, pj_status_t status, 1700 pj_size_t *remainder) 1701 { 1702 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *) 1703 pj_activesock_get_user_data(asock); 1704 1705 pj_size_t app_remainder = 0; 1706 1707 if (data && size > 0) { 1708 /* Push data into input circular buffer (for GnuTLS) */ 1709 pj_lock_acquire(ssock->circ_buf_input_mutex); 1710 circ_write(&ssock->circ_buf_input, data, size); 1711 pj_lock_release(ssock->circ_buf_input_mutex); 1712 } 1713 1714 /* Check if SSL handshake hasn't finished yet */ 1715 if (ssock->connection_state == TLS_STATE_HANDSHAKING) { 1716 pj_bool_t ret = PJ_TRUE; 1717 1718 if (status == PJ_SUCCESS) 1719 status = tls_try_handshake(ssock); 1720 1721 /* Not pending is either success or failed */ 1722 if (status != PJ_EPENDING) 1723 ret = on_handshake_complete(ssock, status); 1724 1725 return ret; 1726 } 1727 1728 /* See if there is any decrypted data for the application */ 1729 if (ssock->read_started) { 1730 do { 1731 /* Get read data structure at the end of the data */ 1732 read_data_t *app_read_data = 1733 *(OFFSET_OF_READ_DATA_PTR(ssock, data)); 1734 int app_data_size = (int)(ssock->read_size - app_read_data->len); 1735 1736 /* Decrypt received data using GnuTLS (will read our input 1737 * circular buffer) */ 1738 int decrypted_size = gnutls_record_recv(ssock->session, 1739 ((read_data_t *)app_read_data->data) + 1740 app_read_data->len, 1741 app_data_size); 1742 1743 if (decrypted_size > 0 || status != PJ_SUCCESS) { 1744 if (ssock->param.cb.on_data_read) { 1745 pj_bool_t ret; 1746 app_remainder = 0; 1747 1748 if (decrypted_size > 0) 1749 app_read_data->len += decrypted_size; 1750 1751 ret = (*ssock->param.cb.on_data_read)(ssock, 1752 app_read_data->data, 1753 app_read_data->len, 1754 status, 1755 &app_remainder); 1756 1757 if (!ret) { 1758 /* We've been destroyed */ 1759 return PJ_FALSE; 1760 } 1761 1762 /* Application may have left some data to be consumed 1763 * later as remainder */ 1764 app_read_data->len = app_remainder; 1765 } 1766 1767 /* Active socket signalled connection closed/error, this has 1768 * been signalled to the application along with any remaining 1769 * buffer. So, let's just reset SSL socket now. */ 1770 if (status != PJ_SUCCESS) { 1771 tls_sock_reset(ssock); 1772 return PJ_FALSE; 1773 } 1774 } else if (decrypted_size == 0) { 1775 /* Nothing more to read */ 1776 1777 return PJ_TRUE; 1778 } else if (decrypted_size == GNUTLS_E_AGAIN || 1779 decrypted_size == GNUTLS_E_INTERRUPTED) { 1780 return PJ_TRUE; 1781 } else if (decrypted_size == GNUTLS_E_REHANDSHAKE) { 1782 /* Seems like we are renegotiating */ 1783 pj_status_t try_handshake_status = tls_try_handshake(ssock); 1784 1785 /* Not pending is either success or failed */ 1786 if (try_handshake_status != PJ_EPENDING) { 1787 if (!on_handshake_complete(ssock, try_handshake_status)) { 1788 return PJ_FALSE; 1789 } 1790 } 1791 1792 if (try_handshake_status != PJ_SUCCESS && 1793 try_handshake_status != PJ_EPENDING) { 1794 return PJ_FALSE; 1795 } 1796 } else if (!gnutls_error_is_fatal(decrypted_size)) { 1797 /* non-fatal error, let's just continue */ 1798 } else { 1799 return PJ_FALSE; 1800 } 1801 } while (PJ_TRUE); 1802 } 1803 1804 return PJ_TRUE; 1805 } 1806 1807 1808 /* Callback every time new data is available from the active socket */ 1809 static pj_bool_t asock_on_data_sent(pj_activesock_t *asock, 1810 pj_ioqueue_op_key_t *send_key, 1811 pj_ssize_t sent) 1812 { 1813 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)pj_activesock_get_user_data(asock); 1814 1815 PJ_UNUSED_ARG(send_key); 1816 PJ_UNUSED_ARG(sent); 1817 1818 if (ssock->connection_state == TLS_STATE_HANDSHAKING) { 1819 /* Initial handshaking */ 1820 pj_status_t status = tls_try_handshake(ssock); 1821 1822 /* Not pending is either success or failed */ 1823 if (status != PJ_EPENDING) 1824 return on_handshake_complete(ssock, status); 1825 1826 } else if (send_key != &ssock->handshake_op_key) { 1827 /* Some data has been sent, notify application */ 1828 write_data_t *wdata = (write_data_t*)send_key->user_data; 1829 if (ssock->param.cb.on_data_sent) { 1830 pj_bool_t ret; 1831 pj_ssize_t sent_len; 1832 1833 sent_len = sent > 0 ? wdata->plain_data_len : sent; 1834 1835 ret = (*ssock->param.cb.on_data_sent)(ssock, wdata->app_key, 1836 sent_len); 1837 if (!ret) { 1838 /* We've been destroyed */ 1839 return PJ_FALSE; 1840 } 1841 } 1842 1843 /* Update write buffer state */ 1844 pj_lock_acquire(ssock->circ_buf_output_mutex); 1845 free_send_data(ssock, wdata); 1846 pj_lock_release(ssock->circ_buf_output_mutex); 1147 static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) 1148 { 1149 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 1150 int decrypted_size; 1151 1152 /* Decrypt received data using GnuTLS (will read our input 1153 * circular buffer) */ 1154 decrypted_size = gnutls_record_recv(gssock->session, data, *size); 1155 *size = 0; 1156 if (decrypted_size > 0) { 1157 *size = decrypted_size; 1158 return PJ_SUCCESS; 1159 } else if (decrypted_size == 0) { 1160 /* Nothing more to read */ 1161 return PJ_SUCCESS; 1162 } else if (decrypted_size == GNUTLS_E_REHANDSHAKE) { 1163 return PJ_EEOF; 1164 } else if (decrypted_size == GNUTLS_E_AGAIN || 1165 decrypted_size == GNUTLS_E_INTERRUPTED || 1166 !gnutls_error_is_fatal(decrypted_size)) 1167 { 1168 /* non-fatal error, let's just continue */ 1169 return PJ_SUCCESS; 1847 1170 } else { 1848 /* SSL re-negotiation is on-progress, just do nothing */ 1849 /* FIXME: check if this is valid for GnuTLS too */ 1850 } 1851 1852 return PJ_TRUE; 1853 } 1854 1855 1856 /* Callback every time a new connection has been accepted (server) */ 1857 static pj_bool_t asock_on_accept_complete(pj_activesock_t *asock, 1858 pj_sock_t newsock, 1859 const pj_sockaddr_t *src_addr, 1860 int src_addr_len) 1861 { 1862 pj_ssl_sock_t *ssock_parent = (pj_ssl_sock_t *) 1863 pj_activesock_get_user_data(asock); 1864 1865 pj_ssl_sock_t *ssock; 1866 pj_activesock_cb asock_cb; 1867 pj_activesock_cfg asock_cfg; 1868 unsigned int i; 1869 pj_status_t status; 1870 1871 PJ_UNUSED_ARG(src_addr_len); 1872 1873 /* Create new SSL socket instance */ 1874 status = pj_ssl_sock_create(ssock_parent->pool, 1875 &ssock_parent->newsock_param, 1876 &ssock); 1877 if (status != PJ_SUCCESS) 1878 goto on_return; 1879 1880 /* Update new SSL socket attributes */ 1881 ssock->sock = newsock; 1882 ssock->parent = ssock_parent; 1883 ssock->is_server = PJ_TRUE; 1884 if (ssock_parent->cert) { 1885 status = pj_ssl_sock_set_certificate(ssock, ssock->pool, 1886 ssock_parent->cert); 1887 if (status != PJ_SUCCESS) 1888 goto on_return; 1889 } 1890 1891 /* Apply QoS, if specified */ 1892 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, 1893 &ssock->param.qos_params, 1, 1894 ssock->pool->obj_name, NULL); 1895 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) 1896 goto on_return; 1897 1898 /* Update local address */ 1899 ssock->addr_len = src_addr_len; 1900 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 1901 &ssock->addr_len); 1902 if (status != PJ_SUCCESS) { 1903 /* This fails on few envs, e.g: win IOCP, just tolerate this and 1904 * use parent local address instead. 1905 */ 1906 pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr); 1907 } 1908 1909 /* Set remote address */ 1910 pj_sockaddr_cp(&ssock->rem_addr, src_addr); 1911 1912 /* Create SSL context */ 1913 status = tls_open(ssock); 1914 if (status != PJ_SUCCESS) 1915 goto on_return; 1916 1917 /* Prepare read buffer */ 1918 ssock->asock_rbuf = (void **)pj_pool_calloc(ssock->pool, 1919 ssock->param.async_cnt, 1920 sizeof(void*)); 1921 if (!ssock->asock_rbuf) 1922 return PJ_ENOMEM; 1923 1924 for (i = 0; i < ssock->param.async_cnt; ++i) { 1925 ssock->asock_rbuf[i] = (void *)pj_pool_alloc( 1926 ssock->pool, 1927 ssock->param.read_buffer_size + 1928 sizeof(read_data_t*)); 1929 if (!ssock->asock_rbuf[i]) 1930 return PJ_ENOMEM; 1931 } 1932 1933 /* Create active socket */ 1934 pj_activesock_cfg_default(&asock_cfg); 1935 asock_cfg.async_cnt = ssock->param.async_cnt; 1936 asock_cfg.concurrency = ssock->param.concurrency; 1937 asock_cfg.whole_data = PJ_TRUE; 1938 1939 pj_bzero(&asock_cb, sizeof(asock_cb)); 1940 asock_cb.on_data_read = asock_on_data_read; 1941 asock_cb.on_data_sent = asock_on_data_sent; 1942 1943 status = pj_activesock_create(ssock->pool, 1944 ssock->sock, 1945 ssock->param.sock_type, 1946 &asock_cfg, 1947 ssock->param.ioqueue, 1948 &asock_cb, 1949 ssock, 1950 &ssock->asock); 1951 1952 if (status != PJ_SUCCESS) 1953 goto on_return; 1954 1955 /* Start reading */ 1956 status = pj_activesock_start_read2(ssock->asock, ssock->pool, 1957 (unsigned)ssock->param.read_buffer_size, 1958 ssock->asock_rbuf, 1959 PJ_IOQUEUE_ALWAYS_ASYNC); 1960 if (status != PJ_SUCCESS) 1961 goto on_return; 1962 1963 /* Prepare write/send state */ 1964 pj_assert(ssock->send_buf.max_len == 0); 1965 ssock->send_buf.buf = (char *)pj_pool_alloc(ssock->pool, 1966 ssock->param.send_buffer_size); 1967 if (!ssock->send_buf.buf) 1968 return PJ_ENOMEM; 1969 1970 ssock->send_buf.max_len = ssock->param.send_buffer_size; 1971 ssock->send_buf.start = ssock->send_buf.buf; 1972 ssock->send_buf.len = 0; 1973 1974 /* Start handshake timer */ 1975 if (ssock->param.timer_heap && 1976 (ssock->param.timeout.sec != 0 || ssock->param.timeout.msec != 0)) { 1977 pj_assert(ssock->timer.id == TIMER_NONE); 1978 ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT; 1979 status = pj_timer_heap_schedule(ssock->param.timer_heap, 1980 &ssock->timer, 1981 &ssock->param.timeout); 1982 if (status != PJ_SUCCESS) 1983 ssock->timer.id = TIMER_NONE; 1984 } 1985 1986 /* Start SSL handshake */ 1987 ssock->connection_state = TLS_STATE_HANDSHAKING; 1988 1989 status = tls_try_handshake(ssock); 1990 1991 on_return: 1992 if (ssock && status != PJ_EPENDING) 1993 on_handshake_complete(ssock, status); 1994 1995 /* Must return PJ_TRUE whatever happened, as active socket must 1996 * continue listening. 1997 */ 1998 return PJ_TRUE; 1999 } 2000 2001 2002 /* Callback every time a new connection has been completed (client) */ 2003 static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock, 2004 pj_status_t status) 2005 { 2006 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) 2007 pj_activesock_get_user_data(asock); 2008 2009 unsigned int i; 2010 int ret; 2011 2012 if (status != PJ_SUCCESS) 2013 goto on_return; 2014 2015 /* Update local address */ 2016 ssock->addr_len = sizeof(pj_sockaddr); 2017 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 2018 &ssock->addr_len); 2019 if (status != PJ_SUCCESS) 2020 goto on_return; 2021 2022 /* Create SSL context */ 2023 status = tls_open(ssock); 2024 if (status != PJ_SUCCESS) 2025 goto on_return; 2026 2027 /* Prepare read buffer */ 2028 ssock->asock_rbuf = (void **)pj_pool_calloc(ssock->pool, 2029 ssock->param.async_cnt, 2030 sizeof(void *)); 2031 if (!ssock->asock_rbuf) 2032 return PJ_ENOMEM; 2033 2034 for (i = 0; i < ssock->param.async_cnt; ++i) { 2035 ssock->asock_rbuf[i] = (void *)pj_pool_alloc( 2036 ssock->pool, 2037 ssock->param.read_buffer_size + 2038 sizeof(read_data_t *)); 2039 if (!ssock->asock_rbuf[i]) 2040 return PJ_ENOMEM; 2041 } 2042 2043 /* Start read */ 2044 status = pj_activesock_start_read2(ssock->asock, ssock->pool, 2045 (unsigned)ssock->param.read_buffer_size, 2046 ssock->asock_rbuf, 2047 PJ_IOQUEUE_ALWAYS_ASYNC); 2048 if (status != PJ_SUCCESS) 2049 goto on_return; 2050 2051 /* Prepare write/send state */ 2052 pj_assert(ssock->send_buf.max_len == 0); 2053 ssock->send_buf.buf = (char *)pj_pool_alloc(ssock->pool, 2054 ssock->param.send_buffer_size); 2055 if (!ssock->send_buf.buf) 2056 return PJ_ENOMEM; 2057 2058 ssock->send_buf.max_len = ssock->param.send_buffer_size; 2059 ssock->send_buf.start = ssock->send_buf.buf; 2060 ssock->send_buf.len = 0; 2061 2062 /* Set server name to connect */ 2063 if (ssock->param.server_name.slen) { 2064 /* Server name is null terminated already */ 2065 ret = gnutls_server_name_set(ssock->session, GNUTLS_NAME_DNS, 2066 ssock->param.server_name.ptr, 2067 ssock->param.server_name.slen); 2068 if (ret < 0) { 2069 PJ_LOG(3, (ssock->pool->obj_name, 2070 "gnutls_server_name_set() failed: %s", 2071 gnutls_strerror(ret))); 2072 } 2073 } 2074 2075 /* Start handshake */ 2076 ssock->connection_state = TLS_STATE_HANDSHAKING; 2077 2078 status = tls_try_handshake(ssock); 2079 if (status != PJ_EPENDING) 2080 goto on_return; 2081 2082 return PJ_TRUE; 2083 2084 on_return: 2085 return on_handshake_complete(ssock, status); 2086 } 2087 2088 static void tls_ciphers_fill(void) 2089 { 2090 if (!tls_available_ciphers) { 2091 tls_init(); 2092 tls_deinit(); 2093 } 2094 } 2095 2096 /* 2097 ******************************************************************* 2098 * API 2099 ******************************************************************* 2100 */ 2101 2102 /* Load credentials from files. */ 2103 PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files(pj_pool_t *pool, 2104 const pj_str_t *CA_file, 2105 const pj_str_t *cert_file, 2106 const pj_str_t *privkey_file, 2107 const pj_str_t *privkey_pass, 2108 pj_ssl_cert_t **p_cert) 2109 { 2110 return pj_ssl_cert_load_from_files2(pool, CA_file, NULL, cert_file, 2111 privkey_file, privkey_pass, p_cert); 2112 } 2113 2114 /* Load credentials from files. */ 2115 PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files2( 2116 pj_pool_t *pool, 2117 const pj_str_t *CA_file, 2118 const pj_str_t *CA_path, 2119 const pj_str_t *cert_file, 2120 const pj_str_t *privkey_file, 2121 const pj_str_t *privkey_pass, 2122 pj_ssl_cert_t **p_cert) 2123 { 2124 pj_ssl_cert_t *cert; 2125 2126 PJ_ASSERT_RETURN(pool && (CA_file || CA_path) && cert_file && 2127 privkey_file, 2128 PJ_EINVAL); 2129 2130 cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t); 2131 if (CA_file) { 2132 pj_strdup_with_null(pool, &cert->CA_file, CA_file); 2133 } 2134 if (CA_path) { 2135 pj_strdup_with_null(pool, &cert->CA_path, CA_path); 2136 } 2137 pj_strdup_with_null(pool, &cert->cert_file, cert_file); 2138 pj_strdup_with_null(pool, &cert->privkey_file, privkey_file); 2139 pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass); 2140 2141 *p_cert = cert; 2142 2143 return PJ_SUCCESS; 2144 } 2145 2146 PJ_DEF(pj_status_t) pj_ssl_cert_load_from_buffer(pj_pool_t *pool, 2147 const pj_ssl_cert_buffer *CA_buf, 2148 const pj_ssl_cert_buffer *cert_buf, 2149 const pj_ssl_cert_buffer *privkey_buf, 2150 const pj_str_t *privkey_pass, 2151 pj_ssl_cert_t **p_cert) 2152 { 2153 pj_ssl_cert_t *cert; 2154 2155 PJ_ASSERT_RETURN(pool && CA_buf && cert_buf && privkey_buf, PJ_EINVAL); 2156 2157 cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t); 2158 pj_strdup(pool, &cert->CA_buf, CA_buf); 2159 pj_strdup(pool, &cert->cert_buf, cert_buf); 2160 pj_strdup(pool, &cert->privkey_buf, privkey_buf); 2161 pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass); 2162 2163 *p_cert = cert; 2164 2165 return PJ_SUCCESS; 2166 } 2167 2168 /* Store credentials. */ 2169 PJ_DEF(pj_status_t) pj_ssl_sock_set_certificate( pj_ssl_sock_t *ssock, 2170 pj_pool_t *pool, 2171 const pj_ssl_cert_t *cert) 2172 { 2173 pj_ssl_cert_t *cert_; 2174 2175 PJ_ASSERT_RETURN(ssock && pool && cert, PJ_EINVAL); 2176 2177 cert_ = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t); 2178 pj_memcpy(cert_, cert, sizeof(cert)); 2179 pj_strdup_with_null(pool, &cert_->CA_file, &cert->CA_file); 2180 pj_strdup_with_null(pool, &cert_->CA_path, &cert->CA_path); 2181 pj_strdup_with_null(pool, &cert_->cert_file, &cert->cert_file); 2182 pj_strdup_with_null(pool, &cert_->privkey_file, &cert->privkey_file); 2183 pj_strdup_with_null(pool, &cert_->privkey_pass, &cert->privkey_pass); 2184 2185 pj_strdup(pool, &cert_->CA_buf, &cert->CA_buf); 2186 pj_strdup(pool, &cert_->cert_buf, &cert->cert_buf); 2187 pj_strdup(pool, &cert_->privkey_buf, &cert->privkey_buf); 2188 2189 ssock->cert = cert_; 2190 2191 return PJ_SUCCESS; 2192 } 2193 2194 2195 /* Get available ciphers. */ 2196 PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[], 2197 unsigned *cipher_num) 2198 { 2199 unsigned int i; 2200 2201 PJ_ASSERT_RETURN(ciphers && cipher_num, PJ_EINVAL); 2202 2203 tls_ciphers_fill(); 2204 2205 if (!tls_available_ciphers) { 2206 *cipher_num = 0; 2207 return PJ_ENOTFOUND; 2208 } 2209 2210 *cipher_num = PJ_MIN(*cipher_num, tls_available_ciphers); 2211 2212 for (i = 0; i < *cipher_num; ++i) 2213 ciphers[i] = tls_ciphers[i].id; 2214 2215 return PJ_SUCCESS; 2216 } 2217 2218 2219 /* Get cipher name string. */ 2220 PJ_DEF(const char *)pj_ssl_cipher_name(pj_ssl_cipher cipher) 2221 { 2222 unsigned int i; 2223 2224 tls_ciphers_fill(); 2225 2226 for (i = 0; i < tls_available_ciphers; ++i) { 2227 if (cipher == tls_ciphers[i].id) 2228 return tls_ciphers[i].name; 2229 } 2230 2231 return NULL; 2232 } 2233 2234 2235 /* Get cipher identifier. */ 2236 PJ_DEF(pj_ssl_cipher) pj_ssl_cipher_id(const char *cipher_name) 2237 { 2238 unsigned int i; 2239 2240 tls_ciphers_fill(); 2241 2242 for (i = 0; i < tls_available_ciphers; ++i) { 2243 if (!pj_ansi_stricmp(tls_ciphers[i].name, cipher_name)) 2244 return tls_ciphers[i].id; 2245 } 2246 2247 return PJ_TLS_UNKNOWN_CIPHER; 2248 } 2249 2250 2251 /* Check if the specified cipher is supported by the TLS backend. */ 2252 PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher) 2253 { 2254 unsigned int i; 2255 2256 tls_ciphers_fill(); 2257 2258 for (i = 0; i < tls_available_ciphers; ++i) { 2259 if (cipher == tls_ciphers[i].id) 2260 return PJ_TRUE; 2261 } 2262 2263 return PJ_FALSE; 2264 } 2265 2266 /* Create SSL socket instance. */ 2267 PJ_DEF(pj_status_t) pj_ssl_sock_create(pj_pool_t *pool, 2268 const pj_ssl_sock_param *param, 2269 pj_ssl_sock_t **p_ssock) 2270 { 2271 pj_ssl_sock_t *ssock; 2272 pj_status_t status; 2273 2274 PJ_ASSERT_RETURN(pool && param && p_ssock, PJ_EINVAL); 2275 PJ_ASSERT_RETURN(param->sock_type == pj_SOCK_STREAM(), PJ_ENOTSUP); 2276 2277 pool = pj_pool_create(pool->factory, "tls%p", 512, 512, NULL); 2278 2279 /* Create secure socket */ 2280 ssock = PJ_POOL_ZALLOC_T(pool, pj_ssl_sock_t); 2281 ssock->pool = pool; 2282 ssock->sock = PJ_INVALID_SOCKET; 2283 ssock->connection_state = TLS_STATE_NULL; 2284 pj_list_init(&ssock->write_pending); 2285 pj_list_init(&ssock->write_pending_empty); 2286 pj_list_init(&ssock->send_pending); 2287 pj_timer_entry_init(&ssock->timer, 0, ssock, &on_timer); 2288 pj_ioqueue_op_key_init(&ssock->handshake_op_key, 2289 sizeof(pj_ioqueue_op_key_t)); 2290 2291 /* Create secure socket mutex */ 2292 status = pj_lock_create_recursive_mutex(pool, pool->obj_name, 2293 &ssock->circ_buf_output_mutex); 2294 if (status != PJ_SUCCESS) 2295 return status; 2296 2297 /* Create input circular buffer mutex */ 2298 status = pj_lock_create_simple_mutex(pool, pool->obj_name, 2299 &ssock->circ_buf_input_mutex); 2300 if (status != PJ_SUCCESS) 2301 return status; 2302 2303 /* Create output circular buffer mutex */ 2304 status = pj_lock_create_simple_mutex(pool, pool->obj_name, 2305 &ssock->circ_buf_output_mutex); 2306 if (status != PJ_SUCCESS) 2307 return status; 2308 2309 /* Init secure socket param */ 2310 ssock->param = *param; 2311 ssock->param.read_buffer_size = ((ssock->param.read_buffer_size + 7) >> 3) 2312 << 3; 2313 2314 if (param->ciphers_num > 0) { 2315 unsigned int i; 2316 ssock->param.ciphers = (pj_ssl_cipher *) 2317 pj_pool_calloc(pool, param->ciphers_num, 2318 sizeof(pj_ssl_cipher)); 2319 if (!ssock->param.ciphers) 2320 return PJ_ENOMEM; 2321 2322 for (i = 0; i < param->ciphers_num; ++i) 2323 ssock->param.ciphers[i] = param->ciphers[i]; 2324 } 2325 2326 /* Server name must be null-terminated */ 2327 pj_strdup_with_null(pool, &ssock->param.server_name, ¶m->server_name); 2328 2329 /* Finally */ 2330 *p_ssock = ssock; 2331 2332 return PJ_SUCCESS; 2333 } 2334 2335 2336 /* 2337 * Close the secure socket. This will unregister the socket from the 2338 * ioqueue and ultimately close the socket. 2339 */ 2340 PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock) 2341 { 2342 pj_pool_t *pool; 2343 2344 PJ_ASSERT_RETURN(ssock, PJ_EINVAL); 2345 2346 if (!ssock->pool) 2347 return PJ_SUCCESS; 2348 2349 if (ssock->timer.id != TIMER_NONE) { 2350 pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer); 2351 ssock->timer.id = TIMER_NONE; 2352 } 2353 2354 tls_sock_reset(ssock); 2355 2356 pj_lock_destroy(ssock->circ_buf_output_mutex); 2357 pj_lock_destroy(ssock->circ_buf_input_mutex); 2358 2359 pool = ssock->pool; 2360 ssock->pool = NULL; 2361 if (pool) 2362 pj_pool_release(pool); 2363 2364 return PJ_SUCCESS; 2365 } 2366 2367 2368 /* Associate arbitrary data with the secure socket. */ 2369 PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock, 2370 void *user_data) 2371 { 2372 PJ_ASSERT_RETURN(ssock, PJ_EINVAL); 2373 2374 ssock->param.user_data = user_data; 2375 return PJ_SUCCESS; 2376 } 2377 2378 2379 /* Retrieve the user data previously associated with this secure socket. */ 2380 PJ_DEF(void *)pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock) 2381 { 2382 PJ_ASSERT_RETURN(ssock, NULL); 2383 2384 return ssock->param.user_data; 2385 } 2386 2387 2388 /* Retrieve the local address and port used by specified SSL socket. */ 2389 PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock, 2390 pj_ssl_sock_info *info) 2391 { 2392 pj_bzero(info, sizeof(*info)); 2393 2394 /* Established flag */ 2395 info->established = (ssock->connection_state == TLS_STATE_ESTABLISHED); 2396 2397 /* Protocol */ 2398 info->proto = ssock->param.proto; 2399 2400 /* Local address */ 2401 pj_sockaddr_cp(&info->local_addr, &ssock->local_addr); 2402 2403 if (info->established) { 2404 int i; 2405 gnutls_cipher_algorithm_t lookup; 2406 gnutls_cipher_algorithm_t cipher; 2407 2408 /* Current cipher */ 2409 cipher = gnutls_cipher_get(ssock->session); 2410 for (i = 0; ; i++) { 2411 unsigned char id[2]; 2412 const char *suite = gnutls_cipher_suite_info(i,(unsigned char *)id, 2413 NULL, &lookup, NULL, 2414 NULL); 2415 if (suite) { 2416 if (lookup == cipher) { 2417 info->cipher = (pj_uint32_t) ((id[0] << 8) | id[1]); 2418 break; 2419 } 2420 } else 2421 break; 2422 } 2423 2424 /* Remote address */ 2425 pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr); 2426 2427 /* Certificates info */ 2428 info->local_cert_info = &ssock->local_cert_info; 2429 info->remote_cert_info = &ssock->remote_cert_info; 2430 2431 /* Verification status */ 2432 info->verify_status = ssock->verify_status; 2433 } 2434 2435 /* Last known GnuTLS error code */ 2436 info->last_native_err = ssock->last_err; 2437 2438 return PJ_SUCCESS; 2439 } 2440 2441 2442 /* Starts read operation on this secure socket. */ 2443 PJ_DEF(pj_status_t) pj_ssl_sock_start_read(pj_ssl_sock_t *ssock, 2444 pj_pool_t *pool, 2445 unsigned buff_size, 2446 pj_uint32_t flags) 2447 { 2448 void **readbuf; 2449 unsigned int i; 2450 2451 PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL); 2452 PJ_ASSERT_RETURN(ssock->connection_state == TLS_STATE_ESTABLISHED, 2453 PJ_EINVALIDOP); 2454 2455 readbuf = (void**) pj_pool_calloc(pool, ssock->param.async_cnt, 2456 sizeof(void *)); 2457 if (!readbuf) 2458 return PJ_ENOMEM; 2459 2460 for (i = 0; i < ssock->param.async_cnt; ++i) { 2461 readbuf[i] = pj_pool_alloc(pool, buff_size); 2462 if (!readbuf[i]) 2463 return PJ_ENOMEM; 2464 } 2465 2466 return pj_ssl_sock_start_read2(ssock, pool, buff_size, readbuf, flags); 2467 } 2468 2469 2470 /* 2471 * Same as #pj_ssl_sock_start_read(), except that the application 2472 * supplies the buffers for the read operation so that the acive socket 2473 * does not have to allocate the buffers. 2474 */ 2475 PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, 2476 pj_pool_t *pool, 2477 unsigned buff_size, 2478 void *readbuf[], 2479 pj_uint32_t flags) 2480 { 2481 unsigned int i; 2482 2483 PJ_ASSERT_RETURN(ssock && pool && buff_size && readbuf, PJ_EINVAL); 2484 PJ_ASSERT_RETURN(ssock->connection_state == TLS_STATE_ESTABLISHED, 2485 PJ_EINVALIDOP); 2486 2487 /* Create SSL socket read buffer */ 2488 ssock->ssock_rbuf = (read_data_t*)pj_pool_calloc(pool, 2489 ssock->param.async_cnt, 2490 sizeof(read_data_t)); 2491 if (!ssock->ssock_rbuf) 2492 return PJ_ENOMEM; 2493 2494 /* Store SSL socket read buffer pointer in the activesock read buffer */ 2495 for (i = 0; i < ssock->param.async_cnt; ++i) { 2496 read_data_t **p_ssock_rbuf = 2497 OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]); 2498 2499 ssock->ssock_rbuf[i].data = readbuf[i]; 2500 ssock->ssock_rbuf[i].len = 0; 2501 2502 *p_ssock_rbuf = &ssock->ssock_rbuf[i]; 2503 } 2504 2505 ssock->read_size = buff_size; 2506 ssock->read_started = PJ_TRUE; 2507 ssock->read_flags = flags; 2508 2509 return PJ_SUCCESS; 2510 } 2511 2512 2513 /* 2514 * Same as pj_ssl_sock_start_read(), except that this function is used 2515 * only for datagram sockets, and it will trigger \a on_data_recvfrom() 2516 * callback instead. 2517 */ 2518 PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock, 2519 pj_pool_t *pool, 2520 unsigned buff_size, 2521 pj_uint32_t flags) 2522 { 2523 PJ_UNUSED_ARG(ssock); 2524 PJ_UNUSED_ARG(pool); 2525 PJ_UNUSED_ARG(buff_size); 2526 PJ_UNUSED_ARG(flags); 2527 2528 return PJ_ENOTSUP; 2529 } 2530 2531 2532 /* 2533 * Same as #pj_ssl_sock_start_recvfrom() except that the recvfrom() 2534 * operation takes the buffer from the argument rather than creating 2535 * new ones. 2536 */ 2537 PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock, 2538 pj_pool_t *pool, 2539 unsigned buff_size, 2540 void *readbuf[], 2541 pj_uint32_t flags) 2542 { 2543 PJ_UNUSED_ARG(ssock); 2544 PJ_UNUSED_ARG(pool); 2545 PJ_UNUSED_ARG(buff_size); 2546 PJ_UNUSED_ARG(readbuf); 2547 PJ_UNUSED_ARG(flags); 2548 2549 return PJ_ENOTSUP; 2550 } 2551 1171 return PJ_ECANCELLED; 1172 } 1173 } 2552 1174 2553 1175 /* … … 2556 1178 * sending data should be delayed until re-negotiation is completed. 2557 1179 */ 2558 static pj_status_t tls_write(pj_ssl_sock_t *ssock, 2559 pj_ioqueue_op_key_t *send_key, 2560 const void *data, pj_ssize_t size, unsigned flags) 2561 { 2562 pj_status_t status; 2563 int nwritten; 1180 static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, 1181 pj_ssize_t size, int *nwritten) 1182 { 1183 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 1184 int nwritten_; 2564 1185 pj_ssize_t total_written = 0; 2565 1186 … … 2571 1192 while (total_written < size) { 2572 1193 /* Try encrypting using GnuTLS */ 2573 nwritten = gnutls_record_send(ssock->session,1194 nwritten_ = gnutls_record_send(gssock->session, 2574 1195 ((read_data_t *)data) + total_written, 2575 size );2576 2577 if (nwritten > 0) {1196 size - total_written); 1197 1198 if (nwritten_ > 0) { 2578 1199 /* Good, some data was encrypted and written */ 2579 total_written += nwritten ;1200 total_written += nwritten_; 2580 1201 } else { 2581 1202 /* Normally we would have to retry record_send but our internal … … 2583 1204 * We will just try again later, although this should never happen. 2584 1205 */ 2585 return tls_status_from_err(ssock, nwritten); 1206 *nwritten = nwritten_; 1207 return tls_status_from_err(ssock, nwritten_); 2586 1208 } 2587 1209 } … … 2589 1211 /* All encrypted data is written to the output circular buffer; 2590 1212 * now send it on the socket (or notify problem). */ 2591 if (total_written == size) 2592 status = flush_circ_buf_output(ssock, send_key, size, flags); 2593 else 2594 status = PJ_ENOMEM; 2595 2596 return status; 2597 } 2598 2599 2600 /* Flush delayed data sending in the write pending list. */ 2601 static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock) 2602 { 2603 /* Check for another ongoing flush */ 2604 if (ssock->flushing_write_pend) { 2605 return PJ_EBUSY; 2606 } 2607 2608 pj_lock_acquire(ssock->circ_buf_output_mutex); 2609 2610 /* Again, check for another ongoing flush */ 2611 if (ssock->flushing_write_pend) { 2612 pj_lock_release(ssock->circ_buf_output_mutex); 2613 return PJ_EBUSY; 2614 } 2615 2616 /* Set ongoing flush flag */ 2617 ssock->flushing_write_pend = PJ_TRUE; 2618 2619 while (!pj_list_empty(&ssock->write_pending)) { 2620 write_data_t *wp; 2621 pj_status_t status; 2622 2623 wp = ssock->write_pending.next; 2624 2625 /* Ticket #1573: Don't hold mutex while calling socket send. */ 2626 pj_lock_release(ssock->circ_buf_output_mutex); 2627 2628 status = tls_write(ssock, &wp->key, wp->data.ptr, 2629 wp->plain_data_len, wp->flags); 2630 if (status != PJ_SUCCESS) { 2631 /* Reset ongoing flush flag first. */ 2632 ssock->flushing_write_pend = PJ_FALSE; 2633 return status; 2634 } 2635 2636 pj_lock_acquire(ssock->circ_buf_output_mutex); 2637 pj_list_erase(wp); 2638 pj_list_push_back(&ssock->write_pending_empty, wp); 2639 } 2640 2641 /* Reset ongoing flush flag */ 2642 ssock->flushing_write_pend = PJ_FALSE; 2643 2644 pj_lock_release(ssock->circ_buf_output_mutex); 2645 1213 *nwritten = total_written; 2646 1214 return PJ_SUCCESS; 2647 1215 } 2648 1216 2649 2650 /* Sending is delayed, push back the sending data into pending list. */ 2651 static pj_status_t delay_send(pj_ssl_sock_t *ssock, 2652 pj_ioqueue_op_key_t *send_key, 2653 const void *data, pj_ssize_t size, 2654 unsigned flags) 2655 { 2656 write_data_t *wp; 2657 2658 pj_lock_acquire(ssock->circ_buf_output_mutex); 2659 2660 /* Init write pending instance */ 2661 if (!pj_list_empty(&ssock->write_pending_empty)) { 2662 wp = ssock->write_pending_empty.next; 2663 pj_list_erase(wp); 2664 } else { 2665 wp = PJ_POOL_ZALLOC_T(ssock->pool, write_data_t); 2666 } 2667 2668 wp->app_key = send_key; 2669 wp->plain_data_len = size; 2670 wp->data.ptr = data; 2671 wp->flags = flags; 2672 2673 pj_list_push_back(&ssock->write_pending, wp); 2674 2675 pj_lock_release(ssock->circ_buf_output_mutex); 2676 2677 /* Must return PJ_EPENDING */ 2678 return PJ_EPENDING; 2679 } 2680 2681 2682 /** 2683 * Send data using the socket. 2684 */ 2685 PJ_DEF(pj_status_t) pj_ssl_sock_send(pj_ssl_sock_t *ssock, 2686 pj_ioqueue_op_key_t *send_key, 2687 const void *data, pj_ssize_t *size, 2688 unsigned flags) 2689 { 2690 pj_status_t status; 2691 2692 PJ_ASSERT_RETURN(ssock && data && size && (*size > 0), PJ_EINVAL); 2693 PJ_ASSERT_RETURN(ssock->connection_state==TLS_STATE_ESTABLISHED, 2694 PJ_EINVALIDOP); 2695 2696 /* Flush delayed send first. Sending data might be delayed when 2697 * re-negotiation is on-progress. */ 2698 status = flush_delayed_send(ssock); 2699 if (status == PJ_EBUSY) { 2700 /* Re-negotiation or flushing is on progress, delay sending */ 2701 status = delay_send(ssock, send_key, data, *size, flags); 2702 goto on_return; 2703 } else if (status != PJ_SUCCESS) { 2704 goto on_return; 2705 } 2706 2707 /* Write data to SSL */ 2708 status = tls_write(ssock, send_key, data, *size, flags); 2709 if (status == PJ_EBUSY) { 2710 /* Re-negotiation is on progress, delay sending */ 2711 status = delay_send(ssock, send_key, data, *size, flags); 2712 } 2713 2714 on_return: 2715 return status; 2716 } 2717 2718 2719 /** 2720 * Send datagram using the socket. 2721 */ 2722 PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock, 2723 pj_ioqueue_op_key_t *send_key, 2724 const void *data, pj_ssize_t *size, 2725 unsigned flags, 2726 const pj_sockaddr_t *addr, int addr_len) 2727 { 2728 PJ_UNUSED_ARG(ssock); 2729 PJ_UNUSED_ARG(send_key); 2730 PJ_UNUSED_ARG(data); 2731 PJ_UNUSED_ARG(size); 2732 PJ_UNUSED_ARG(flags); 2733 PJ_UNUSED_ARG(addr); 2734 PJ_UNUSED_ARG(addr_len); 2735 2736 return PJ_ENOTSUP; 2737 } 2738 2739 /** 2740 * Starts asynchronous socket accept() operations on this secure socket. 2741 */ 2742 PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock, 2743 pj_pool_t *pool, 2744 const pj_sockaddr_t *localaddr, 2745 int addr_len) 2746 { 2747 return pj_ssl_sock_start_accept2(ssock, pool, localaddr, addr_len, 2748 &ssock->param); 2749 } 2750 2751 /** 2752 * Starts asynchronous socket accept() operations on this secure socket. 2753 */ 2754 PJ_DEF(pj_status_t) 2755 pj_ssl_sock_start_accept2 (pj_ssl_sock_t *ssock, 2756 pj_pool_t *pool, 2757 const pj_sockaddr_t *localaddr, 2758 int addr_len, 2759 const pj_ssl_sock_param *newsock_param) 2760 { 2761 pj_activesock_cb asock_cb; 2762 pj_activesock_cfg asock_cfg; 2763 pj_status_t status; 2764 2765 PJ_ASSERT_RETURN(ssock && pool && localaddr && addr_len, PJ_EINVAL); 2766 2767 /* Verify new socket parameters */ 2768 if (newsock_param->grp_lock != ssock->param.grp_lock || 2769 newsock_param->sock_af != ssock->param.sock_af || 2770 newsock_param->sock_type != ssock->param.sock_type) 2771 { 2772 return PJ_EINVAL; 2773 } 2774 2775 /* Create socket */ 2776 status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0, 2777 &ssock->sock); 2778 if (status != PJ_SUCCESS) 2779 goto on_error; 2780 2781 /* Apply SO_REUSEADDR */ 2782 if (ssock->param.reuse_addr) { 2783 int enabled = 1; 2784 status = pj_sock_setsockopt(ssock->sock, pj_SOL_SOCKET(), 2785 pj_SO_REUSEADDR(), 2786 &enabled, sizeof(enabled)); 2787 if (status != PJ_SUCCESS) { 2788 PJ_PERROR(4,(ssock->pool->obj_name, status, 2789 "Warning: error applying SO_REUSEADDR")); 2790 } 2791 } 2792 2793 /* Apply QoS, if specified */ 2794 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, 2795 &ssock->param.qos_params, 2, 2796 ssock->pool->obj_name, NULL); 2797 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) 2798 goto on_error; 2799 2800 /* Bind socket */ 2801 status = pj_sock_bind(ssock->sock, localaddr, addr_len); 2802 if (status != PJ_SUCCESS) 2803 goto on_error; 2804 2805 /* Start listening to the address */ 2806 status = pj_sock_listen(ssock->sock, PJ_SOMAXCONN); 2807 if (status != PJ_SUCCESS) 2808 goto on_error; 2809 2810 /* Create active socket */ 2811 pj_activesock_cfg_default(&asock_cfg); 2812 asock_cfg.async_cnt = ssock->param.async_cnt; 2813 asock_cfg.concurrency = ssock->param.concurrency; 2814 asock_cfg.whole_data = PJ_TRUE; 2815 2816 pj_bzero(&asock_cb, sizeof(asock_cb)); 2817 asock_cb.on_accept_complete = asock_on_accept_complete; 2818 2819 status = pj_activesock_create(pool, 2820 ssock->sock, 2821 ssock->param.sock_type, 2822 &asock_cfg, 2823 ssock->param.ioqueue, 2824 &asock_cb, 2825 ssock, 2826 &ssock->asock); 2827 2828 if (status != PJ_SUCCESS) 2829 goto on_error; 2830 2831 /* Start accepting */ 2832 pj_ssl_sock_param_copy(pool, &ssock->newsock_param, newsock_param); 2833 status = pj_activesock_start_accept(ssock->asock, pool); 2834 if (status != PJ_SUCCESS) 2835 goto on_error; 2836 2837 /* Update local address */ 2838 ssock->addr_len = addr_len; 2839 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 2840 &ssock->addr_len); 2841 if (status != PJ_SUCCESS) 2842 pj_sockaddr_cp(&ssock->local_addr, localaddr); 2843 2844 ssock->is_server = PJ_TRUE; 2845 2846 return PJ_SUCCESS; 2847 2848 on_error: 2849 tls_sock_reset(ssock); 2850 return status; 2851 } 2852 2853 2854 /** 2855 * Starts asynchronous socket connect() operation. 2856 */ 2857 PJ_DEF(pj_status_t) pj_ssl_sock_start_connect( pj_ssl_sock_t *ssock, 2858 pj_pool_t *pool, 2859 const pj_sockaddr_t *localaddr, 2860 const pj_sockaddr_t *remaddr, 2861 int addr_len) 2862 { 2863 pj_activesock_cb asock_cb; 2864 pj_activesock_cfg asock_cfg; 2865 pj_status_t status; 2866 2867 PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len, 2868 PJ_EINVAL); 2869 2870 /* Create socket */ 2871 status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0, 2872 &ssock->sock); 2873 if (status != PJ_SUCCESS) 2874 goto on_error; 2875 2876 /* Apply QoS, if specified */ 2877 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, 2878 &ssock->param.qos_params, 2, 2879 ssock->pool->obj_name, NULL); 2880 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) 2881 goto on_error; 2882 2883 /* Bind socket */ 2884 status = pj_sock_bind(ssock->sock, localaddr, addr_len); 2885 if (status != PJ_SUCCESS) 2886 goto on_error; 2887 2888 /* Create active socket */ 2889 pj_activesock_cfg_default(&asock_cfg); 2890 asock_cfg.async_cnt = ssock->param.async_cnt; 2891 asock_cfg.concurrency = ssock->param.concurrency; 2892 asock_cfg.whole_data = PJ_TRUE; 2893 2894 pj_bzero(&asock_cb, sizeof(asock_cb)); 2895 asock_cb.on_connect_complete = asock_on_connect_complete; 2896 asock_cb.on_data_read = asock_on_data_read; 2897 asock_cb.on_data_sent = asock_on_data_sent; 2898 2899 status = pj_activesock_create(pool, 2900 ssock->sock, 2901 ssock->param.sock_type, 2902 &asock_cfg, 2903 ssock->param.ioqueue, 2904 &asock_cb, 2905 ssock, 2906 &ssock->asock); 2907 2908 if (status != PJ_SUCCESS) 2909 goto on_error; 2910 2911 /* Save remote address */ 2912 pj_sockaddr_cp(&ssock->rem_addr, remaddr); 2913 2914 /* Start timer */ 2915 if (ssock->param.timer_heap && 2916 (ssock->param.timeout.sec != 0 || ssock->param.timeout.msec != 0)) 2917 { 2918 pj_assert(ssock->timer.id == TIMER_NONE); 2919 ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT; 2920 status = pj_timer_heap_schedule(ssock->param.timer_heap, 2921 &ssock->timer, 2922 &ssock->param.timeout); 2923 if (status != PJ_SUCCESS) 2924 ssock->timer.id = TIMER_NONE; 2925 } 2926 2927 status = pj_activesock_start_connect(ssock->asock, pool, remaddr, 2928 addr_len); 2929 2930 if (status == PJ_SUCCESS) 2931 asock_on_connect_complete(ssock->asock, PJ_SUCCESS); 2932 else if (status != PJ_EPENDING) 2933 goto on_error; 2934 2935 /* Update local address */ 2936 ssock->addr_len = addr_len; 2937 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 2938 &ssock->addr_len); 2939 /* Note that we may not get an IP address here. This can 2940 * happen for example on Windows, where getsockname() 2941 * would return 0.0.0.0 if socket has just started the 2942 * async connect. In this case, just leave the local 2943 * address with 0.0.0.0 for now; it will be updated 2944 * once the socket is established. 2945 */ 2946 2947 /* Update socket state */ 2948 ssock->is_server = PJ_FALSE; 2949 2950 return PJ_EPENDING; 2951 2952 on_error: 2953 tls_sock_reset(ssock); 2954 return status; 2955 } 2956 2957 2958 PJ_DEF(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock) 2959 { 1217 static pj_status_t ssl_renegotiate(pj_ssl_sock_t *ssock) 1218 { 1219 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock; 2960 1220 int status; 2961 1221 2962 /* Nothing established yet */2963 PJ_ASSERT_RETURN(ssock->connection_state == TLS_STATE_ESTABLISHED,2964 PJ_EINVALIDOP);2965 2966 /* Cannot renegotiate; we're a client */2967 /* FIXME: in fact maybe that's not true */2968 PJ_ASSERT_RETURN(!ssock->is_server, PJ_EINVALIDOP);2969 2970 1222 /* First call gnutls_rehandshake() to see if this is even possible */ 2971 status = gnutls_rehandshake( ssock->session);1223 status = gnutls_rehandshake(gssock->session); 2972 1224 2973 1225 if (status == GNUTLS_E_SUCCESS) { … … 2980 1232 * renegotiate 2981 1233 */ 2982 ssock->connection_state = TLS_STATE_HANDSHAKING; 2983 status = tls_try_handshake(ssock); 2984 2985 return status; 1234 return PJ_SUCCESS; 2986 1235 } else { 2987 1236 return tls_status_from_err(ssock, status); -
pjproject/trunk/pjlib/src/pj/ssl_sock_ossl.c
r5936 r5938 32 32 #include <pj/timer.h> 33 33 34 35 34 /* Only build when PJ_HAS_SSL_SOCK is enabled and when the backend is 36 35 * OpenSSL. … … 39 38 (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_OPENSSL) 40 39 40 #include "ssl_sock_imp_common.h" 41 #include "ssl_sock_imp_common.c" 42 41 43 #define THIS_FILE "ssl_sock_ossl.c" 42 43 /* Workaround for ticket #985 and #1930 */44 #ifndef PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT45 # define PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT 50046 #endif47 44 48 45 /* … … 164 161 165 162 /* 166 * SSL/TLS state enumeration.167 */168 enum ssl_state {169 SSL_STATE_NULL,170 SSL_STATE_HANDSHAKING,171 SSL_STATE_ESTABLISHED,172 SSL_STATE_ERROR173 };174 175 /*176 * Internal timer types.177 */178 enum timer_id179 {180 TIMER_NONE,181 TIMER_HANDSHAKE_TIMEOUT,182 TIMER_CLOSE183 };184 185 /*186 * Structure of SSL socket read buffer.187 */188 typedef struct read_data_t189 {190 void *data;191 pj_size_t len;192 } read_data_t;193 194 /*195 * Get the offset of pointer to read-buffer of SSL socket from read-buffer196 * of active socket. Note that both SSL socket and active socket employ197 * different but correlated read-buffers (as much as async_cnt for each),198 * and to make it easier/faster to find corresponding SSL socket's read-buffer199 * from known active socket's read-buffer, the pointer of corresponding200 * SSL socket's read-buffer is stored right after the end of active socket's201 * read-buffer.202 */203 #define OFFSET_OF_READ_DATA_PTR(ssock, asock_rbuf) \204 (read_data_t**) \205 ((pj_int8_t*)(asock_rbuf) + \206 ssock->param.read_buffer_size)207 208 /*209 * Structure of SSL socket write data.210 */211 typedef struct write_data_t {212 PJ_DECL_LIST_MEMBER(struct write_data_t);213 pj_ioqueue_op_key_t key;214 pj_size_t record_len;215 pj_ioqueue_op_key_t *app_key;216 pj_size_t plain_data_len;217 pj_size_t data_len;218 unsigned flags;219 union {220 char content[1];221 const char *ptr;222 } data;223 } write_data_t;224 225 /*226 * Structure of SSL socket write buffer (circular buffer).227 */228 typedef struct send_buf_t {229 char *buf;230 pj_size_t max_len;231 char *start;232 pj_size_t len;233 } send_buf_t;234 235 /*236 163 * Secure socket structure definition. 237 164 */ 238 struct pj_ssl_sock_t 239 { 240 pj_pool_t *pool; 241 pj_ssl_sock_t *parent; 242 pj_ssl_sock_param param; 243 pj_ssl_sock_param newsock_param; 244 pj_ssl_cert_t *cert; 245 246 pj_ssl_cert_info local_cert_info; 247 pj_ssl_cert_info remote_cert_info; 248 249 pj_bool_t is_server; 250 enum ssl_state ssl_state; 251 pj_ioqueue_op_key_t handshake_op_key; 252 pj_timer_entry timer; 253 pj_status_t verify_status; 254 255 unsigned long last_err; 256 257 pj_sock_t sock; 258 pj_activesock_t *asock; 259 260 pj_sockaddr local_addr; 261 pj_sockaddr rem_addr; 262 int addr_len; 263 264 pj_bool_t read_started; 265 pj_size_t read_size; 266 pj_uint32_t read_flags; 267 void **asock_rbuf; 268 read_data_t *ssock_rbuf; 269 270 write_data_t write_pending;/* list of pending write to OpenSSL */ 271 write_data_t write_pending_empty; /* cache for write_pending */ 272 pj_bool_t flushing_write_pend; /* flag of flushing is ongoing*/ 273 send_buf_t send_buf; 274 write_data_t send_buf_pending; /* send buffer is full but some 275 * data is queuing in wbio. */ 276 write_data_t send_pending; /* list of pending write to network */ 277 pj_lock_t *write_mutex; /* protect write BIO and send_buf */ 165 typedef struct ossl_sock_t 166 { 167 pj_ssl_sock_t base; 278 168 279 169 SSL_CTX *ossl_ctx; … … 281 171 BIO *ossl_rbio; 282 172 BIO *ossl_wbio; 283 }; 284 285 286 /* 287 * Certificate/credential structure definition. 288 */ 289 struct pj_ssl_cert_t 290 { 291 pj_str_t CA_file; 292 pj_str_t CA_path; 293 pj_str_t cert_file; 294 pj_str_t privkey_file; 295 pj_str_t privkey_pass; 296 297 /* Certificate buffer. */ 298 pj_ssl_cert_buffer CA_buf; 299 pj_ssl_cert_buffer cert_buf; 300 pj_ssl_cert_buffer privkey_buf; 301 }; 302 303 304 static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len); 305 static void free_send_data(pj_ssl_sock_t *ssock, write_data_t *wdata); 306 static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock); 307 308 /* 309 ******************************************************************* 310 * Static/internal functions. 311 ******************************************************************* 312 */ 173 } ossl_sock_t; 313 174 314 175 /** … … 520 381 521 382 383 /* 384 ******************************************************************* 385 * I/O functions. 386 ******************************************************************* 387 */ 388 389 static pj_bool_t io_empty(pj_ssl_sock_t *ssock, circ_buf_t *cb) 390 { 391 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 392 393 return !BIO_pending(ossock->ossl_wbio); 394 } 395 396 static pj_size_t io_size(pj_ssl_sock_t *ssock, circ_buf_t *cb) 397 { 398 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 399 char *data; 400 401 return BIO_get_mem_data(ossock->ossl_wbio, &data); 402 } 403 404 static void io_read(pj_ssl_sock_t *ssock, circ_buf_t *cb, 405 pj_uint8_t *dst, pj_size_t len) 406 { 407 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 408 char *data; 409 410 BIO_get_mem_data(ossock->ossl_wbio, &data); 411 pj_memcpy(dst, data, len); 412 413 /* Reset write BIO */ 414 (void)BIO_reset(ossock->ossl_wbio); 415 } 416 417 static pj_status_t io_write(pj_ssl_sock_t *ssock, circ_buf_t *cb, 418 const pj_uint8_t *src, pj_size_t len) 419 { 420 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 421 int nwritten; 422 423 nwritten = BIO_write(ossock->ossl_rbio, src, (int)len); 424 return (nwritten < (int)len)? GET_SSL_STATUS(cb->owner): PJ_SUCCESS; 425 } 426 427 /* 428 ******************************************************************* 429 */ 430 522 431 /* OpenSSL library initialization counter */ 523 432 static int openssl_init_count; 524 525 /* OpenSSL available ciphers */526 static unsigned openssl_cipher_num;527 static struct openssl_ciphers_t {528 pj_ssl_cipher id;529 const char *name;530 } openssl_ciphers[PJ_SSL_SOCK_MAX_CIPHERS];531 532 /* OpenSSL available curves */533 static unsigned openssl_curves_num;534 static struct openssl_curves_t {535 pj_ssl_curve id;536 const char *name;537 } openssl_curves[PJ_SSL_SOCK_MAX_CURVES];538 433 539 434 /* OpenSSL application data index */ … … 570 465 571 466 /* Init available ciphers */ 572 if ( openssl_cipher_num == 0 || openssl_curves_num == 0) {467 if (ssl_cipher_num == 0 || ssl_curves_num == 0) { 573 468 SSL_METHOD *meth = NULL; 574 469 SSL_CTX *ctx; … … 609 504 610 505 n = sk_SSL_CIPHER_num(sk_cipher); 611 if (n > PJ_ARRAY_SIZE( openssl_ciphers))612 n = PJ_ARRAY_SIZE( openssl_ciphers);506 if (n > PJ_ARRAY_SIZE(ssl_ciphers)) 507 n = PJ_ARRAY_SIZE(ssl_ciphers); 613 508 614 509 for (i = 0; i < n; ++i) { 615 510 const SSL_CIPHER *c; 616 511 c = sk_SSL_CIPHER_value(sk_cipher,i); 617 openssl_ciphers[i].id = (pj_ssl_cipher)512 ssl_ciphers[i].id = (pj_ssl_cipher) 618 513 (pj_uint32_t)SSL_CIPHER_get_id(c) & 619 514 0x00FFFFFF; 620 openssl_ciphers[i].name = SSL_CIPHER_get_name(c);621 } 622 openssl_cipher_num = n;515 ssl_ciphers[i].name = SSL_CIPHER_get_name(c); 516 } 517 ssl_cipher_num = n; 623 518 624 519 SSL_set_session(ssl, SSL_SESSION_new()); … … 626 521 #if !USING_LIBRESSL && !defined(OPENSSL_NO_EC) \ 627 522 && OPENSSL_VERSION_NUMBER >= 0x1000200fL 628 openssl_curves_num = SSL_get_shared_curve(ssl,-1);629 if ( openssl_curves_num > PJ_ARRAY_SIZE(openssl_curves))630 openssl_curves_num = PJ_ARRAY_SIZE(openssl_curves);631 632 for (i = 0; i < openssl_curves_num; i++) {523 ssl_curves_num = SSL_get_shared_curve(ssl,-1); 524 if (ssl_curves_num > PJ_ARRAY_SIZE(ssl_curves)) 525 ssl_curves_num = PJ_ARRAY_SIZE(ssl_curves); 526 527 for (i = 0; i < ssl_curves_num; i++) { 633 528 nid = SSL_get_shared_curve(ssl, i); 634 529 … … 642 537 } 643 538 644 openssl_curves[i].id = get_cid_from_nid(nid);645 openssl_curves[i].name = cname;539 ssl_curves[i].id = get_cid_from_nid(nid); 540 ssl_curves[i].name = cname; 646 541 } 647 542 #else 648 543 PJ_UNUSED_ARG(nid); 649 544 PJ_UNUSED_ARG(cname); 650 openssl_curves_num = 0;545 ssl_curves_num = 0; 651 546 #endif 652 547 … … 788 683 static void set_entropy(pj_ssl_sock_t *ssock); 789 684 685 686 static pj_ssl_sock_t *ssl_alloc(pj_pool_t *pool) 687 { 688 return (pj_ssl_sock_t *)PJ_POOL_ZALLOC_T(pool, ossl_sock_t); 689 } 690 691 790 692 /* Create and initialize new SSL context and instance */ 791 static pj_status_t create_ssl(pj_ssl_sock_t *ssock) 792 { 693 static pj_status_t ssl_create(pj_ssl_sock_t *ssock) 694 { 695 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 793 696 #if !defined(OPENSSL_NO_DH) 794 697 BIO *bio; … … 1142 1045 1143 1046 /* Create SSL instance */ 1144 ssock->ossl_ctx = ctx;1145 ssock->ossl_ssl = SSL_new(ssock->ossl_ctx);1146 if ( ssock->ossl_ssl == NULL) {1047 ossock->ossl_ctx = ctx; 1048 ossock->ossl_ssl = SSL_new(ossock->ossl_ctx); 1049 if (ossock->ossl_ssl == NULL) { 1147 1050 return GET_SSL_STATUS(ssock); 1148 1051 } 1149 1052 1150 1053 /* Set SSL sock as application data of SSL instance */ 1151 SSL_set_ex_data( ssock->ossl_ssl, sslsock_idx, ssock);1054 SSL_set_ex_data(ossock->ossl_ssl, sslsock_idx, ssock); 1152 1055 1153 1056 /* SSL verification options */ … … 1156 1059 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; 1157 1060 1158 SSL_set_verify( ssock->ossl_ssl, mode, &verify_cb);1061 SSL_set_verify(ossock->ossl_ssl, mode, &verify_cb); 1159 1062 1160 1063 /* Set cipher list */ … … 1174 1077 1175 1078 /* Setup SSL BIOs */ 1176 ssock->ossl_rbio = BIO_new(BIO_s_mem());1177 ssock->ossl_wbio = BIO_new(BIO_s_mem());1178 (void)BIO_set_close( ssock->ossl_rbio, BIO_CLOSE);1179 (void)BIO_set_close( ssock->ossl_wbio, BIO_CLOSE);1180 SSL_set_bio( ssock->ossl_ssl, ssock->ossl_rbio,ssock->ossl_wbio);1079 ossock->ossl_rbio = BIO_new(BIO_s_mem()); 1080 ossock->ossl_wbio = BIO_new(BIO_s_mem()); 1081 (void)BIO_set_close(ossock->ossl_rbio, BIO_CLOSE); 1082 (void)BIO_set_close(ossock->ossl_wbio, BIO_CLOSE); 1083 SSL_set_bio(ossock->ossl_ssl, ossock->ossl_rbio, ossock->ossl_wbio); 1181 1084 1182 1085 return PJ_SUCCESS; … … 1185 1088 1186 1089 /* Destroy SSL context and instance */ 1187 static void destroy_ssl(pj_ssl_sock_t *ssock) 1188 { 1090 static void ssl_destroy(pj_ssl_sock_t *ssock) 1091 { 1092 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1093 1189 1094 /* Destroy SSL instance */ 1190 if ( ssock->ossl_ssl) {1095 if (ossock->ossl_ssl) { 1191 1096 /** 1192 1097 * Avoid calling SSL_shutdown() if handshake wasn't completed. … … 1194 1099 * SSL handshake, while previous versions always return 0. 1195 1100 */ 1196 if (SSL_in_init( ssock->ossl_ssl) == 0) {1197 SSL_shutdown( ssock->ossl_ssl);1101 if (SSL_in_init(ossock->ossl_ssl) == 0) { 1102 SSL_shutdown(ossock->ossl_ssl); 1198 1103 } 1199 SSL_free( ssock->ossl_ssl); /* this will also close BIOs */1200 ssock->ossl_ssl = NULL;1104 SSL_free(ossock->ossl_ssl); /* this will also close BIOs */ 1105 ossock->ossl_ssl = NULL; 1201 1106 } 1202 1107 1203 1108 /* Destroy SSL context */ 1204 if ( ssock->ossl_ctx) {1205 SSL_CTX_free( ssock->ossl_ctx);1206 ssock->ossl_ctx = NULL;1109 if (ossock->ossl_ctx) { 1110 SSL_CTX_free(ossock->ossl_ctx); 1111 ossock->ossl_ctx = NULL; 1207 1112 } 1208 1113 … … 1214 1119 1215 1120 1216 /* Close sockets */1217 static void close_sockets(pj_ssl_sock_t *ssock)1218 {1219 pj_activesock_t *asock;1220 pj_sock_t sock;1221 1222 /* This can happen when pj_ssl_sock_create() fails. */1223 if (!ssock->write_mutex)1224 return;1225 1226 pj_lock_acquire(ssock->write_mutex);1227 asock = ssock->asock;1228 if (asock) {1229 // Don't set ssock->asock to NULL, as it may trigger assertion in1230 // send operation. This should be safe as active socket will simply1231 // return PJ_EINVALIDOP on any operation if it is already closed.1232 //ssock->asock = NULL;1233 ssock->sock = PJ_INVALID_SOCKET;1234 }1235 sock = ssock->sock;1236 if (sock != PJ_INVALID_SOCKET)1237 ssock->sock = PJ_INVALID_SOCKET;1238 pj_lock_release(ssock->write_mutex);1239 1240 if (asock)1241 pj_activesock_close(asock);1242 1243 if (sock != PJ_INVALID_SOCKET)1244 pj_sock_close(sock);1245 }1246 1247 1248 1121 /* Reset SSL socket state */ 1249 static void reset_ssl_sock_state(pj_ssl_sock_t *ssock)1122 static void ssl_reset_sock_state(pj_ssl_sock_t *ssock) 1250 1123 { 1251 1124 pj_lock_acquire(ssock->write_mutex); … … 1253 1126 pj_lock_release(ssock->write_mutex); 1254 1127 1255 close_sockets(ssock);1128 ssl_close_sockets(ssock); 1256 1129 1257 1130 /* Upon error, OpenSSL may leave any error description in the thread … … 1265 1138 1266 1139 1140 static void ssl_ciphers_populate() 1141 { 1142 if (ssl_cipher_num == 0 || ssl_curves_num == 0) { 1143 init_openssl(); 1144 shutdown_openssl(); 1145 } 1146 } 1147 1148 static pj_ssl_cipher ssl_get_cipher(pj_ssl_sock_t *ssock) 1149 { 1150 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1151 const SSL_CIPHER *cipher; 1152 1153 /* Current cipher */ 1154 cipher = SSL_get_current_cipher(ossock->ossl_ssl); 1155 if (cipher) { 1156 return (SSL_CIPHER_get_id(cipher) & 0x00FFFFFF); 1157 } else { 1158 return PJ_TLS_UNKNOWN_CIPHER; 1159 } 1160 } 1161 1267 1162 /* Generate cipher list with user preference order in OpenSSL format */ 1268 1163 static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock) 1269 1164 { 1165 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1270 1166 pj_pool_t *tmp_pool = NULL; 1271 1167 char *buf = NULL; … … 1277 1173 1278 1174 if (ssock->param.ciphers_num == 0) { 1279 ret = SSL_set_cipher_list( ssock->ossl_ssl, PJ_SSL_SOCK_OSSL_CIPHERS);1175 ret = SSL_set_cipher_list(ossock->ossl_ssl, PJ_SSL_SOCK_OSSL_CIPHERS); 1280 1176 if (ret < 1) { 1281 1177 return GET_SSL_STATUS(ssock); … … 1296 1192 1297 1193 /* Set SSL with ALL available ciphers */ 1298 SSL_set_cipher_list( ssock->ossl_ssl, "ALL:COMPLEMENTOFALL");1194 SSL_set_cipher_list(ossock->ossl_ssl, "ALL:COMPLEMENTOFALL"); 1299 1195 1300 1196 /* Generate user specified cipher list in OpenSSL format */ 1301 sk_cipher = SSL_get_ciphers( ssock->ossl_ssl);1197 sk_cipher = SSL_get_ciphers(ossock->ossl_ssl); 1302 1198 for (i = 0; i < ssock->param.ciphers_num; ++i) { 1303 1199 for (j = 0; j < sk_SSL_CIPHER_num(sk_cipher); ++j) { … … 1335 1231 1336 1232 /* Finally, set chosen cipher list */ 1337 ret = SSL_set_cipher_list( ssock->ossl_ssl, buf);1233 ret = SSL_set_cipher_list(ossock->ossl_ssl, buf); 1338 1234 if (ret < 1) { 1339 1235 pj_pool_release(tmp_pool); … … 1349 1245 #if !USING_LIBRESSL && !defined(OPENSSL_NO_EC) \ 1350 1246 && OPENSSL_VERSION_NUMBER >= 0x1000200fL 1247 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1351 1248 int ret; 1352 1249 int curves[PJ_SSL_SOCK_MAX_CURVES]; … … 1360 1257 } 1361 1258 1362 if( SSL_is_server( ssock->ossl_ssl) ) {1363 ret = SSL_set1_curves( ssock->ossl_ssl, curves,1259 if( SSL_is_server(ossock->ossl_ssl) ) { 1260 ret = SSL_set1_curves(ossock->ossl_ssl, curves, 1364 1261 ssock->param.curves_num); 1365 1262 if (ret < 1) 1366 1263 return GET_SSL_STATUS(ssock); 1367 1264 } else { 1368 ret = SSL_CTX_set1_curves( ssock->ossl_ctx, curves,1265 ret = SSL_CTX_set1_curves(ossock->ossl_ctx, curves, 1369 1266 ssock->param.curves_num); 1370 1267 if (ret < 1) … … 1380 1277 { 1381 1278 #if !USING_LIBRESSL && OPENSSL_VERSION_NUMBER >= 0x1000200fL 1279 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1382 1280 int ret; 1383 1281 1384 1282 if (ssock->param.sigalgs.ptr && ssock->param.sigalgs.slen) { 1385 1283 if (ssock->is_server) { 1386 ret = SSL_set1_client_sigalgs_list( ssock->ossl_ssl,1284 ret = SSL_set1_client_sigalgs_list(ossock->ossl_ssl, 1387 1285 ssock->param.sigalgs.ptr); 1388 1286 } else { 1389 ret = SSL_set1_sigalgs_list( ssock->ossl_ssl,1287 ret = SSL_set1_sigalgs_list(ossock->ossl_ssl, 1390 1288 ssock->param.sigalgs.ptr); 1391 1289 } … … 1654 1552 * called after handshake or renegotiation successfully completed. 1655 1553 */ 1656 static void update_certs_info(pj_ssl_sock_t *ssock) 1657 { 1554 static void ssl_update_certs_info(pj_ssl_sock_t *ssock) 1555 { 1556 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1658 1557 X509 *x; 1659 1558 … … 1661 1560 1662 1561 /* Active local certificate */ 1663 x = SSL_get_certificate( ssock->ossl_ssl);1562 x = SSL_get_certificate(ossock->ossl_ssl); 1664 1563 if (x) { 1665 1564 get_cert_info(ssock->pool, &ssock->local_cert_info, x, PJ_FALSE); … … 1670 1569 1671 1570 /* Active remote certificate */ 1672 x = SSL_get_peer_certificate( ssock->ossl_ssl);1571 x = SSL_get_peer_certificate(ossock->ossl_ssl); 1673 1572 if (x) { 1674 1573 get_cert_info(ssock->pool, &ssock->remote_cert_info, x, PJ_TRUE); … … 1681 1580 1682 1581 1683 /* When handshake completed:1684 * - notify application1685 * - if handshake failed, reset SSL state1686 * - return PJ_FALSE when SSL socket instance is destroyed by application.1687 */1688 static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock,1689 pj_status_t status)1690 {1691 /* Cancel handshake timer */1692 if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) {1693 pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);1694 ssock->timer.id = TIMER_NONE;1695 }1696 1697 /* Update certificates info on successful handshake */1698 if (status == PJ_SUCCESS)1699 update_certs_info(ssock);1700 1701 /* Accepting */1702 if (ssock->is_server) {1703 if (status != PJ_SUCCESS) {1704 /* Handshake failed in accepting, destroy our self silently. */1705 1706 char errmsg[PJ_ERR_MSG_SIZE];1707 char buf[PJ_INET6_ADDRSTRLEN+10];1708 1709 pj_strerror(status, errmsg, sizeof(errmsg));1710 PJ_LOG(3,(ssock->pool->obj_name, "Handshake failed in accepting "1711 "%s: %s",1712 pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3),1713 errmsg));1714 1715 if (ssock->param.cb.on_accept_complete2) {1716 (*ssock->param.cb.on_accept_complete2)1717 (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,1718 pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr),1719 status);1720 }1721 1722 /* Originally, this is a workaround for ticket #985. However,1723 * a race condition may occur in multiple worker threads1724 * environment when we are destroying SSL objects while other1725 * threads are still accessing them.1726 * Please see ticket #1930 for more info.1727 */1728 #if 1 //(defined(PJ_WIN32) && PJ_WIN32!=0)||(defined(PJ_WIN64) && PJ_WIN64!=0)1729 if (ssock->param.timer_heap) {1730 pj_time_val interval = {0, PJ_SSL_SOCK_DELAYED_CLOSE_TIMEOUT};1731 1732 ssock->ssl_state = SSL_STATE_NULL;1733 close_sockets(ssock);1734 1735 if (ssock->timer.id != TIMER_NONE) {1736 pj_timer_heap_cancel(ssock->param.timer_heap,1737 &ssock->timer);1738 }1739 ssock->timer.id = TIMER_CLOSE;1740 pj_time_val_normalize(&interval);1741 if (pj_timer_heap_schedule(ssock->param.timer_heap,1742 &ssock->timer, &interval) != 0)1743 {1744 PJ_LOG(3,(ssock->pool->obj_name, "Failed to schedule "1745 "a delayed close. Race condition may occur."));1746 ssock->timer.id = TIMER_NONE;1747 pj_ssl_sock_close(ssock);1748 }1749 } else {1750 pj_ssl_sock_close(ssock);1751 }1752 #else1753 {1754 pj_ssl_sock_close(ssock);1755 }1756 #endif1757 1758 return PJ_FALSE;1759 }1760 /* Notify application the newly accepted SSL socket */1761 if (ssock->param.cb.on_accept_complete2) {1762 pj_bool_t ret;1763 ret = (*ssock->param.cb.on_accept_complete2)1764 (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,1765 pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr),1766 status);1767 if (ret == PJ_FALSE)1768 return PJ_FALSE;1769 } else if (ssock->param.cb.on_accept_complete) {1770 pj_bool_t ret;1771 ret = (*ssock->param.cb.on_accept_complete)1772 (ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,1773 pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr));1774 if (ret == PJ_FALSE)1775 return PJ_FALSE;1776 }1777 }1778 1779 /* Connecting */1780 else {1781 /* On failure, reset SSL socket state first, as app may try to1782 * reconnect in the callback.1783 */1784 if (status != PJ_SUCCESS) {1785 /* Server disconnected us, possibly due to SSL nego failure */1786 if (status == PJ_EEOF) {1787 unsigned long err;1788 err = ERR_get_error();1789 if (err != SSL_ERROR_NONE)1790 status = STATUS_FROM_SSL_ERR("connecting", ssock, err);1791 }1792 reset_ssl_sock_state(ssock);1793 }1794 if (ssock->param.cb.on_connect_complete) {1795 pj_bool_t ret;1796 ret = (*ssock->param.cb.on_connect_complete)(ssock, status);1797 if (ret == PJ_FALSE)1798 return PJ_FALSE;1799 }1800 }1801 1802 return PJ_TRUE;1803 }1804 1805 static write_data_t* alloc_send_data(pj_ssl_sock_t *ssock, pj_size_t len)1806 {1807 send_buf_t *send_buf = &ssock->send_buf;1808 pj_size_t avail_len, skipped_len = 0;1809 char *reg1, *reg2;1810 pj_size_t reg1_len, reg2_len;1811 write_data_t *p;1812 1813 /* Check buffer availability */1814 avail_len = send_buf->max_len - send_buf->len;1815 if (avail_len < len)1816 return NULL;1817 1818 /* If buffer empty, reset start pointer and return it */1819 if (send_buf->len == 0) {1820 send_buf->start = send_buf->buf;1821 send_buf->len = len;1822 p = (write_data_t*)send_buf->start;1823 goto init_send_data;1824 }1825 1826 /* Free space may be wrapped/splitted into two regions, so let's1827 * analyze them if any region can hold the write data.1828 */1829 reg1 = send_buf->start + send_buf->len;1830 if (reg1 >= send_buf->buf + send_buf->max_len)1831 reg1 -= send_buf->max_len;1832 reg1_len = send_buf->max_len - send_buf->len;1833 if (reg1 + reg1_len > send_buf->buf + send_buf->max_len) {1834 reg1_len = send_buf->buf + send_buf->max_len - reg1;1835 reg2 = send_buf->buf;1836 reg2_len = send_buf->start - send_buf->buf;1837 } else {1838 reg2 = NULL;1839 reg2_len = 0;1840 }1841 1842 /* More buffer availability check, note that the write data must be in1843 * a contigue buffer.1844 */1845 avail_len = PJ_MAX(reg1_len, reg2_len);1846 if (avail_len < len)1847 return NULL;1848 1849 /* Get the data slot */1850 if (reg1_len >= len) {1851 p = (write_data_t*)reg1;1852 } else {1853 p = (write_data_t*)reg2;1854 skipped_len = reg1_len;1855 }1856 1857 /* Update buffer length */1858 send_buf->len += len + skipped_len;1859 1860 init_send_data:1861 /* Init the new send data */1862 pj_bzero(p, sizeof(*p));1863 pj_list_init(p);1864 pj_list_push_back(&ssock->send_pending, p);1865 1866 return p;1867 }1868 1869 static void free_send_data(pj_ssl_sock_t *ssock, write_data_t *wdata)1870 {1871 send_buf_t *buf = &ssock->send_buf;1872 write_data_t *spl = &ssock->send_pending;1873 1874 pj_assert(!pj_list_empty(&ssock->send_pending));1875 1876 /* Free slot from the buffer */1877 if (spl->next == wdata && spl->prev == wdata) {1878 /* This is the only data, reset the buffer */1879 buf->start = buf->buf;1880 buf->len = 0;1881 } else if (spl->next == wdata) {1882 /* This is the first data, shift start pointer of the buffer and1883 * adjust the buffer length.1884 */1885 buf->start = (char*)wdata->next;1886 if (wdata->next > wdata) {1887 buf->len -= ((char*)wdata->next - buf->start);1888 } else {1889 /* Overlapped */1890 pj_size_t right_len, left_len;1891 right_len = buf->buf + buf->max_len - (char*)wdata;1892 left_len = (char*)wdata->next - buf->buf;1893 buf->len -= (right_len + left_len);1894 }1895 } else if (spl->prev == wdata) {1896 /* This is the last data, just adjust the buffer length */1897 if (wdata->prev < wdata) {1898 pj_size_t jump_len;1899 jump_len = (char*)wdata -1900 ((char*)wdata->prev + wdata->prev->record_len);1901 buf->len -= (wdata->record_len + jump_len);1902 } else {1903 /* Overlapped */1904 pj_size_t right_len, left_len;1905 right_len = buf->buf + buf->max_len -1906 ((char*)wdata->prev + wdata->prev->record_len);1907 left_len = (char*)wdata + wdata->record_len - buf->buf;1908 buf->len -= (right_len + left_len);1909 }1910 }1911 /* For data in the middle buffer, just do nothing on the buffer. The slot1912 * will be freed later when freeing the first/last data.1913 */1914 1915 /* Remove the data from send pending list */1916 pj_list_erase(wdata);1917 }1918 1919 #if 01920 /* Just for testing send buffer alloc/free */1921 #include <pj/rand.h>1922 pj_status_t pj_ssl_sock_ossl_test_send_buf(pj_pool_t *pool)1923 {1924 enum { MAX_CHUNK_NUM = 20 };1925 unsigned chunk_size, chunk_cnt, i;1926 write_data_t *wdata[MAX_CHUNK_NUM] = {0};1927 pj_time_val now;1928 pj_ssl_sock_t *ssock = NULL;1929 pj_ssl_sock_param param;1930 pj_status_t status;1931 1932 pj_gettimeofday(&now);1933 pj_srand((unsigned)now.sec);1934 1935 pj_ssl_sock_param_default(¶m);1936 status = pj_ssl_sock_create(pool, ¶m, &ssock);1937 if (status != PJ_SUCCESS) {1938 return status;1939 }1940 1941 if (ssock->send_buf.max_len == 0) {1942 ssock->send_buf.buf = (char*)1943 pj_pool_alloc(ssock->pool,1944 ssock->param.send_buffer_size);1945 ssock->send_buf.max_len = ssock->param.send_buffer_size;1946 ssock->send_buf.start = ssock->send_buf.buf;1947 ssock->send_buf.len = 0;1948 }1949 1950 chunk_size = ssock->param.send_buffer_size / MAX_CHUNK_NUM / 2;1951 chunk_cnt = 0;1952 for (i = 0; i < MAX_CHUNK_NUM; i++) {1953 wdata[i] = alloc_send_data(ssock, pj_rand() % chunk_size + 321);1954 if (wdata[i])1955 chunk_cnt++;1956 else1957 break;1958 }1959 1960 while (chunk_cnt) {1961 i = pj_rand() % MAX_CHUNK_NUM;1962 if (wdata[i]) {1963 free_send_data(ssock, wdata[i]);1964 wdata[i] = NULL;1965 chunk_cnt--;1966 }1967 }1968 1969 if (ssock->send_buf.len != 0)1970 status = PJ_EBUG;1971 1972 pj_ssl_sock_close(ssock);1973 return status;1974 }1975 #endif1976 1977 1978 1582 /* Flush write BIO to network socket. Note that any access to write BIO 1979 1583 * MUST be serialized, so mutex protection must cover any call to OpenSSL … … 1982 1586 * OpenSSL API call). 1983 1587 */ 1984 static pj_status_t flush_write_bio(pj_ssl_sock_t *ssock, 1985 pj_ioqueue_op_key_t *send_key, 1986 pj_size_t orig_len, 1987 unsigned flags) 1988 { 1989 char *data; 1990 pj_ssize_t len; 1991 write_data_t *wdata; 1992 pj_size_t needed_len; 1993 pj_status_t status; 1994 1995 pj_lock_acquire(ssock->write_mutex); 1996 1997 /* Check if there is data in write BIO, flush it if any */ 1998 if (!BIO_pending(ssock->ossl_wbio)) { 1999 pj_lock_release(ssock->write_mutex); 2000 return PJ_SUCCESS; 2001 } 2002 2003 /* Get data and its length */ 2004 len = BIO_get_mem_data(ssock->ossl_wbio, &data); 2005 if (len == 0) { 2006 pj_lock_release(ssock->write_mutex); 2007 return PJ_SUCCESS; 2008 } 2009 2010 /* Calculate buffer size needed, and align it to 8 */ 2011 needed_len = len + sizeof(write_data_t); 2012 needed_len = ((needed_len + 7) >> 3) << 3; 2013 2014 /* Allocate buffer for send data */ 2015 wdata = alloc_send_data(ssock, needed_len); 2016 if (wdata == NULL) { 2017 /* Oops, write BIO is ready but the send buffer is full, let's just 2018 * queue it for sending and return PJ_EPENDING. 2019 */ 2020 ssock->send_buf_pending.data_len = needed_len; 2021 ssock->send_buf_pending.app_key = send_key; 2022 ssock->send_buf_pending.flags = flags; 2023 ssock->send_buf_pending.plain_data_len = orig_len; 2024 pj_lock_release(ssock->write_mutex); 2025 return PJ_EPENDING; 2026 } 2027 2028 /* Copy the data and set its properties into the send data */ 2029 pj_ioqueue_op_key_init(&wdata->key, sizeof(pj_ioqueue_op_key_t)); 2030 wdata->key.user_data = wdata; 2031 wdata->app_key = send_key; 2032 wdata->record_len = needed_len; 2033 wdata->data_len = len; 2034 wdata->plain_data_len = orig_len; 2035 wdata->flags = flags; 2036 pj_memcpy(&wdata->data, data, len); 2037 2038 /* Reset write BIO */ 2039 (void)BIO_reset(ssock->ossl_wbio); 2040 2041 /* Ticket #1573: Don't hold mutex while calling PJLIB socket send(). */ 2042 pj_lock_release(ssock->write_mutex); 2043 2044 /* Send it */ 2045 if (ssock->param.sock_type == pj_SOCK_STREAM()) { 2046 status = pj_activesock_send(ssock->asock, &wdata->key, 2047 wdata->data.content, &len, 2048 flags); 1588 static pj_status_t flush_circ_buf_output(pj_ssl_sock_t *ssock, 1589 pj_ioqueue_op_key_t *send_key, 1590 pj_size_t orig_len, unsigned flags); 1591 1592 1593 static void ssl_set_state(pj_ssl_sock_t *ssock, pj_bool_t is_server) 1594 { 1595 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1596 if (is_server) { 1597 SSL_set_accept_state(ossock->ossl_ssl); 2049 1598 } else { 2050 status = pj_activesock_sendto(ssock->asock, &wdata->key, 2051 wdata->data.content, &len, 2052 flags, 2053 (pj_sockaddr_t*)&ssock->rem_addr, 2054 ssock->addr_len); 2055 } 2056 2057 if (status != PJ_EPENDING) { 2058 /* When the sending is not pending, remove the wdata from send 2059 * pending list. 2060 */ 2061 pj_lock_acquire(ssock->write_mutex); 2062 free_send_data(ssock, wdata); 2063 pj_lock_release(ssock->write_mutex); 2064 } 2065 2066 return status; 2067 } 2068 2069 2070 static void on_timer(pj_timer_heap_t *th, struct pj_timer_entry *te) 2071 { 2072 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)te->user_data; 2073 int timer_id = te->id; 2074 2075 te->id = TIMER_NONE; 2076 2077 PJ_UNUSED_ARG(th); 2078 2079 switch (timer_id) { 2080 case TIMER_HANDSHAKE_TIMEOUT: 2081 PJ_LOG(1,(ssock->pool->obj_name, "SSL timeout after %d.%ds", 2082 ssock->param.timeout.sec, ssock->param.timeout.msec)); 2083 2084 on_handshake_complete(ssock, PJ_ETIMEDOUT); 2085 break; 2086 case TIMER_CLOSE: 2087 pj_ssl_sock_close(ssock); 2088 break; 2089 default: 2090 pj_assert(!"Unknown timer"); 2091 break; 2092 } 1599 SSL_set_connect_state(ossock->ossl_ssl); 1600 } 1601 } 1602 1603 1604 static void ssl_set_peer_name(pj_ssl_sock_t *ssock) 1605 { 1606 #ifdef SSL_set_tlsext_host_name 1607 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1608 1609 /* Set server name to connect */ 1610 if (ssock->param.server_name.slen) { 1611 /* Server name is null terminated already */ 1612 if (!SSL_set_tlsext_host_name(ossock->ossl_ssl, 1613 ssock->param.server_name.ptr)) 1614 { 1615 char err_str[PJ_ERR_MSG_SIZE]; 1616 1617 ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str)); 1618 PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() " 1619 "failed: %s", err_str)); 1620 } 1621 } 1622 #endif 2093 1623 } 2094 1624 2095 1625 2096 1626 /* Asynchronouse handshake */ 2097 static pj_status_t do_handshake(pj_ssl_sock_t *ssock) 2098 { 1627 static pj_status_t ssl_do_handshake(pj_ssl_sock_t *ssock) 1628 { 1629 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 2099 1630 pj_status_t status; 2100 1631 int err; … … 2102 1633 /* Perform SSL handshake */ 2103 1634 pj_lock_acquire(ssock->write_mutex); 2104 err = SSL_do_handshake( ssock->ossl_ssl);1635 err = SSL_do_handshake(ossock->ossl_ssl); 2105 1636 pj_lock_release(ssock->write_mutex); 2106 1637 … … 2108 1639 * flush it if any. 2109 1640 */ 2110 status = flush_ write_bio(ssock, &ssock->handshake_op_key, 0, 0);1641 status = flush_circ_buf_output(ssock, &ssock->handshake_op_key, 0, 0); 2111 1642 if (status != PJ_SUCCESS && status != PJ_EPENDING) { 2112 1643 return status; … … 2114 1645 2115 1646 if (err < 0) { 2116 int err2 = SSL_get_error( ssock->ossl_ssl, err);1647 int err2 = SSL_get_error(ossock->ossl_ssl, err); 2117 1648 if (err2 != SSL_ERROR_NONE && err2 != SSL_ERROR_WANT_READ) 2118 1649 { … … 2124 1655 2125 1656 /* Check if handshake has been completed */ 2126 if (SSL_is_init_finished( ssock->ossl_ssl)) {1657 if (SSL_is_init_finished(ossock->ossl_ssl)) { 2127 1658 ssock->ssl_state = SSL_STATE_ESTABLISHED; 2128 1659 return PJ_SUCCESS; … … 2132 1663 } 2133 1664 2134 static void ssl_on_destroy(void *arg) 2135 { 2136 pj_pool_t *pool = NULL; 2137 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)arg; 2138 2139 destroy_ssl(ssock); 2140 2141 pj_lock_destroy(ssock->write_mutex); 2142 2143 pool = ssock->pool; 2144 ssock->pool = NULL; 2145 if (pool) 2146 pj_pool_release(pool); 2147 } 2148 2149 2150 /* 2151 ******************************************************************* 2152 * Active socket callbacks. 2153 ******************************************************************* 2154 */ 2155 2156 static pj_bool_t asock_on_data_read (pj_activesock_t *asock, 2157 void *data, 2158 pj_size_t size, 2159 pj_status_t status, 2160 pj_size_t *remainder) 2161 { 2162 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) 2163 pj_activesock_get_user_data(asock); 2164 pj_size_t nwritten; 2165 2166 /* Socket error or closed */ 2167 if (data && size > 0) { 2168 /* Consume the whole data */ 2169 nwritten = BIO_write(ssock->ossl_rbio, data, (int)size); 2170 if (nwritten < size) { 2171 status = GET_SSL_STATUS(ssock); 2172 goto on_error; 2173 } 2174 } 2175 2176 /* Check if SSL handshake hasn't finished yet */ 2177 if (ssock->ssl_state == SSL_STATE_HANDSHAKING) { 2178 pj_bool_t ret = PJ_TRUE; 2179 2180 if (status == PJ_SUCCESS) 2181 status = do_handshake(ssock); 2182 2183 /* Not pending is either success or failed */ 2184 if (status != PJ_EPENDING) 2185 ret = on_handshake_complete(ssock, status); 2186 2187 return ret; 2188 } 2189 2190 /* See if there is any decrypted data for the application */ 2191 if (ssock->read_started) { 2192 do { 2193 read_data_t *buf = *(OFFSET_OF_READ_DATA_PTR(ssock, data)); 2194 void *data_ = (pj_int8_t*)buf->data + buf->len; 2195 int size_ = (int)(ssock->read_size - buf->len); 2196 int len = size_; 2197 2198 /* SSL_read() may write some data to BIO write when re-negotiation 2199 * is on progress, so let's protect it with write mutex. 2200 */ 2201 pj_lock_acquire(ssock->write_mutex); 2202 size_ = SSL_read(ssock->ossl_ssl, data_, size_); 2203 pj_lock_release(ssock->write_mutex); 2204 2205 if (size_ > 0 || status != PJ_SUCCESS) { 2206 if (ssock->param.cb.on_data_read) { 2207 pj_bool_t ret; 2208 pj_size_t remainder_ = 0; 2209 2210 if (size_ > 0) 2211 buf->len += size_; 2212 2213 if (status != PJ_SUCCESS) { 2214 ssock->ssl_state = SSL_STATE_ERROR; 2215 } 2216 2217 ret = (*ssock->param.cb.on_data_read)(ssock, buf->data, 2218 buf->len, status, 2219 &remainder_); 2220 if (!ret) { 2221 /* We've been destroyed */ 2222 return PJ_FALSE; 2223 } 2224 2225 /* Application may have left some data to be consumed 2226 * later. 2227 */ 2228 buf->len = remainder_; 2229 } 2230 2231 /* Active socket signalled connection closed/error, this has 2232 * been signalled to the application along with any remaining 2233 * buffer. So, let's just reset SSL socket now. 2234 */ 2235 if (status != PJ_SUCCESS) { 2236 reset_ssl_sock_state(ssock); 2237 return PJ_FALSE; 2238 } 2239 2240 } else { 2241 2242 int err = SSL_get_error(ssock->ossl_ssl, size_); 2243 2244 /* SSL might just return SSL_ERROR_WANT_READ in 2245 * re-negotiation. 2246 */ 2247 if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ) 2248 { 2249 if (err == SSL_ERROR_SYSCALL && size_ == -1 && 2250 ERR_peek_error() == 0 && errno == 0) 2251 { 2252 status = STATUS_FROM_SSL_ERR2("Read", ssock, size_, 2253 err, len); 2254 PJ_LOG(4,("SSL", "SSL_read() = -1, with " 2255 "SSL_ERROR_SYSCALL, no SSL error, " 2256 "and errno = 0 - skip BIO error")); 2257 /* Ignore these errors */ 2258 } else { 2259 /* Reset SSL socket state, then return PJ_FALSE */ 2260 status = STATUS_FROM_SSL_ERR2("Read", ssock, size_, 2261 err, len); 2262 reset_ssl_sock_state(ssock); 2263 goto on_error; 2264 } 2265 } 2266 2267 status = do_handshake(ssock); 2268 if (status == PJ_SUCCESS) { 2269 /* Renegotiation completed */ 2270 2271 /* Update certificates */ 2272 update_certs_info(ssock); 2273 2274 // Ticket #1573: Don't hold mutex while calling 2275 // PJLIB socket send(). 2276 //pj_lock_acquire(ssock->write_mutex); 2277 status = flush_delayed_send(ssock); 2278 //pj_lock_release(ssock->write_mutex); 2279 2280 /* If flushing is ongoing, treat it as success */ 2281 if (status == PJ_EBUSY) 2282 status = PJ_SUCCESS; 2283 2284 if (status != PJ_SUCCESS && status != PJ_EPENDING) { 2285 PJ_PERROR(1,(ssock->pool->obj_name, status, 2286 "Failed to flush delayed send")); 2287 goto on_error; 2288 } 2289 } else if (status != PJ_EPENDING) { 2290 PJ_PERROR(1,(ssock->pool->obj_name, status, 2291 "Renegotiation failed")); 2292 goto on_error; 2293 } 2294 2295 break; 2296 } 2297 } while (1); 2298 } 2299 2300 return PJ_TRUE; 2301 2302 on_error: 2303 if (ssock->ssl_state == SSL_STATE_HANDSHAKING) 2304 return on_handshake_complete(ssock, status); 2305 2306 if (ssock->read_started && ssock->param.cb.on_data_read) { 2307 pj_bool_t ret; 2308 ret = (*ssock->param.cb.on_data_read)(ssock, NULL, 0, status, 2309 remainder); 2310 if (!ret) { 2311 /* We've been destroyed */ 2312 return PJ_FALSE; 2313 } 2314 } 2315 2316 reset_ssl_sock_state(ssock); 2317 return PJ_FALSE; 2318 } 2319 2320 2321 static pj_bool_t asock_on_data_sent (pj_activesock_t *asock, 2322 pj_ioqueue_op_key_t *send_key, 2323 pj_ssize_t sent) 2324 { 2325 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) 2326 pj_activesock_get_user_data(asock); 2327 write_data_t *wdata = (write_data_t*)send_key->user_data; 2328 pj_ioqueue_op_key_t *app_key = wdata->app_key; 2329 pj_ssize_t sent_len; 2330 2331 sent_len = (sent > 0)? wdata->plain_data_len : sent; 2332 2333 /* Update write buffer state */ 2334 pj_lock_acquire(ssock->write_mutex); 2335 free_send_data(ssock, wdata); 2336 pj_lock_release(ssock->write_mutex); 2337 wdata = NULL; 2338 2339 if (ssock->ssl_state == SSL_STATE_HANDSHAKING) { 2340 /* Initial handshaking */ 2341 pj_status_t status; 2342 2343 status = do_handshake(ssock); 2344 /* Not pending is either success or failed */ 2345 if (status != PJ_EPENDING) 2346 return on_handshake_complete(ssock, status); 2347 2348 } else if (send_key != &ssock->handshake_op_key) { 2349 /* Some data has been sent, notify application */ 2350 if (ssock->param.cb.on_data_sent) { 2351 pj_bool_t ret; 2352 ret = (*ssock->param.cb.on_data_sent)(ssock, app_key, 2353 sent_len); 2354 if (!ret) { 2355 /* We've been destroyed */ 2356 return PJ_FALSE; 2357 } 2358 } 2359 } else { 2360 /* SSL re-negotiation is on-progress, just do nothing */ 2361 } 2362 2363 /* Send buffer has been updated, let's try to send any pending data */ 2364 if (ssock->send_buf_pending.data_len) { 2365 pj_status_t status; 2366 status = flush_write_bio(ssock, ssock->send_buf_pending.app_key, 2367 ssock->send_buf_pending.plain_data_len, 2368 ssock->send_buf_pending.flags); 2369 if (status == PJ_SUCCESS || status == PJ_EPENDING) { 2370 ssock->send_buf_pending.data_len = 0; 2371 } 2372 } 2373 2374 return PJ_TRUE; 2375 } 2376 2377 2378 static pj_bool_t asock_on_accept_complete (pj_activesock_t *asock, 2379 pj_sock_t newsock, 2380 const pj_sockaddr_t *src_addr, 2381 int src_addr_len) 2382 { 2383 pj_ssl_sock_t *ssock_parent = (pj_ssl_sock_t*) 2384 pj_activesock_get_user_data(asock); 2385 pj_ssl_sock_t *ssock; 2386 pj_activesock_cb asock_cb; 2387 pj_activesock_cfg asock_cfg; 2388 unsigned i; 2389 pj_status_t status; 2390 2391 /* Create new SSL socket instance */ 2392 status = pj_ssl_sock_create(ssock_parent->pool, 2393 &ssock_parent->newsock_param, &ssock); 2394 if (status != PJ_SUCCESS) 2395 goto on_return; 2396 2397 /* Update new SSL socket attributes */ 2398 ssock->sock = newsock; 2399 ssock->parent = ssock_parent; 2400 ssock->is_server = PJ_TRUE; 2401 if (ssock_parent->cert) { 2402 status = pj_ssl_sock_set_certificate(ssock, ssock->pool, 2403 ssock_parent->cert); 2404 if (status != PJ_SUCCESS) 2405 goto on_return; 2406 } 2407 2408 /* Apply QoS, if specified */ 2409 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, 2410 &ssock->param.qos_params, 1, 2411 ssock->pool->obj_name, NULL); 2412 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) 2413 goto on_return; 2414 2415 /* Apply socket options, if specified */ 2416 if (ssock->param.sockopt_params.cnt) { 2417 status = pj_sock_setsockopt_params(ssock->sock, 2418 &ssock->param.sockopt_params); 2419 if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) 2420 goto on_return; 2421 } 2422 2423 /* Update local address */ 2424 ssock->addr_len = src_addr_len; 2425 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 2426 &ssock->addr_len); 2427 if (status != PJ_SUCCESS) { 2428 /* This fails on few envs, e.g: win IOCP, just tolerate this and 2429 * use parent local address instead. 2430 */ 2431 pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr); 2432 } 2433 2434 /* Set remote address */ 2435 pj_sockaddr_cp(&ssock->rem_addr, src_addr); 2436 2437 /* Create SSL context */ 2438 status = create_ssl(ssock); 2439 if (status != PJ_SUCCESS) 2440 goto on_return; 2441 2442 /* Prepare read buffer */ 2443 ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool, 2444 ssock->param.async_cnt, 2445 sizeof(void*)); 2446 for (i = 0; i<ssock->param.async_cnt; ++i) { 2447 ssock->asock_rbuf[i] = (void*) pj_pool_alloc( 2448 ssock->pool, 2449 ssock->param.read_buffer_size + 2450 sizeof(read_data_t*)); 2451 } 2452 2453 /* Create active socket */ 2454 pj_activesock_cfg_default(&asock_cfg); 2455 asock_cfg.async_cnt = ssock->param.async_cnt; 2456 asock_cfg.concurrency = ssock->param.concurrency; 2457 asock_cfg.whole_data = PJ_TRUE; 2458 2459 /* If listener socket has group lock, automatically create group lock 2460 * for the new socket. 2461 */ 2462 if (ssock_parent->param.grp_lock) { 2463 pj_grp_lock_t *glock; 2464 2465 status = pj_grp_lock_create(ssock->pool, NULL, &glock); 2466 if (status != PJ_SUCCESS) 2467 goto on_return; 2468 2469 pj_grp_lock_add_ref(glock); 2470 asock_cfg.grp_lock = ssock->param.grp_lock = glock; 2471 pj_grp_lock_add_handler(ssock->param.grp_lock, ssock->pool, ssock, 2472 ssl_on_destroy); 2473 } 2474 2475 pj_bzero(&asock_cb, sizeof(asock_cb)); 2476 asock_cb.on_data_read = asock_on_data_read; 2477 asock_cb.on_data_sent = asock_on_data_sent; 2478 2479 status = pj_activesock_create(ssock->pool, 2480 ssock->sock, 2481 ssock->param.sock_type, 2482 &asock_cfg, 2483 ssock->param.ioqueue, 2484 &asock_cb, 2485 ssock, 2486 &ssock->asock); 2487 2488 if (status != PJ_SUCCESS) 2489 goto on_return; 2490 2491 /* Start read */ 2492 status = pj_activesock_start_read2(ssock->asock, ssock->pool, 2493 (unsigned)ssock->param.read_buffer_size, 2494 ssock->asock_rbuf, 2495 PJ_IOQUEUE_ALWAYS_ASYNC); 2496 if (status != PJ_SUCCESS) 2497 goto on_return; 2498 2499 /* Prepare write/send state */ 2500 pj_assert(ssock->send_buf.max_len == 0); 2501 ssock->send_buf.buf = (char*) 2502 pj_pool_alloc(ssock->pool, 2503 ssock->param.send_buffer_size); 2504 ssock->send_buf.max_len = ssock->param.send_buffer_size; 2505 ssock->send_buf.start = ssock->send_buf.buf; 2506 ssock->send_buf.len = 0; 2507 2508 /* Start handshake timer */ 2509 if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 || 2510 ssock->param.timeout.msec != 0)) 2511 { 2512 pj_assert(ssock->timer.id == TIMER_NONE); 2513 ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT; 2514 status = pj_timer_heap_schedule(ssock->param.timer_heap, 2515 &ssock->timer, 2516 &ssock->param.timeout); 2517 if (status != PJ_SUCCESS) { 2518 ssock->timer.id = TIMER_NONE; 2519 status = PJ_SUCCESS; 2520 } 2521 } 2522 2523 /* Start SSL handshake */ 2524 ssock->ssl_state = SSL_STATE_HANDSHAKING; 2525 SSL_set_accept_state(ssock->ossl_ssl); 2526 status = do_handshake(ssock); 2527 2528 on_return: 2529 if (ssock && status != PJ_EPENDING) { 2530 on_handshake_complete(ssock, status); 2531 } 2532 2533 /* Must return PJ_TRUE whatever happened, as active socket must 2534 * continue listening. 2535 */ 2536 return PJ_TRUE; 2537 } 2538 2539 2540 static pj_bool_t asock_on_accept_complete2(pj_activesock_t *asock, 2541 pj_sock_t newsock, 2542 const pj_sockaddr_t *src_addr, 2543 int src_addr_len, 2544 pj_status_t status) 2545 { 2546 pj_bool_t ret = PJ_TRUE; 2547 if (status != PJ_SUCCESS) { 2548 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) 2549 pj_activesock_get_user_data(asock); 2550 2551 if (ssock->param.cb.on_accept_complete2) { 2552 (*ssock->param.cb.on_accept_complete2) (ssock, NULL, 2553 src_addr, src_addr_len, 2554 status); 2555 } 2556 } else { 2557 ret = asock_on_accept_complete(asock, newsock, src_addr, src_addr_len); 2558 } 2559 return ret; 2560 } 2561 2562 2563 static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock, 2564 pj_status_t status) 2565 { 2566 pj_ssl_sock_t *ssock = (pj_ssl_sock_t*) 2567 pj_activesock_get_user_data(asock); 2568 unsigned i; 2569 2570 if (status != PJ_SUCCESS) 2571 goto on_return; 2572 2573 /* Update local address */ 2574 ssock->addr_len = sizeof(pj_sockaddr); 2575 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 2576 &ssock->addr_len); 2577 if (status != PJ_SUCCESS) 2578 goto on_return; 2579 2580 /* Create SSL context */ 2581 status = create_ssl(ssock); 2582 if (status != PJ_SUCCESS) 2583 goto on_return; 2584 2585 /* Prepare read buffer */ 2586 ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool, 2587 ssock->param.async_cnt, 2588 sizeof(void*)); 2589 for (i = 0; i<ssock->param.async_cnt; ++i) { 2590 ssock->asock_rbuf[i] = (void*) pj_pool_alloc( 2591 ssock->pool, 2592 ssock->param.read_buffer_size + 2593 sizeof(read_data_t*)); 2594 } 2595 2596 /* Start read */ 2597 status = pj_activesock_start_read2(ssock->asock, ssock->pool, 2598 (unsigned)ssock->param.read_buffer_size, 2599 ssock->asock_rbuf, 2600 PJ_IOQUEUE_ALWAYS_ASYNC); 2601 if (status != PJ_SUCCESS) 2602 goto on_return; 2603 2604 /* Prepare write/send state */ 2605 pj_assert(ssock->send_buf.max_len == 0); 2606 ssock->send_buf.buf = (char*) 2607 pj_pool_alloc(ssock->pool, 2608 ssock->param.send_buffer_size); 2609 ssock->send_buf.max_len = ssock->param.send_buffer_size; 2610 ssock->send_buf.start = ssock->send_buf.buf; 2611 ssock->send_buf.len = 0; 2612 2613 #ifdef SSL_set_tlsext_host_name 2614 /* Set server name to connect */ 2615 if (ssock->param.server_name.slen) { 2616 /* Server name is null terminated already */ 2617 if (!SSL_set_tlsext_host_name(ssock->ossl_ssl, 2618 ssock->param.server_name.ptr)) 2619 { 2620 char err_str[PJ_ERR_MSG_SIZE]; 2621 2622 ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str)); 2623 PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() " 2624 "failed: %s", err_str)); 2625 } 2626 } 2627 #endif 2628 2629 /* Start SSL handshake */ 2630 ssock->ssl_state = SSL_STATE_HANDSHAKING; 2631 SSL_set_connect_state(ssock->ossl_ssl); 2632 2633 status = do_handshake(ssock); 2634 if (status != PJ_EPENDING) 2635 goto on_return; 2636 2637 return PJ_TRUE; 2638 2639 on_return: 2640 return on_handshake_complete(ssock, status); 2641 } 2642 2643 2644 2645 /* 2646 ******************************************************************* 2647 * API 2648 ******************************************************************* 2649 */ 2650 2651 /* Load credentials from files. */ 2652 PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files (pj_pool_t *pool, 2653 const pj_str_t *CA_file, 2654 const pj_str_t *cert_file, 2655 const pj_str_t *privkey_file, 2656 const pj_str_t *privkey_pass, 2657 pj_ssl_cert_t **p_cert) 2658 { 2659 return pj_ssl_cert_load_from_files2(pool, CA_file, NULL, cert_file, 2660 privkey_file, privkey_pass, p_cert); 2661 } 2662 2663 PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files2(pj_pool_t *pool, 2664 const pj_str_t *CA_file, 2665 const pj_str_t *CA_path, 2666 const pj_str_t *cert_file, 2667 const pj_str_t *privkey_file, 2668 const pj_str_t *privkey_pass, 2669 pj_ssl_cert_t **p_cert) 2670 { 2671 pj_ssl_cert_t *cert; 2672 2673 PJ_ASSERT_RETURN(pool && (CA_file || CA_path) && cert_file && 2674 privkey_file, 2675 PJ_EINVAL); 2676 2677 cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t); 2678 if (CA_file) { 2679 pj_strdup_with_null(pool, &cert->CA_file, CA_file); 2680 } 2681 if (CA_path) { 2682 pj_strdup_with_null(pool, &cert->CA_path, CA_path); 2683 } 2684 pj_strdup_with_null(pool, &cert->cert_file, cert_file); 2685 pj_strdup_with_null(pool, &cert->privkey_file, privkey_file); 2686 pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass); 2687 2688 *p_cert = cert; 2689 2690 return PJ_SUCCESS; 2691 } 2692 2693 PJ_DEF(pj_status_t) pj_ssl_cert_load_from_buffer(pj_pool_t *pool, 2694 const pj_ssl_cert_buffer *CA_buf, 2695 const pj_ssl_cert_buffer *cert_buf, 2696 const pj_ssl_cert_buffer *privkey_buf, 2697 const pj_str_t *privkey_pass, 2698 pj_ssl_cert_t **p_cert) 2699 { 2700 pj_ssl_cert_t *cert; 2701 2702 PJ_ASSERT_RETURN(pool && CA_buf && cert_buf && privkey_buf, PJ_EINVAL); 2703 2704 cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t); 2705 pj_strdup(pool, &cert->CA_buf, CA_buf); 2706 pj_strdup(pool, &cert->cert_buf, cert_buf); 2707 pj_strdup(pool, &cert->privkey_buf, privkey_buf); 2708 pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass); 2709 2710 *p_cert = cert; 2711 2712 return PJ_SUCCESS; 2713 } 2714 2715 /* Set SSL socket credentials. */ 2716 PJ_DEF(pj_status_t) pj_ssl_sock_set_certificate( 2717 pj_ssl_sock_t *ssock, 2718 pj_pool_t *pool, 2719 const pj_ssl_cert_t *cert) 2720 { 2721 pj_ssl_cert_t *cert_; 2722 2723 PJ_ASSERT_RETURN(ssock && pool && cert, PJ_EINVAL); 2724 2725 cert_ = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t); 2726 pj_memcpy(cert_, cert, sizeof(pj_ssl_cert_t)); 2727 pj_strdup_with_null(pool, &cert_->CA_file, &cert->CA_file); 2728 pj_strdup_with_null(pool, &cert_->CA_path, &cert->CA_path); 2729 pj_strdup_with_null(pool, &cert_->cert_file, &cert->cert_file); 2730 pj_strdup_with_null(pool, &cert_->privkey_file, &cert->privkey_file); 2731 pj_strdup_with_null(pool, &cert_->privkey_pass, &cert->privkey_pass); 2732 2733 pj_strdup(pool, &cert_->CA_buf, &cert->CA_buf); 2734 pj_strdup(pool, &cert_->cert_buf, &cert->cert_buf); 2735 pj_strdup(pool, &cert_->privkey_buf, &cert->privkey_buf); 2736 2737 ssock->cert = cert_; 2738 2739 return PJ_SUCCESS; 2740 } 2741 2742 2743 /* Get available ciphers. */ 2744 PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[], 2745 unsigned *cipher_num) 2746 { 2747 unsigned i; 2748 2749 PJ_ASSERT_RETURN(ciphers && cipher_num, PJ_EINVAL); 2750 2751 if (openssl_cipher_num == 0) { 2752 init_openssl(); 2753 shutdown_openssl(); 2754 } 2755 2756 if (openssl_cipher_num == 0) { 2757 *cipher_num = 0; 2758 return PJ_ENOTFOUND; 2759 } 2760 2761 *cipher_num = PJ_MIN(*cipher_num, openssl_cipher_num); 2762 2763 for (i = 0; i < *cipher_num; ++i) 2764 ciphers[i] = openssl_ciphers[i].id; 2765 2766 return PJ_SUCCESS; 2767 } 2768 2769 2770 /* Get cipher name string */ 2771 PJ_DEF(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher) 2772 { 2773 unsigned i; 2774 2775 if (openssl_cipher_num == 0) { 2776 init_openssl(); 2777 shutdown_openssl(); 2778 } 2779 2780 for (i = 0; i < openssl_cipher_num; ++i) { 2781 if (cipher == openssl_ciphers[i].id) 2782 return openssl_ciphers[i].name; 2783 } 2784 2785 return NULL; 2786 } 2787 2788 /* Get cipher identifier */ 2789 PJ_DEF(pj_ssl_cipher) pj_ssl_cipher_id(const char *cipher_name) 2790 { 2791 unsigned i; 2792 2793 if (openssl_cipher_num == 0) { 2794 init_openssl(); 2795 shutdown_openssl(); 2796 } 2797 2798 for (i = 0; i < openssl_cipher_num; ++i) { 2799 if (!pj_ansi_stricmp(openssl_ciphers[i].name, cipher_name)) 2800 return openssl_ciphers[i].id; 2801 } 2802 2803 return PJ_TLS_UNKNOWN_CIPHER; 2804 } 2805 2806 /* Check if the specified cipher is supported by SSL/TLS backend. */ 2807 PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher) 2808 { 2809 unsigned i; 2810 2811 if (openssl_cipher_num == 0) { 2812 init_openssl(); 2813 shutdown_openssl(); 2814 } 2815 2816 for (i = 0; i < openssl_cipher_num; ++i) { 2817 if (cipher == openssl_ciphers[i].id) 2818 return PJ_TRUE; 2819 } 2820 2821 return PJ_FALSE; 2822 } 2823 2824 /* Get available curves. */ 2825 PJ_DEF(pj_status_t) pj_ssl_curve_get_availables(pj_ssl_curve curves[], 2826 unsigned *curve_num) 2827 { 2828 unsigned i; 2829 2830 PJ_ASSERT_RETURN(curves && curve_num, PJ_EINVAL); 2831 2832 if (openssl_curves_num == 0) { 2833 init_openssl(); 2834 shutdown_openssl(); 2835 } 2836 2837 if (openssl_curves_num == 0) { 2838 *curve_num = 0; 2839 return PJ_ENOTFOUND; 2840 } 2841 2842 *curve_num = PJ_MIN(*curve_num, openssl_curves_num); 2843 2844 for (i = 0; i < *curve_num; ++i) 2845 curves[i] = openssl_curves[i].id; 2846 2847 return PJ_SUCCESS; 2848 } 2849 2850 /* Get curve name string. */ 2851 PJ_DEF(const char*) pj_ssl_curve_name(pj_ssl_curve curve) 2852 { 2853 unsigned i; 2854 2855 if (openssl_curves_num == 0) { 2856 init_openssl(); 2857 shutdown_openssl(); 2858 } 2859 2860 for (i = 0; i < openssl_curves_num; ++i) { 2861 if (curve == openssl_curves[i].id) 2862 return openssl_curves[i].name; 2863 } 2864 2865 return NULL; 2866 } 2867 2868 /* Get curve ID from curve name string. */ 2869 PJ_DEF(pj_ssl_curve) pj_ssl_curve_id(const char *curve_name) 2870 { 2871 unsigned i; 2872 2873 if (openssl_curves_num == 0) { 2874 init_openssl(); 2875 shutdown_openssl(); 2876 } 2877 2878 for (i = 0; i < openssl_curves_num; ++i) { 2879 if (openssl_curves[i].name && 2880 !pj_ansi_stricmp(openssl_curves[i].name, curve_name)) 2881 { 2882 return openssl_curves[i].id; 2883 } 2884 } 2885 2886 return PJ_TLS_UNKNOWN_CURVE; 2887 } 2888 2889 /* Check if the specified curve is supported by SSL/TLS backend. */ 2890 PJ_DEF(pj_bool_t) pj_ssl_curve_is_supported(pj_ssl_curve curve) 2891 { 2892 unsigned i; 2893 2894 if (openssl_curves_num == 0) { 2895 init_openssl(); 2896 shutdown_openssl(); 2897 } 2898 2899 for (i = 0; i < openssl_curves_num; ++i) { 2900 if (curve == openssl_curves[i].id) 2901 return PJ_TRUE; 2902 } 2903 2904 return PJ_FALSE; 2905 } 2906 2907 /* 2908 * Create SSL socket instance. 2909 */ 2910 PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool, 2911 const pj_ssl_sock_param *param, 2912 pj_ssl_sock_t **p_ssock) 2913 { 2914 pj_ssl_sock_t *ssock; 2915 pj_status_t status; 2916 2917 PJ_ASSERT_RETURN(pool && param && p_ssock, PJ_EINVAL); 2918 PJ_ASSERT_RETURN(param->sock_type == pj_SOCK_STREAM(), PJ_ENOTSUP); 2919 2920 pool = pj_pool_create(pool->factory, "ssl%p", 512, 512, NULL); 2921 2922 /* Create secure socket */ 2923 ssock = PJ_POOL_ZALLOC_T(pool, pj_ssl_sock_t); 2924 ssock->pool = pool; 2925 ssock->sock = PJ_INVALID_SOCKET; 2926 ssock->ssl_state = SSL_STATE_NULL; 2927 pj_list_init(&ssock->write_pending); 2928 pj_list_init(&ssock->write_pending_empty); 2929 pj_list_init(&ssock->send_pending); 2930 pj_timer_entry_init(&ssock->timer, 0, ssock, &on_timer); 2931 pj_ioqueue_op_key_init(&ssock->handshake_op_key, 2932 sizeof(pj_ioqueue_op_key_t)); 2933 2934 /* Create secure socket mutex */ 2935 status = pj_lock_create_recursive_mutex(pool, pool->obj_name, 2936 &ssock->write_mutex); 2937 if (status != PJ_SUCCESS) { 2938 pj_pool_release(pool); 2939 return status; 2940 } 2941 2942 /* Init secure socket param */ 2943 pj_ssl_sock_param_copy(pool, &ssock->param, param); 2944 2945 if (ssock->param.grp_lock) { 2946 pj_grp_lock_add_ref(ssock->param.grp_lock); 2947 pj_grp_lock_add_handler(ssock->param.grp_lock, pool, ssock, 2948 ssl_on_destroy); 2949 } 2950 2951 ssock->param.read_buffer_size = ((ssock->param.read_buffer_size+7)>>3)<<3; 2952 if (!ssock->param.timer_heap) { 2953 PJ_LOG(3,(ssock->pool->obj_name, "Warning: timer heap is not " 2954 "available. It is recommended to supply one to avoid " 2955 "a race condition if more than one worker threads " 2956 "are used.")); 2957 } 2958 2959 /* Finally */ 2960 *p_ssock = ssock; 2961 2962 return PJ_SUCCESS; 2963 } 2964 2965 2966 /* 2967 * Close the secure socket. This will unregister the socket from the 2968 * ioqueue and ultimately close the socket. 2969 */ 2970 PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock) 2971 { 2972 PJ_ASSERT_RETURN(ssock, PJ_EINVAL); 2973 2974 if (!ssock->pool) 2975 return PJ_SUCCESS; 2976 2977 if (ssock->timer.id != TIMER_NONE) { 2978 pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer); 2979 ssock->timer.id = TIMER_NONE; 2980 } 2981 2982 reset_ssl_sock_state(ssock); 2983 if (ssock->param.grp_lock) { 2984 pj_grp_lock_dec_ref(ssock->param.grp_lock); 2985 } else { 2986 ssl_on_destroy(ssock); 2987 } 2988 2989 return PJ_SUCCESS; 2990 } 2991 2992 2993 /* 2994 * Associate arbitrary data with the secure socket. 2995 */ 2996 PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock, 2997 void *user_data) 2998 { 2999 PJ_ASSERT_RETURN(ssock, PJ_EINVAL); 3000 3001 ssock->param.user_data = user_data; 3002 return PJ_SUCCESS; 3003 } 3004 3005 3006 /* 3007 * Retrieve the user data previously associated with this secure 3008 * socket. 3009 */ 3010 PJ_DEF(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock) 3011 { 3012 PJ_ASSERT_RETURN(ssock, NULL); 3013 3014 return ssock->param.user_data; 3015 } 3016 3017 3018 /* 3019 * Retrieve the local address and port used by specified SSL socket. 3020 */ 3021 PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock, 3022 pj_ssl_sock_info *info) 3023 { 3024 pj_bzero(info, sizeof(*info)); 3025 3026 /* Established flag */ 3027 info->established = (ssock->ssl_state == SSL_STATE_ESTABLISHED); 3028 3029 /* Protocol */ 3030 info->proto = ssock->param.proto; 3031 3032 /* Local address */ 3033 pj_sockaddr_cp(&info->local_addr, &ssock->local_addr); 3034 3035 if (info->established) { 3036 const SSL_CIPHER *cipher; 3037 3038 /* Current cipher */ 3039 cipher = SSL_get_current_cipher(ssock->ossl_ssl); 3040 if (cipher) { 3041 info->cipher = (SSL_CIPHER_get_id(cipher) & 0x00FFFFFF); 3042 } else { 3043 info->cipher = PJ_TLS_UNKNOWN_CIPHER; 3044 } 3045 3046 /* Remote address */ 3047 pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr); 3048 3049 /* Certificates info */ 3050 info->local_cert_info = &ssock->local_cert_info; 3051 info->remote_cert_info = &ssock->remote_cert_info; 3052 3053 /* Verification status */ 3054 info->verify_status = ssock->verify_status; 3055 } 3056 3057 /* Last known OpenSSL error code */ 3058 info->last_native_err = ssock->last_err; 3059 3060 /* Group lock */ 3061 info->grp_lock = ssock->param.grp_lock; 3062 3063 return PJ_SUCCESS; 3064 } 3065 3066 3067 /* 3068 * Starts read operation on this secure socket. 3069 */ 3070 PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock, 3071 pj_pool_t *pool, 3072 unsigned buff_size, 3073 pj_uint32_t flags) 3074 { 3075 void **readbuf; 3076 unsigned i; 3077 3078 PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL); 3079 3080 if (ssock->ssl_state != SSL_STATE_ESTABLISHED) 3081 return PJ_EINVALIDOP; 3082 3083 readbuf = (void**) pj_pool_calloc(pool, ssock->param.async_cnt, 3084 sizeof(void*)); 3085 3086 for (i=0; i<ssock->param.async_cnt; ++i) { 3087 readbuf[i] = pj_pool_alloc(pool, buff_size); 3088 } 3089 3090 return pj_ssl_sock_start_read2(ssock, pool, buff_size, 3091 readbuf, flags); 3092 } 3093 3094 3095 /* 3096 * Same as #pj_ssl_sock_start_read(), except that the application 3097 * supplies the buffers for the read operation so that the acive socket 3098 * does not have to allocate the buffers. 3099 */ 3100 PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock, 3101 pj_pool_t *pool, 3102 unsigned buff_size, 3103 void *readbuf[], 3104 pj_uint32_t flags) 3105 { 3106 unsigned i; 3107 3108 PJ_ASSERT_RETURN(ssock && pool && buff_size && readbuf, PJ_EINVAL); 3109 3110 if (ssock->ssl_state != SSL_STATE_ESTABLISHED) 3111 return PJ_EINVALIDOP; 3112 3113 /* Create SSL socket read buffer */ 3114 ssock->ssock_rbuf = (read_data_t*)pj_pool_calloc(pool, 3115 ssock->param.async_cnt, 3116 sizeof(read_data_t)); 3117 3118 /* Store SSL socket read buffer pointer in the activesock read buffer */ 3119 for (i=0; i<ssock->param.async_cnt; ++i) { 3120 read_data_t **p_ssock_rbuf = 3121 OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]); 3122 3123 ssock->ssock_rbuf[i].data = readbuf[i]; 3124 ssock->ssock_rbuf[i].len = 0; 3125 3126 *p_ssock_rbuf = &ssock->ssock_rbuf[i]; 3127 } 3128 3129 ssock->read_size = buff_size; 3130 ssock->read_started = PJ_TRUE; 3131 ssock->read_flags = flags; 3132 3133 return PJ_SUCCESS; 3134 } 3135 3136 3137 /* 3138 * Same as pj_ssl_sock_start_read(), except that this function is used 3139 * only for datagram sockets, and it will trigger \a on_data_recvfrom() 3140 * callback instead. 3141 */ 3142 PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock, 3143 pj_pool_t *pool, 3144 unsigned buff_size, 3145 pj_uint32_t flags) 3146 { 3147 PJ_UNUSED_ARG(ssock); 3148 PJ_UNUSED_ARG(pool); 3149 PJ_UNUSED_ARG(buff_size); 3150 PJ_UNUSED_ARG(flags); 3151 3152 return PJ_ENOTSUP; 3153 } 3154 3155 3156 /* 3157 * Same as #pj_ssl_sock_start_recvfrom() except that the recvfrom() 3158 * operation takes the buffer from the argument rather than creating 3159 * new ones. 3160 */ 3161 PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock, 3162 pj_pool_t *pool, 3163 unsigned buff_size, 3164 void *readbuf[], 3165 pj_uint32_t flags) 3166 { 3167 PJ_UNUSED_ARG(ssock); 3168 PJ_UNUSED_ARG(pool); 3169 PJ_UNUSED_ARG(buff_size); 3170 PJ_UNUSED_ARG(readbuf); 3171 PJ_UNUSED_ARG(flags); 3172 3173 return PJ_ENOTSUP; 3174 } 3175 3176 /* Write plain data to SSL and flush write BIO. */ 3177 static pj_status_t ssl_write(pj_ssl_sock_t *ssock, 3178 pj_ioqueue_op_key_t *send_key, 3179 const void *data, 3180 pj_ssize_t size, 3181 unsigned flags) 3182 { 3183 pj_status_t status; 3184 int nwritten; 3185 3186 /* Write the plain data to SSL, after SSL encrypts it, write BIO will 3187 * contain the secured data to be sent via socket. Note that re- 3188 * negotitation may be on progress, so sending data should be delayed 3189 * until re-negotiation is completed. 1665 1666 static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size) 1667 { 1668 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1669 int size_ = *size; 1670 int len = size_; 1671 1672 /* SSL_read() may write some data to write buffer when re-negotiation 1673 * is on progress, so let's protect it with write mutex. 3190 1674 */ 3191 1675 pj_lock_acquire(ssock->write_mutex); 3192 /* Don't write to SSL if send buffer is full and some data is in 3193 * write BIO already, just return PJ_ENOMEM. 3194 */ 3195 if (ssock->send_buf_pending.data_len) { 3196 pj_lock_release(ssock->write_mutex); 3197 return PJ_ENOMEM; 3198 } 3199 nwritten = SSL_write(ssock->ossl_ssl, data, (int)size); 1676 *size = size_ = SSL_read(ossock->ossl_ssl, data, size_); 3200 1677 pj_lock_release(ssock->write_mutex); 3201 3202 if (nwritten == size) { 3203 /* All data written, flush write BIO to network socket */ 3204 status = flush_write_bio(ssock, send_key, size, flags); 3205 } else if (nwritten <= 0) { 1678 1679 if (size_ <= 0) { 1680 pj_status_t status; 1681 int err = SSL_get_error(ossock->ossl_ssl, size_); 1682 1683 /* SSL might just return SSL_ERROR_WANT_READ in 1684 * re-negotiation. 1685 */ 1686 if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ) { 1687 if (err == SSL_ERROR_SYSCALL && size_ == -1 && 1688 ERR_peek_error() == 0 && errno == 0) 1689 { 1690 status = STATUS_FROM_SSL_ERR2("Read", ssock, size_, 1691 err, len); 1692 PJ_LOG(4,("SSL", "SSL_read() = -1, with " 1693 "SSL_ERROR_SYSCALL, no SSL error, " 1694 "and errno = 0 - skip BIO error")); 1695 /* Ignore these errors */ 1696 } else { 1697 /* Reset SSL socket state, then return PJ_FALSE */ 1698 status = STATUS_FROM_SSL_ERR2("Read", ssock, size_, 1699 err, len); 1700 ssl_reset_sock_state(ssock); 1701 return status; 1702 } 1703 } 1704 1705 /* Need renegotiation */ 1706 return PJ_EEOF; 1707 } 1708 1709 return PJ_SUCCESS; 1710 } 1711 1712 1713 /* Write plain data to SSL and flush write BIO. */ 1714 static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data, 1715 pj_ssize_t size, int *nwritten) 1716 { 1717 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1718 pj_status_t status = PJ_SUCCESS; 1719 1720 *nwritten = SSL_write(ossock->ossl_ssl, data, (int)size); 1721 if (*nwritten <= 0) { 3206 1722 /* SSL failed to process the data, it may just that re-negotiation 3207 1723 * is on progress. 3208 1724 */ 3209 1725 int err; 3210 err = SSL_get_error( ssock->ossl_ssl,nwritten);1726 err = SSL_get_error(ossock->ossl_ssl, *nwritten); 3211 1727 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_NONE) { 3212 /* Re-negotiation is on progress, flush re-negotiation data */ 3213 status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0); 3214 if (status == PJ_SUCCESS || status == PJ_EPENDING) 3215 /* Just return PJ_EBUSY when re-negotiation is on progress */ 3216 status = PJ_EBUSY; 1728 status = PJ_EEOF; 3217 1729 } else { 3218 1730 /* Some problem occured */ 3219 status = STATUS_FROM_SSL_ERR2("Write", ssock, nwritten, err, size); 3220 } 3221 } else { 3222 /* nwritten < *size, shouldn't happen, unless write BIO cannot hold 1731 status = STATUS_FROM_SSL_ERR2("Write", ssock, *nwritten, 1732 err, size); 1733 } 1734 } else if (*nwritten < size) { 1735 /* nwritten < size, shouldn't happen, unless write BIO cannot hold 3223 1736 * the whole secured data, perhaps because of insufficient memory. 3224 1737 */ … … 3229 1742 } 3230 1743 3231 /* Flush delayed data sending in the write pending list. */ 3232 static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock) 3233 { 3234 /* Check for another ongoing flush */ 3235 if (ssock->flushing_write_pend) 3236 return PJ_EBUSY; 3237 3238 pj_lock_acquire(ssock->write_mutex); 3239 3240 /* Again, check for another ongoing flush */ 3241 if (ssock->flushing_write_pend) { 3242 pj_lock_release(ssock->write_mutex); 3243 return PJ_EBUSY; 3244 } 3245 3246 /* Set ongoing flush flag */ 3247 ssock->flushing_write_pend = PJ_TRUE; 3248 3249 while (!pj_list_empty(&ssock->write_pending)) { 3250 write_data_t *wp; 3251 pj_status_t status; 3252 3253 wp = ssock->write_pending.next; 3254 3255 /* Ticket #1573: Don't hold mutex while calling socket send. */ 3256 pj_lock_release(ssock->write_mutex); 3257 3258 status = ssl_write(ssock, &wp->key, wp->data.ptr, 3259 wp->plain_data_len, wp->flags); 3260 if (status != PJ_SUCCESS) { 3261 /* Reset ongoing flush flag first. */ 3262 ssock->flushing_write_pend = PJ_FALSE; 3263 return status; 3264 } 3265 3266 pj_lock_acquire(ssock->write_mutex); 3267 pj_list_erase(wp); 3268 pj_list_push_back(&ssock->write_pending_empty, wp); 3269 } 3270 3271 /* Reset ongoing flush flag */ 3272 ssock->flushing_write_pend = PJ_FALSE; 3273 3274 pj_lock_release(ssock->write_mutex); 3275 3276 return PJ_SUCCESS; 3277 } 3278 3279 /* Sending is delayed, push back the sending data into pending list. */ 3280 static pj_status_t delay_send (pj_ssl_sock_t *ssock, 3281 pj_ioqueue_op_key_t *send_key, 3282 const void *data, 3283 pj_ssize_t size, 3284 unsigned flags) 3285 { 3286 write_data_t *wp; 3287 3288 pj_lock_acquire(ssock->write_mutex); 3289 3290 /* Init write pending instance */ 3291 if (!pj_list_empty(&ssock->write_pending_empty)) { 3292 wp = ssock->write_pending_empty.next; 3293 pj_list_erase(wp); 3294 } else { 3295 wp = PJ_POOL_ZALLOC_T(ssock->pool, write_data_t); 3296 } 3297 3298 wp->app_key = send_key; 3299 wp->plain_data_len = size; 3300 wp->data.ptr = data; 3301 wp->flags = flags; 3302 3303 pj_list_push_back(&ssock->write_pending, wp); 3304 3305 pj_lock_release(ssock->write_mutex); 3306 3307 /* Must return PJ_EPENDING */ 3308 return PJ_EPENDING; 3309 } 3310 3311 /** 3312 * Send data using the socket. 3313 */ 3314 PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock, 3315 pj_ioqueue_op_key_t *send_key, 3316 const void *data, 3317 pj_ssize_t *size, 3318 unsigned flags) 3319 { 3320 pj_status_t status; 3321 3322 PJ_ASSERT_RETURN(ssock && data && size && (*size>0), PJ_EINVAL); 3323 3324 if (ssock->ssl_state != SSL_STATE_ESTABLISHED) 3325 return PJ_EINVALIDOP; 3326 3327 // Ticket #1573: Don't hold mutex while calling PJLIB socket send(). 3328 //pj_lock_acquire(ssock->write_mutex); 3329 3330 /* Flush delayed send first. Sending data might be delayed when 3331 * re-negotiation is on-progress. 3332 */ 3333 status = flush_delayed_send(ssock); 3334 if (status == PJ_EBUSY) { 3335 /* Re-negotiation or flushing is on progress, delay sending */ 3336 status = delay_send(ssock, send_key, data, *size, flags); 3337 goto on_return; 3338 } else if (status != PJ_SUCCESS) { 3339 goto on_return; 3340 } 3341 3342 /* Write data to SSL */ 3343 status = ssl_write(ssock, send_key, data, *size, flags); 3344 if (status == PJ_EBUSY) { 3345 /* Re-negotiation is on progress, delay sending */ 3346 status = delay_send(ssock, send_key, data, *size, flags); 3347 } 3348 3349 on_return: 3350 //pj_lock_release(ssock->write_mutex); 3351 return status; 3352 } 3353 3354 3355 /** 3356 * Send datagram using the socket. 3357 */ 3358 PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock, 3359 pj_ioqueue_op_key_t *send_key, 3360 const void *data, 3361 pj_ssize_t *size, 3362 unsigned flags, 3363 const pj_sockaddr_t *addr, 3364 int addr_len) 3365 { 3366 PJ_UNUSED_ARG(ssock); 3367 PJ_UNUSED_ARG(send_key); 3368 PJ_UNUSED_ARG(data); 3369 PJ_UNUSED_ARG(size); 3370 PJ_UNUSED_ARG(flags); 3371 PJ_UNUSED_ARG(addr); 3372 PJ_UNUSED_ARG(addr_len); 3373 3374 return PJ_ENOTSUP; 3375 } 3376 3377 3378 /** 3379 * Starts asynchronous socket accept() operations on this secure socket. 3380 */ 3381 PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock, 3382 pj_pool_t *pool, 3383 const pj_sockaddr_t *localaddr, 3384 int addr_len) 3385 { 3386 return pj_ssl_sock_start_accept2(ssock, pool, localaddr, addr_len, 3387 &ssock->param); 3388 } 3389 3390 3391 /** 3392 * Same as #pj_ssl_sock_start_accept(), but application provides parameter 3393 * for new accepted secure sockets. 3394 */ 3395 PJ_DEF(pj_status_t) 3396 pj_ssl_sock_start_accept2(pj_ssl_sock_t *ssock, 3397 pj_pool_t *pool, 3398 const pj_sockaddr_t *localaddr, 3399 int addr_len, 3400 const pj_ssl_sock_param *newsock_param) 3401 { 3402 pj_activesock_cb asock_cb; 3403 pj_activesock_cfg asock_cfg; 3404 pj_status_t status; 3405 3406 PJ_ASSERT_RETURN(ssock && pool && localaddr && addr_len, PJ_EINVAL); 3407 3408 /* Verify new socket parameters */ 3409 if (newsock_param->grp_lock != ssock->param.grp_lock || 3410 newsock_param->sock_af != ssock->param.sock_af || 3411 newsock_param->sock_type != ssock->param.sock_type) 3412 { 3413 return PJ_EINVAL; 3414 } 3415 3416 /* Create socket */ 3417 status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0, 3418 &ssock->sock); 3419 if (status != PJ_SUCCESS) 3420 goto on_error; 3421 3422 /* Apply SO_REUSEADDR */ 3423 if (ssock->param.reuse_addr) { 3424 int enabled = 1; 3425 status = pj_sock_setsockopt(ssock->sock, pj_SOL_SOCKET(), 3426 pj_SO_REUSEADDR(), 3427 &enabled, sizeof(enabled)); 3428 if (status != PJ_SUCCESS) { 3429 PJ_PERROR(4,(ssock->pool->obj_name, status, 3430 "Warning: error applying SO_REUSEADDR")); 3431 } 3432 } 3433 3434 /* Apply QoS, if specified */ 3435 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, 3436 &ssock->param.qos_params, 2, 3437 ssock->pool->obj_name, NULL); 3438 3439 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) 3440 goto on_error; 3441 3442 /* Apply socket options, if specified */ 3443 if (ssock->param.sockopt_params.cnt) { 3444 status = pj_sock_setsockopt_params(ssock->sock, 3445 &ssock->param.sockopt_params); 3446 3447 if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) 3448 goto on_error; 3449 } 3450 3451 /* Bind socket */ 3452 status = pj_sock_bind(ssock->sock, localaddr, addr_len); 3453 if (status != PJ_SUCCESS) 3454 goto on_error; 3455 3456 /* Start listening to the address */ 3457 status = pj_sock_listen(ssock->sock, PJ_SOMAXCONN); 3458 if (status != PJ_SUCCESS) 3459 goto on_error; 3460 3461 /* Create active socket */ 3462 pj_activesock_cfg_default(&asock_cfg); 3463 asock_cfg.async_cnt = ssock->param.async_cnt; 3464 asock_cfg.concurrency = ssock->param.concurrency; 3465 asock_cfg.whole_data = PJ_TRUE; 3466 asock_cfg.grp_lock = ssock->param.grp_lock; 3467 3468 pj_bzero(&asock_cb, sizeof(asock_cb)); 3469 //asock_cb.on_accept_complete = asock_on_accept_complete; 3470 asock_cb.on_accept_complete2 = asock_on_accept_complete2; 3471 3472 status = pj_activesock_create(pool, 3473 ssock->sock, 3474 ssock->param.sock_type, 3475 &asock_cfg, 3476 ssock->param.ioqueue, 3477 &asock_cb, 3478 ssock, 3479 &ssock->asock); 3480 3481 if (status != PJ_SUCCESS) 3482 goto on_error; 3483 3484 /* Start accepting */ 3485 pj_ssl_sock_param_copy(pool, &ssock->newsock_param, newsock_param); 3486 ssock->newsock_param.grp_lock = NULL; 3487 status = pj_activesock_start_accept(ssock->asock, pool); 3488 if (status != PJ_SUCCESS) 3489 goto on_error; 3490 3491 /* Update local address */ 3492 ssock->addr_len = addr_len; 3493 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 3494 &ssock->addr_len); 3495 if (status != PJ_SUCCESS) 3496 pj_sockaddr_cp(&ssock->local_addr, localaddr); 3497 3498 ssock->is_server = PJ_TRUE; 3499 3500 return PJ_SUCCESS; 3501 3502 on_error: 3503 reset_ssl_sock_state(ssock); 3504 return status; 3505 } 3506 3507 3508 /** 3509 * Starts asynchronous socket connect() operation. 3510 */ 3511 PJ_DEF(pj_status_t) pj_ssl_sock_start_connect( pj_ssl_sock_t *ssock, 3512 pj_pool_t *pool, 3513 const pj_sockaddr_t *localaddr, 3514 const pj_sockaddr_t *remaddr, 3515 int addr_len) 3516 { 3517 pj_activesock_cb asock_cb; 3518 pj_activesock_cfg asock_cfg; 3519 pj_status_t status; 3520 3521 PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len, 3522 PJ_EINVAL); 3523 3524 /* Create socket */ 3525 status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0, 3526 &ssock->sock); 3527 if (status != PJ_SUCCESS) 3528 goto on_error; 3529 3530 /* Apply QoS, if specified */ 3531 status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type, 3532 &ssock->param.qos_params, 2, 3533 ssock->pool->obj_name, NULL); 3534 if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error) 3535 goto on_error; 3536 3537 /* Apply socket options, if specified */ 3538 if (ssock->param.sockopt_params.cnt) { 3539 status = pj_sock_setsockopt_params(ssock->sock, 3540 &ssock->param.sockopt_params); 3541 3542 if (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error) 3543 goto on_error; 3544 } 3545 3546 /* Bind socket */ 3547 status = pj_sock_bind(ssock->sock, localaddr, addr_len); 3548 if (status != PJ_SUCCESS) 3549 goto on_error; 3550 3551 /* Create active socket */ 3552 pj_activesock_cfg_default(&asock_cfg); 3553 asock_cfg.async_cnt = ssock->param.async_cnt; 3554 asock_cfg.concurrency = ssock->param.concurrency; 3555 asock_cfg.whole_data = PJ_TRUE; 3556 asock_cfg.grp_lock = ssock->param.grp_lock; 3557 3558 pj_bzero(&asock_cb, sizeof(asock_cb)); 3559 asock_cb.on_connect_complete = asock_on_connect_complete; 3560 asock_cb.on_data_read = asock_on_data_read; 3561 asock_cb.on_data_sent = asock_on_data_sent; 3562 3563 status = pj_activesock_create(pool, 3564 ssock->sock, 3565 ssock->param.sock_type, 3566 &asock_cfg, 3567 ssock->param.ioqueue, 3568 &asock_cb, 3569 ssock, 3570 &ssock->asock); 3571 3572 if (status != PJ_SUCCESS) 3573 goto on_error; 3574 3575 /* Save remote address */ 3576 pj_sockaddr_cp(&ssock->rem_addr, remaddr); 3577 3578 /* Start timer */ 3579 if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 || 3580 ssock->param.timeout.msec != 0)) 3581 { 3582 pj_assert(ssock->timer.id == TIMER_NONE); 3583 ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT; 3584 status = pj_timer_heap_schedule(ssock->param.timer_heap, 3585 &ssock->timer, 3586 &ssock->param.timeout); 3587 if (status != PJ_SUCCESS) { 3588 ssock->timer.id = TIMER_NONE; 3589 status = PJ_SUCCESS; 3590 } 3591 } 3592 3593 status = pj_activesock_start_connect(ssock->asock, pool, remaddr, 3594 addr_len); 3595 3596 if (status == PJ_SUCCESS) 3597 asock_on_connect_complete(ssock->asock, PJ_SUCCESS); 3598 else if (status != PJ_EPENDING) 3599 goto on_error; 3600 3601 /* Update local address */ 3602 ssock->addr_len = addr_len; 3603 status = pj_sock_getsockname(ssock->sock, &ssock->local_addr, 3604 &ssock->addr_len); 3605 /* Note that we may not get an IP address here. This can 3606 * happen for example on Windows, where getsockname() 3607 * would return 0.0.0.0 if socket has just started the 3608 * async connect. In this case, just leave the local 3609 * address with 0.0.0.0 for now; it will be updated 3610 * once the socket is established. 3611 */ 3612 3613 /* Update SSL state */ 3614 ssock->is_server = PJ_FALSE; 3615 3616 return PJ_EPENDING; 3617 3618 on_error: 3619 reset_ssl_sock_state(ssock); 3620 return status; 3621 } 3622 3623 3624 PJ_DEF(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock) 3625 { 1744 1745 static pj_status_t ssl_renegotiate(pj_ssl_sock_t *ssock) 1746 { 1747 ossl_sock_t *ossock = (ossl_sock_t *)ssock; 1748 pj_status_t status = PJ_SUCCESS; 3626 1749 int ret; 3627 pj_status_t status; 3628 3629 PJ_ASSERT_RETURN(ssock, PJ_EINVAL); 3630 3631 if (ssock->ssl_state != SSL_STATE_ESTABLISHED) 3632 return PJ_EINVALIDOP; 3633 3634 if (SSL_renegotiate_pending(ssock->ossl_ssl)) 1750 1751 if (SSL_renegotiate_pending(ossock->ossl_ssl)) 3635 1752 return PJ_EPENDING; 3636 1753 3637 ret = SSL_renegotiate( ssock->ossl_ssl);1754 ret = SSL_renegotiate(ossock->ossl_ssl); 3638 1755 if (ret <= 0) { 3639 1756 status = GET_SSL_STATUS(ssock); 3640 } else { 3641 status = do_handshake(ssock); 3642 } 3643 1757 } 1758 3644 1759 return status; 3645 1760 }
Note: See TracChangeset
for help on using the changeset viewer.