sip_transport_tls_ossl.c 64.2 KB
Newer Older
1
/* $Id: sip_transport_tls_ossl.c 3553 2011-05-05 06:14:19Z nanang $ */
Emmanuel Milou's avatar
Emmanuel Milou committed
2
/* 
3
 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
Emmanuel Milou's avatar
Emmanuel Milou committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
 */
#include <pjsip/sip_transport_tls.h>
#include <pjsip/sip_endpoint.h>
#include <pjsip/sip_errno.h>
#include <pj/compat/socket.h>
#include <pj/addr_resolv.h>
#include <pj/assert.h>
#include <pj/ioqueue.h>
#include <pj/lock.h>
#include <pj/log.h>
#include <pj/os.h>
#include <pj/pool.h>
#include <pj/compat/socket.h>
#include <pj/sock_select.h>
#include <pj/string.h>


/* Only build when PJSIP_HAS_TLS_TRANSPORT is enabled */
#if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0



/* 
 * Include OpenSSL headers 
 */
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

/*
 * With VisualC++, it's not possible to dynamically link against some
 * libraries when some macros are defined (unlike "make" based build
 * system where this can be easily manipulated).
 *
 * So for VisualC++ IDE, include OpenSSL libraries in the linking by
 * using the #pragma lib construct below.
 */
#ifdef _MSC_VER
# ifdef _DEBUG
#  pragma comment( lib, "libeay32MTd")
#  pragma comment( lib, "ssleay32MTd")
#else
#  pragma comment( lib, "libeay32MT")
#  pragma comment( lib, "ssleay32MT")
# endif
#endif


#define THIS_FILE	"transport_tls_ossl.c"

#define MAX_ASYNC_CNT	16
#define POOL_LIS_INIT	512
#define POOL_LIS_INC	512
#define POOL_TP_INIT	512
#define POOL_TP_INC	512



/**
 * Get the number of descriptors in the set. This is defined in sock_select.c
 * This function will only return the number of sockets set from PJ_FD_SET
 * operation. When the set is modified by other means (such as by select()),
 * the count will not be reflected here.
 *
 * That's why don't export this function in the header file, to avoid
 * misunderstanding.
 *
 * @param fdsetp    The descriptor set.
 *
 * @return          Number of descriptors in the set.
 */
PJ_DECL(pj_size_t) PJ_FD_COUNT(const pj_fd_set_t *fdsetp);



struct tls_listener;
struct tls_transport;


/*
 * This structure is "descendant" of pj_ioqueue_op_key_t, and it is used to
 * track pending/asynchronous accept() operation. TLS transport may have
 * more than one pending accept() operations, depending on the value of
 * async_cnt.
 */
struct pending_accept
{
    pj_ioqueue_op_key_t	     op_key;
    struct tls_listener	    *listener;
    unsigned		     index;
    pj_pool_t		    *pool;
    pj_sock_t		     new_sock;
    int			     addr_len;
    pj_sockaddr_in	     local_addr;
    pj_sockaddr_in	     remote_addr;
};


/*
 * This is the TLS listener, which is a "descendant" of pjsip_tpfactory (the
 * SIP transport factory).
 */
struct tls_listener
{
    pjsip_tpfactory	     factory;
    pj_bool_t		     is_registered;
    pjsip_tls_setting	     setting;
    pjsip_endpoint	    *endpt;
    pjsip_tpmgr		    *tpmgr;
    pj_sock_t		     sock;
    pj_ioqueue_key_t	    *key;
    unsigned		     async_cnt;
    struct pending_accept   *accept_op[MAX_ASYNC_CNT];

    SSL_CTX		    *ctx;
};


/*
 * This structure is used to keep delayed transmit operation in a list.
 * A delayed transmission occurs when application sends tx_data when
 * the TLS connect/establishment is still in progress. These delayed
 * transmission will be "flushed" once the socket is connected (either
 * successfully or with errors).
 */
struct delayed_tdata
{
    PJ_DECL_LIST_MEMBER(struct delayed_tdata);
    pjsip_tx_data_op_key    *tdata_op_key;
};


/*
 * This structure describes the TLS transport, and it's descendant of
 * pjsip_transport.
 */
struct tls_transport
{
    pjsip_transport	     base;
    pj_bool_t		     is_server;

    /* Do not save listener instance in the transport, because
     * listener might be destroyed during transport's lifetime.
     * See http://trac.pjsip.org/repos/ticket/491
    struct tls_listener	    *listener;
     */

    /* TLS settings, copied from listener */
    struct {
	pj_str_t	     server_name;
	pj_time_val	     timeout;
    } setting;

    pj_bool_t		     is_registered;
    pj_bool_t		     is_closing;
    pj_status_t		     close_reason;
    pj_sock_t		     sock;
    pj_ioqueue_key_t	    *key;
    pj_bool_t		     has_pending_connect;

    /* SSL connection */
    SSL			    *ssl;
    pj_bool_t		     ssl_shutdown_called;

    /* Keep alive */
    pj_timer_entry	     ka_timer;
    pj_time_val		     last_activity;

    /* TLS transport can only have  one rdata!
     * Otherwise chunks of incoming PDU may be received on different
     * buffer.
     */
    pjsip_rx_data	     rdata;

    /* Pending transmission list. */
    struct delayed_tdata     delayed_list;
};


/****************************************************************************
 * PROTOTYPES
 */

/* This callback is called when pending accept() operation completes. */
static void on_accept_complete(	pj_ioqueue_key_t *key, 
				pj_ioqueue_op_key_t *op_key, 
				pj_sock_t sock, 
				pj_status_t status);

/* This callback is called by transport manager to destroy listener */
static pj_status_t lis_destroy(pjsip_tpfactory *factory);

/* This callback is called by transport manager to create transport */
static pj_status_t lis_create_transport(pjsip_tpfactory *factory,
					pjsip_tpmgr *mgr,
					pjsip_endpoint *endpt,
					const pj_sockaddr *rem_addr,
					int addr_len,
					pjsip_transport **transport);

/* Common function to create and initialize transport */
static pj_status_t tls_create(struct tls_listener *listener,
			      pj_pool_t *pool,
			      pj_sock_t sock, pj_bool_t is_server,
			      const pj_sockaddr_in *local,
			      const pj_sockaddr_in *remote,
			      struct tls_transport **p_tls);


/****************************************************************************
 * SSL FUNCTIONS
 */

/* ssl_report_error() */
static void ssl_report_error(const char *sender, int level, 
			     pj_status_t status,
			     const char *format, ...)
{
    va_list marker;

    va_start(marker, format);

#if PJ_LOG_MAX_LEVEL > 0
    if (status != PJ_SUCCESS) {
	char err_format[PJ_ERR_MSG_SIZE + 512];
	int len;

	len = pj_ansi_snprintf(err_format, sizeof(err_format),
			       "%s: ", format);
	pj_strerror(status, err_format+len, sizeof(err_format)-len);
	
	pj_log(sender, level, err_format, marker);

    } else {
	unsigned long ssl_err;

	ssl_err = ERR_get_error();

	if (ssl_err == 0) {
	    pj_log(sender, level, format, marker);
	} else {
	    char err_format[512];
	    int len;

	    len = pj_ansi_snprintf(err_format, sizeof(err_format),
				   "%s: ", format);
	    ERR_error_string(ssl_err, err_format+len);
	    
	    pj_log(sender, level, err_format, marker);
	}
    }
#endif

    va_end(marker);
}


static void sockaddr_to_host_port( pj_pool_t *pool,
				   pjsip_host_port *host_port,
				   const pj_sockaddr_in *addr )
{
    enum { M = 48 };
    host_port->host.ptr = (char*)pj_pool_alloc(pool, M);
    host_port->host.slen = pj_ansi_snprintf( host_port->host.ptr, M, "%s", 
					    pj_inet_ntoa(addr->sin_addr));
    host_port->port = pj_ntohs(addr->sin_port);
}


/* SSL password callback. */
static int password_cb(char *buf, int num, int rwflag, void *user_data)
{
    struct tls_listener *lis = (struct tls_listener*) user_data;

    PJ_UNUSED_ARG(rwflag);

    if(num < lis->setting.password.slen+1)
	return 0;
    
    pj_memcpy(buf, lis->setting.password.ptr, lis->setting.password.slen);
    return lis->setting.password.slen;
}


/* OpenSSL library initialization counter */
static int openssl_init_count;

/* Initialize OpenSSL */
static pj_status_t init_openssl(void)
{
    if (++openssl_init_count != 1)
	return PJ_SUCCESS;

    SSL_library_init();
    SSL_load_error_strings();
    OpenSSL_add_all_algorithms();

    return PJ_SUCCESS;
}

/* Shutdown OpenSSL */
static void shutdown_openssl(void)
{
    if (--openssl_init_count != 0)
	return;
}


/* Create and initialize new SSL context */
static pj_status_t create_ctx( struct tls_listener *lis, SSL_CTX **p_ctx)
{
    struct pjsip_tls_setting *opt = &lis->setting;
    int method;
    char *lis_name = lis->factory.obj_name;
    SSL_METHOD *ssl_method;
    SSL_CTX *ctx;
    int mode, rc;
        
    *p_ctx = NULL;

    /* Make sure OpenSSL library has been initialized */
    init_openssl();

    /* Determine SSL method to use */
    method = opt->method;
    if (method == PJSIP_SSL_UNSPECIFIED_METHOD)
	method = PJSIP_SSL_DEFAULT_METHOD;

    switch (method) {
    case PJSIP_SSLV23_METHOD:
	ssl_method = SSLv23_method();
	break;
    case PJSIP_TLSV1_METHOD:
	ssl_method = TLSv1_method();
	break;
    case PJSIP_SSLV3_METHOD:
	ssl_method = SSLv3_method();
	break;
    default:
	ssl_report_error(lis_name, 4, PJSIP_TLS_EINVMETHOD,
			 "Error creating SSL context");
	return PJSIP_TLS_EINVMETHOD;
    }

    /* Create SSL context for the listener */
    ctx = SSL_CTX_new(ssl_method);
    if (ctx == NULL) {
	ssl_report_error(lis_name, 4, PJ_SUCCESS,
			 "Error creating SSL context");
	return PJSIP_TLS_ECTX;
    }


    /* Load CA list if one is specified. */
    if (opt->ca_list_file.slen) {

	/* Can only take a NULL terminated filename in the setting */
	pj_assert(opt->ca_list_file.ptr[opt->ca_list_file.slen] == '\0');

	rc = SSL_CTX_load_verify_locations(ctx, opt->ca_list_file.ptr, NULL);

	if (rc != 1) {
	    ssl_report_error(lis_name, 4, PJ_SUCCESS,
			     "Error loading/verifying CA list file '%.*s'",
			     (int)opt->ca_list_file.slen,
			     opt->ca_list_file.ptr);
	    SSL_CTX_free(ctx);
	    return PJSIP_TLS_ECACERT;
	}

	PJ_LOG(5,(lis_name, "TLS CA file successfully loaded from '%.*s'",
		  (int)opt->ca_list_file.slen,
		  opt->ca_list_file.ptr));
    }
    
    /* Set password callback */
    SSL_CTX_set_default_passwd_cb(ctx, password_cb);
    SSL_CTX_set_default_passwd_cb_userdata(ctx, lis);


    /* Load certificate if one is specified */
    if (opt->cert_file.slen) {

	/* Can only take a NULL terminated filename in the setting */
	pj_assert(opt->cert_file.ptr[opt->cert_file.slen] == '\0');

	/* Load certificate chain from file into ctx */
	rc = SSL_CTX_use_certificate_chain_file(ctx, opt->cert_file.ptr);

	if(rc != 1) {
	    ssl_report_error(lis_name, 4, PJ_SUCCESS,
			     "Error loading certificate chain file '%.*s'",
			     (int)opt->cert_file.slen,
			     opt->cert_file.ptr);
	    SSL_CTX_free(ctx);
	    return PJSIP_TLS_ECERTFILE;
	}

	PJ_LOG(5,(lis_name, "TLS certificate successfully loaded from '%.*s'",
		  (int)opt->cert_file.slen,
		  opt->cert_file.ptr));
    }


    /* Load private key if one is specified */
    if (opt->privkey_file.slen) {

	/* Can only take a NULL terminated filename in the setting */
	pj_assert(opt->privkey_file.ptr[opt->privkey_file.slen] == '\0');

	/* Adds the first private key found in file to ctx */
	rc = SSL_CTX_use_PrivateKey_file(ctx, opt->privkey_file.ptr, 
					 SSL_FILETYPE_PEM);

	if(rc != 1) {
	    ssl_report_error(lis_name, 4, PJ_SUCCESS,
			     "Error adding private key from '%.*s'",
			     (int)opt->privkey_file.slen,
			     opt->privkey_file.ptr);
	    SSL_CTX_free(ctx);
	    return PJSIP_TLS_EKEYFILE;
	}

	PJ_LOG(5,(lis_name, "TLS private key successfully loaded from '%.*s'",
		  (int)opt->privkey_file.slen,
		  opt->privkey_file.ptr));
    }


    /* SSL verification options */
    if (lis->setting.verify_client || lis->setting.verify_server) {
	mode = SSL_VERIFY_PEER;
	if (lis->setting.require_client_cert)
	    mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
    } else {
	mode = SSL_VERIFY_NONE;
    }

    SSL_CTX_set_verify(ctx, mode, NULL);

    PJ_LOG(5,(lis_name, "TLS verification mode set to %d", mode));

    /* Optionally set cipher list if one is specified */
    if (opt->ciphers.slen) {
	/* Can only take a NULL terminated cipher list in the setting */
	pj_assert(opt->cert_file.ptr[opt->cert_file.slen] == '\0');

	rc = SSL_CTX_set_cipher_list(ctx, opt->ciphers.ptr);
	if (rc != 1) {
	    ssl_report_error(lis_name, 4, PJ_SUCCESS,
			     "Error setting cipher list '%.*s'",
			     (int)opt->ciphers.slen,
			     opt->ciphers.ptr);
	    SSL_CTX_free(ctx);
	    return PJSIP_TLS_ECIPHER;
	}

	PJ_LOG(5,(lis_name, "TLS ciphers set to '%.*s'",
		  (int)opt->ciphers.slen,
		  opt->ciphers.ptr));
    }

    /* Done! */

    *p_ctx = ctx;
    return PJ_SUCCESS;
}

/* Destroy SSL context */
static void destroy_ctx(SSL_CTX *ctx)
{
    SSL_CTX_free(ctx);

    /* Potentially shutdown OpenSSL library if this is the last
     * context exists.
     */
    shutdown_openssl();
}

/*
 * Perform SSL_connect upon completion of socket connect()
 */
static pj_status_t ssl_connect(struct tls_transport *tls)
{
    SSL *ssl = tls->ssl;
    int status;

    if (SSL_is_init_finished (ssl))
	return PJ_SUCCESS;

    if (SSL_get_fd(ssl) < 0)
	SSL_set_fd(ssl, (int)tls->sock);

    if (!SSL_in_connect_init(ssl))
	SSL_set_connect_state(ssl);

#ifdef SSL_set_tlsext_host_name
    if (tls->setting.server_name.slen) {
	char server_name[PJ_MAX_HOSTNAME];

	if (tls->setting.server_name.slen >= PJ_MAX_HOSTNAME)
	    return PJ_ENAMETOOLONG;

	pj_memcpy(server_name, tls->setting.server_name.ptr, 
		  tls->setting.server_name.slen);
	server_name[tls->setting.server_name.slen] = '\0';

	if (!SSL_set_tlsext_host_name(ssl, server_name)) {
	    PJ_LOG(4,(tls->base.obj_name, 
		      "SSL_set_tlsext_host_name() failed"));
	}
    }
#endif

    PJ_LOG(5,(tls->base.obj_name, "Starting SSL_connect() negotiation"));

    do {
	/* These handle sets are used to set up for whatever SSL_connect
	 * says it wants next. They're reset on each pass around the loop.
	 */
	pj_fd_set_t rd_set;
	pj_fd_set_t wr_set;
	
	PJ_FD_ZERO(&rd_set);
	PJ_FD_ZERO(&wr_set);

	status = SSL_connect (ssl);
	switch (SSL_get_error (ssl, status)) {
        case SSL_ERROR_NONE:
	    /* Success */
	    status = 0;
	    PJ_LOG(5,(tls->base.obj_name, 
		      "SSL_connect() negotiation completes successfully"));
	    break;

        case SSL_ERROR_WANT_WRITE:
	    /* Wait for more activity */
	    PJ_FD_SET(tls->sock, &wr_set);
	    status = 1;
	    break;
	    
        case SSL_ERROR_WANT_READ:
	    /* Wait for more activity */
	    PJ_FD_SET(tls->sock, &rd_set);
	    status = 1;
	    break;
	    
        case SSL_ERROR_ZERO_RETURN:
	    /* The peer has notified us that it is shutting down via
	     * the SSL "close_notify" message so we need to
	     * shutdown, too.
	     */
	    PJ_LOG(4,(THIS_FILE, "SSL connect() failed, remote has"
				 "shutdown connection."));
	    return PJ_STATUS_FROM_OS(OSERR_ENOTCONN);
	    
        case SSL_ERROR_SYSCALL:
	    /* On some platforms (e.g. MS Windows) OpenSSL does not
	     * store the last error in errno so explicitly do so.
	     *
	     * Explicitly check for EWOULDBLOCK since it doesn't get
	     * converted to an SSL_ERROR_WANT_{READ,WRITE} on some
	     * platforms. If SSL_connect failed outright, though, don't
	     * bother checking more. This can happen if the socket gets
	     * closed during the handshake.
	     */
	    if (pj_get_netos_error() == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) &&
		status == -1)
            {
		/* Although the SSL_ERROR_WANT_READ/WRITE isn't getting
		 * set correctly, the read/write state should be valid.
		 * Use that to decide what to do.
		 */
		status = 1;               /* Wait for more activity */
		if (SSL_want_write (ssl))
		    PJ_FD_SET(tls->sock, &wr_set);
		else if (SSL_want_read (ssl))
		    PJ_FD_SET(tls->sock, &rd_set);
		else
		    status = -1;	/* Doesn't want anything - bail out */
            }
	    else {
		status = -1;
	    }
	    break;

        default:
	    ssl_report_error(tls->base.obj_name, 4, PJ_SUCCESS,
			     "SSL_connect() error");
	    status = -1;
	    break;
        }
	
	if (status == 1) {
	    pj_time_val timeout, *p_timeout;

	    /* Must have at least one handle to wait for at this point. */
	    pj_assert(PJ_FD_COUNT(&rd_set) == 1 || PJ_FD_COUNT(&wr_set) == 1);
	    
	    /* This will block the whole stack!!! */
	    PJ_TODO(SUPPORT_SSL_ASYNCHRONOUS_CONNECT);

	    if (tls->setting.timeout.sec == 0 &&
		tls->setting.timeout.msec == 0)
	    {
		p_timeout = NULL;
	    } else {
		timeout = tls->setting.timeout;
		p_timeout = &timeout;
	    }

	    /* Block indefinitely if timeout pointer is zero. */
	    status = pj_sock_select(tls->sock+1, &rd_set, &wr_set,
				    NULL, p_timeout);
	    	    
	    /* 0 is timeout, so we're done.
	     * -1 is error, so we're done.
	     * Could be both handles set (same handle in both masks) so set to 1.
	     */
	    if (status >= 1)
		status = 1;
	    else if (status == 0)
		return PJSIP_TLS_ETIMEDOUT;
	    else
		status = -1;
        }
	
    } while (status == 1 && !SSL_is_init_finished (ssl));
        
    return (status == -1 ? PJSIP_TLS_ECONNECT : PJ_SUCCESS);
}


/*
 * Perform SSL_accept() on the newly established incoming TLS connection.
 */
static pj_status_t ssl_accept(struct tls_transport *tls)
{
    SSL *ssl = tls->ssl;
    int rc;
    
    if (SSL_is_init_finished (ssl))
	return PJ_SUCCESS;
    
    if (!SSL_in_accept_init(ssl))
	SSL_set_accept_state(ssl);

    PJ_LOG(5,(tls->base.obj_name, "Starting SSL_accept() negotiation"));

    /* Repeat retrying SSL_accept() procedure until it completes either
     * successfully or with failure.
     */
    do {

	/* These handle sets are used to set up for whatever SSL_accept says
	 * it wants next. They're reset on each pass around the loop.
	 */
	pj_fd_set_t rd_set;
	pj_fd_set_t wr_set;
	
	PJ_FD_ZERO(&rd_set);
	PJ_FD_ZERO(&wr_set);

	rc = SSL_accept (ssl);

	switch (SSL_get_error (ssl, rc)) {
        case SSL_ERROR_NONE:
	    /* Success! */
	    rc = 0;
	    PJ_LOG(5,(tls->base.obj_name, 
		      "SSL_accept() negotiation completes successfully"));
	    break;
	    
        case SSL_ERROR_WANT_WRITE:
	    PJ_FD_SET(tls->sock, &wr_set);
	    rc = 1;               /* Wait for more activity */
	    break;
	    
        case SSL_ERROR_WANT_READ:
	    PJ_FD_SET(tls->sock, &rd_set);
	    rc = 1;               /* Need to read more data */
	    break;

        case SSL_ERROR_ZERO_RETURN:
	    /* The peer has notified us that it is shutting down via the SSL 
	     * "close_notify" message so we need to shutdown, too.
	     */
	    PJ_LOG(4,(tls->base.obj_name,  
		      "Incoming SSL connection closed prematurely by client"));
	    return PJ_STATUS_FROM_OS(OSERR_ENOTCONN);

        case SSL_ERROR_SYSCALL:
	    /* Explicitly check for EWOULDBLOCK since it doesn't get converted
	     * to an SSL_ERROR_WANT_{READ,WRITE} on some platforms. 
	     * If SSL_accept failed outright, though, don't bother checking 
	     * more. This can happen if the socket gets closed during the 
	     * handshake.
	     */
	    if (pj_get_netos_error()==PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) 
		&& rc==-1)
            {
		/* Although the SSL_ERROR_WANT_READ/WRITE isn't getting set 
		 * correctly, the read/write state should be valid. Use that 
		 * to decide what to do.
		 */
		rc = 1;               /* Wait for more activity */
		if (SSL_want_write(ssl))
		    PJ_FD_SET(tls->sock, &wr_set);
		else if (SSL_want_read(ssl))
		    PJ_FD_SET(tls->sock, &rd_set);
		else {
		    /* Doesn't want anything - bail out */
		    return PJ_STATUS_FROM_OS(OSERR_ENOTCONN);
		}
            }
	    else {
		return PJSIP_TLS_EUNKNOWN;
	    }
	    break;
	    
        default:
	    ssl_report_error(tls->base.obj_name, 4, PJ_SUCCESS,
			     "Error calling SSL_accept()");
	    return pj_get_netos_error() ? pj_get_netos_error() : 
		    PJSIP_TLS_EUNKNOWN;
        }
	
	if (rc == 1) {

	    pj_time_val timeout, *p_timeout;

	    /* Must have at least one handle to wait for at this point. */
	    pj_assert(PJ_FD_COUNT(&rd_set) == 1 || PJ_FD_COUNT(&wr_set) == 1);

	    if (tls->setting.timeout.sec == 0 &&
		tls->setting.timeout.msec == 0)
	    {
		p_timeout = NULL;
	    } else {
		timeout = tls->setting.timeout;
		p_timeout = &timeout;
	    }

	    rc = pj_sock_select(tls->sock+1, &rd_set, &wr_set, NULL, 
			        p_timeout);
	    
	    if (rc >= 1)
		rc = 1;
	    else if (rc == 0)
		return PJSIP_TLS_ETIMEDOUT;
	    else
		return pj_get_netos_error();
        }
	
    } while (rc == 1 && !SSL_is_init_finished(ssl));
    
    return (rc == -1 ? PJSIP_TLS_EUNKNOWN : PJ_SUCCESS);
}


/* Send outgoing data with SSL connection */
static pj_status_t ssl_write_bytes(struct tls_transport *tls,
				   const void *data,
				   int size,
				   const char *data_name)
{
    int sent = 0;

    do {
	const int fragment_sent = SSL_write(tls->ssl,
					    ((pj_uint8_t*)data) + sent, 
					    size - sent);
    
	switch( SSL_get_error(tls->ssl, fragment_sent)) {
	case SSL_ERROR_NONE:
	    sent += fragment_sent;
	    break;
	    
	case SSL_ERROR_WANT_READ:
	case SSL_ERROR_WANT_WRITE:
	    /* For now, we can't handle situation where WANT_READ/WANT_WRITE
	     * is raised after some data has been sent, since we don't have
	     * mechanism to keep track of how many bytes have been sent
	     * inside the individual tdata.
	     */
	    pj_assert(sent == 0);
	    PJ_TODO(PARTIAL_SSL_SENT);
	    return PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK);
	    
	case SSL_ERROR_ZERO_RETURN:
	    /* The peer has notified us that it is shutting down via the SSL
	     * "close_notify" message. Tell the transport manager that it
	     * shouldn't use this transport any more and return ENOTCONN
	     * to caller.
	     */
	    
	    /* It is safe to call this multiple times. */
	    pjsip_transport_shutdown(&tls->base);

	    return PJ_STATUS_FROM_OS(OSERR_ENOTCONN);
	    
	case SSL_ERROR_SYSCALL:
	    if (fragment_sent == 0) {
		/* An EOF occured but the SSL "close_notify" message was not
		 * sent. Shutdown the transport and return ENOTCONN.
		 */

		/* It is safe to call this multiple times. */
		pjsip_transport_shutdown(&tls->base);

		return PJ_STATUS_FROM_OS(OSERR_ENOTCONN);
	    }
	    
	    /* Other error */
	    return pj_get_netos_error();

	default:
	    ssl_report_error(tls->base.obj_name, 4, PJ_SUCCESS,
			     "Error sending %s with SSL_write()",
			     data_name);
	    return pj_get_netos_error() ? pj_get_netos_error() 
		    : PJSIP_TLS_ESEND;
	}
    
    } while (sent < size);

    return PJ_SUCCESS;

}

/* Send outgoing tdata with SSL connection */
static pj_status_t ssl_write(struct tls_transport *tls,
			     pjsip_tx_data *tdata)
{
    return ssl_write_bytes(tls, tdata->buf.start, 
			   tdata->buf.cur - tdata->buf.start,
			   pjsip_tx_data_get_info(tdata));
}


/* Read data from SSL connection */
static pj_status_t ssl_read(struct tls_transport *tls)
{
    pjsip_rx_data *rdata = &tls->rdata;

    int bytes_read, max_size;

    max_size = sizeof(rdata->pkt_info.packet) - rdata->pkt_info.len;
    bytes_read = SSL_read(tls->ssl, 
			  rdata->pkt_info.packet+rdata->pkt_info.len,
                          max_size);

    switch (SSL_get_error(tls->ssl, bytes_read)) {
    case SSL_ERROR_NONE:
	/* Data successfully read */
	rdata->pkt_info.len += bytes_read;
	return PJ_SUCCESS;
	
    case SSL_ERROR_WANT_READ:
    case SSL_ERROR_WANT_WRITE:
	return PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK);
	
    case SSL_ERROR_ZERO_RETURN:
	/* The peer has notified us that it is shutting down via the SSL
	 * "close_notify" message.
	 */
	pjsip_transport_shutdown(&tls->base);
	return PJ_STATUS_FROM_OS(OSERR_ENOTCONN);
	
    case SSL_ERROR_SYSCALL:
	if (bytes_read == 0) {
	    /* An EOF occured but the SSL "close_notify" message was not
	     * sent.
	     */
	    pjsip_transport_shutdown(&tls->base);
	    return PJ_STATUS_FROM_OS(OSERR_ENOTCONN);
	}
	
	/* Other error */
	return pj_get_netos_error();
	
    default:
	ssl_report_error(tls->base.obj_name, 4, PJ_SUCCESS,
			 "Error reading data with SSL_read()");
	return pj_get_netos_error() ? pj_get_netos_error() 
		: PJSIP_TLS_EREAD;
    }

    /* Should not reach here */
}


/****************************************************************************
 * The TLS listener/transport factory.
 */

/*
 * This is the public API to create, initialize, register, and start the
 * TLS listener.
 */
PJ_DEF(pj_status_t) pjsip_tls_transport_start( pjsip_endpoint *endpt,
					       const pjsip_tls_setting *opt,
					       const pj_sockaddr_in *local,
					       const pjsip_host_port *a_name,
					       unsigned async_cnt,
					       pjsip_tpfactory **p_factory)
{
    pj_pool_t *pool;
    struct tls_listener *listener;
    pj_ioqueue_callback listener_cb;
    pj_sockaddr_in *listener_addr;
    int addr_len;
    unsigned i;
    pj_status_t status;

    /* Sanity check */
    PJ_ASSERT_RETURN(endpt && async_cnt, PJ_EINVAL);

    /* Verify that address given in a_name (if any) is valid */
    if (a_name && a_name->host.slen) {
	pj_sockaddr_in tmp;

	status = pj_sockaddr_in_init(&tmp, &a_name->host, 
				     (pj_uint16_t)a_name->port);
	if (status != PJ_SUCCESS || tmp.sin_addr.s_addr == PJ_INADDR_ANY ||
	    tmp.sin_addr.s_addr == PJ_INADDR_NONE)
	{
	    /* Invalid address */
	    return PJ_EINVAL;
	}
    }

    pool = pjsip_endpt_create_pool(endpt, "tlslis", POOL_LIS_INIT, 
				   POOL_LIS_INC);
    PJ_ASSERT_RETURN(pool, PJ_ENOMEM);


    listener = PJ_POOL_ZALLOC_T(pool, struct tls_listener);
    listener->factory.pool = pool;
    listener->factory.type = PJSIP_TRANSPORT_TLS;
959
    listener->factory.type_name = "tls";
Emmanuel Milou's avatar
Emmanuel Milou committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    listener->factory.flag = 
	pjsip_transport_get_flag_from_type(PJSIP_TRANSPORT_TLS);
    listener->sock = PJ_INVALID_SOCKET;
    
    /* Create object name */
    pj_ansi_snprintf(listener->factory.obj_name, 
		     sizeof(listener->factory.obj_name),
		     "tls%p",  listener);
    
    /* Create duplicate of TLS settings */
    if (opt)
	pjsip_tls_setting_copy(pool, &listener->setting, opt);
    else
	pjsip_tls_setting_default(&listener->setting);

    /* Initialize SSL context to be used by this listener */
    status = create_ctx(listener, &listener->ctx);
    if (status != PJ_SUCCESS)
	goto on_error;

    status = pj_lock_create_recursive_mutex(pool, "tlslis", 
					    &listener->factory.lock);
    if (status != PJ_SUCCESS)
	goto on_error;


    /* Create and bind socket */
    status = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, &listener->sock);
    if (status != PJ_SUCCESS)
	goto on_error;

    listener_addr = (pj_sockaddr_in*)&listener->factory.local_addr;
    if (local) {
	pj_memcpy(listener_addr, local, sizeof(pj_sockaddr_in));
    } else {
	pj_sockaddr_in_init(listener_addr, NULL, 0);
    }

    status = pj_sock_bind(listener->sock, listener_addr, 
			  sizeof(pj_sockaddr_in));
    if (status != PJ_SUCCESS)
For faster browsing, not all history is shown. View entire blame