~ubuntu-branches/ubuntu/wily/sflphone/wily

« back to all changes in this revision

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

  • Committer: Package Import Robot
  • Author(s): Francois Marier, Francois Marier, Mark Purcell
  • Date: 2014-10-18 15:08:50 UTC
  • mfrom: (1.1.12)
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20141018150850-2exfk34ckb15pcwi
Tags: 1.4.1-0.1
[ Francois Marier ]
* Non-maintainer upload
* New upstream release (closes: #759576, #741130)
  - debian/rules +PJPROJECT_VERSION := 2.2.1
  - add upstream patch to fix broken TLS support
  - add patch to fix pjproject regression

[ Mark Purcell ]
* Build-Depends:
  - sflphone-daemon + libavformat-dev, libavcodec-dev, libswscale-dev,
  libavdevice-dev, libavutil-dev
  - sflphone-gnome + libclutter-gtk-1.0-dev

Show diffs side-by-side

added added

removed removed

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