~ubuntu-branches/ubuntu/trusty/sflphone/trusty

« back to all changes in this revision

Viewing changes to daemon/libs/pjproject/pjlib/src/pj/ssl_sock_ossl.c

  • Committer: Package Import Robot
  • Author(s): Mark Purcell
  • Date: 2013-06-30 11:40:56 UTC
  • mfrom: (4.1.18 saucy-proposed)
  • Revision ID: package-import@ubuntu.com-20130630114056-0np50jkyqo6vnmii
Tags: 1.2.3-2
* changeset_r92d62cfc54732bbbcfff2b1d36c096b120b981a5.diff 
  - fixes automatic endian detection 
* Update Vcs: fixes vcs-field-not-canonical

Show diffs side-by-side

added added

removed removed

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