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

« back to all changes in this revision

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

  • Committer: Package Import Robot
  • Author(s): Mark Purcell
  • Date: 2014-01-28 18:23:36 UTC
  • mfrom: (1.1.11)
  • mto: This revision was merged to the branch mainline in revision 24.
  • Revision ID: package-import@ubuntu.com-20140128182336-3xenud1kbnwmf3mz
* New upstream release 
  - Fixes "New Upstream Release" (Closes: #735846)
  - Fixes "Ringtone does not stop" (Closes: #727164)
  - Fixes "[sflphone-kde] crash on startup" (Closes: #718178)
  - Fixes "sflphone GUI crashes when call is hung up" (Closes: #736583)
* Build-Depends: ensure GnuTLS 2.6
  - libucommon-dev (>= 6.0.7-1.1), libccrtp-dev (>= 2.0.6-3)
  - Fixes "FTBFS Build-Depends libgnutls{26,28}-dev" (Closes: #722040)
* Fix "boost 1.49 is going away" unversioned Build-Depends: (Closes: #736746)
* Add Build-Depends: libsndfile-dev, nepomuk-core-dev

Show diffs side-by-side

added added

removed removed

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