-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathcom_wolfssl_WolfSSLSession.c
6082 lines (5218 loc) · 181 KB
/
com_wolfssl_WolfSSLSession.c
1
2
3
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
959
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
/* com_wolfssl_WolfSSLSession.c
*
* Copyright (C) 2006-2025 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL 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.
*
* wolfSSL 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
#include <stdio.h>
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#else
#include <wolfssl/options.h>
#endif
#ifndef USE_WINDOWS_API
#include <sys/time.h>
#include <arpa/inet.h>
#include <sys/errno.h>
#if defined(WOLFJNI_USE_IO_SELECT)
#include <sys/select.h>
#else
#include <poll.h>
#endif
#endif
#ifndef WOLFSSL_JNI_DEFAULT_PEEK_TIMEOUT
/* Default wolfSSL_peek() timeout for wolfSSL_get_session(), ms */
#define WOLFSSL_JNI_DEFAULT_PEEK_TIMEOUT 2000
#endif
#include <wolfssl/ssl.h>
#include <wolfssl/error-ssl.h>
#include "com_wolfssl_globals.h"
#include "com_wolfssl_WolfSSL.h"
/* custom I/O native fn prototypes */
int NativeSSLIORecvCb(WOLFSSL *ssl, char *buf, int sz, void *ctx);
int NativeSSLIOSendCb(WOLFSSL *ssl, char *buf, int sz, void *ctx);
/* ALPN select native callback prototype */
int NativeALPNSelectCb(WOLFSSL *ssl, const unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen, void *arg);
/* TLS 1.3 secret native callback prototype */
int NativeTls13SecretCb(WOLFSSL *ssl, int id, const unsigned char* secret,
int secretSz, void* ctx);
#ifdef HAVE_CRL
/* global object refs for CRL callback */
static jobject g_crlCbIfaceObj;
#endif
/* Data used per-WOLFSSL session that needs to be stored across native
* function calls. Stored inside WOLFSSL app data, set with
* wolfSSL_set_app_data(), retrieved with wolfSSL_get_app_data().
* Global callback objects are created with NewGlobalRef(), then freed
* inside freeSSL() with DeleteGlobalRef().
*
* interruptFds[2] is a pipe() used for non-Windows platforms. This pipe is
* used to interrupt threads blocked inside select()/poll() when a separate
* Java thread calls close() on the SSLSocket. */
typedef struct SSLAppData {
int threadsInPoll; /* number of threads in poll/select() */
#ifndef USE_WINDOWS_API
int interruptFds[2]; /* pipe for interrupting socketSelect() */
wolfSSL_Mutex* pollCountLock; /* lock around threadsInPoll */
#endif
wolfSSL_Mutex* jniSessLock; /* WOLFSSL session lock */
jobject* g_verifySSLCbIfaceObj; /* Java verify callback [global ref] */
} SSLAppData;
/* custom native fn prototypes */
void NativeMissingCRLCallback(const char* url);
int NativeSSLVerifyCallback(int preverify_ok, WOLFSSL_X509_STORE_CTX* store);
int NativeSSLVerifyCallback(int preverify_ok, WOLFSSL_X509_STORE_CTX* store)
{
JNIEnv* jenv;
jint vmret = 0;
jint retval = -1;
jclass excClass;
jclass verifyClass = NULL;
jmethodID verifyMethod;
jobjectRefType refcheck;
SSLAppData* appData; /* WOLFSSL app data, stored verify cb obj */
jobject* g_verifySSLCbIfaceObj; /* Global jobject, stored in app data */
if (!g_vm) {
/* we can't throw an exception yet, so just return 0 (failure) */
return 0;
}
/* get JNIEnv from JavaVM */
vmret = (int)((*g_vm)->GetEnv(g_vm, (void**) &jenv, JNI_VERSION_1_6));
if (vmret == JNI_EDETACHED) {
#ifdef __ANDROID__
vmret = (*g_vm)->AttachCurrentThread(g_vm, &jenv, NULL);
#else
vmret = (*g_vm)->AttachCurrentThread(g_vm, (void**) &jenv, NULL);
#endif
if (vmret) {
return -101; /* failed to attach JNIEnv to thread */
}
} else if (vmret != JNI_OK) {
return -102; /* unable to get JNIEnv from JavaVM */
}
/* find exception class */
excClass = (*jenv)->FindClass(jenv, "com/wolfssl/WolfSSLException");
if( (*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
return -103;
}
/* get app data to retrieve stored Java jobject callback object */
appData = (SSLAppData*)wolfSSL_get_app_data(
wolfSSL_X509_STORE_CTX_get_ex_data(store, 0));
if (appData == NULL) {
printf("Error getting app data from WOLFSSL\n");
return -105;
}
/* get global Java verify callback object */
g_verifySSLCbIfaceObj = appData->g_verifySSLCbIfaceObj;
if (g_verifySSLCbIfaceObj == NULL || *g_verifySSLCbIfaceObj == NULL) {
printf("Error getting g_verifySSLCbIfaceObj from appData\n");
return -106;
}
/* check if our stored object reference is valid */
refcheck = (*jenv)->GetObjectRefType(jenv, *g_verifySSLCbIfaceObj);
if (refcheck == 2) {
/* lookup WolfSSLVerifyCallback class from global object ref */
verifyClass = (*jenv)->GetObjectClass(jenv, *g_verifySSLCbIfaceObj);
if (!verifyClass) {
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
}
(*jenv)->ThrowNew(jenv, excClass,
"Can't get native WolfSSLVerifyCallback class reference");
return -107;
}
verifyMethod = (*jenv)->GetMethodID(jenv, verifyClass,
"verifyCallback", "(IJ)I");
if (verifyMethod == 0) {
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
}
(*jenv)->ThrowNew(jenv, excClass,
"Error getting verifyCallback method from JNI");
return -108;
}
retval = (*jenv)->CallIntMethod(jenv, *g_verifySSLCbIfaceObj,
verifyMethod, preverify_ok, (jlong)(uintptr_t)store);
if ((*jenv)->ExceptionOccurred(jenv)) {
/* exception occurred on the Java side during method call */
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
return -109;
}
} else {
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
}
(*jenv)->ThrowNew(jenv, excClass,
"Object reference invalid in NativeSSLVerifyCallback");
return -1;
}
return retval;
}
#ifndef USE_WINDOWS_API
/* Close interrupt pipe() descriptors and reset back to -1. */
static void closeInterruptPipe(SSLAppData* appData)
{
if (appData != NULL) {
if (appData->interruptFds[0] != -1) {
close(appData->interruptFds[0]);
appData->interruptFds[0] = -1;
}
if (appData->interruptFds[1] != -1) {
close(appData->interruptFds[1]);
appData->interruptFds[1] = -1;
}
}
}
/* Signal to threads blocked in select() or poll() to wake up, by writing
* one byte to the appData.interruptFds[1] pipe. */
static void writeToInterruptPipe(SSLAppData* appData)
{
if (appData != NULL) {
if (appData->interruptFds[1] != -1) {
write(appData->interruptFds[1], "1", 1);
}
}
}
#endif /* !USE_WINDOWS_API */
/* Return number of threads waiting in poll()/select() */
static int threadsWaitingInPollSelect(SSLAppData* appData)
{
int ret = 0;
#ifndef USE_WINDOWS_API
wolfSSL_Mutex* pollCountLock = NULL;
if (appData != NULL) {
pollCountLock = appData->pollCountLock;
if (pollCountLock != NULL) {
if (wc_LockMutex(pollCountLock) == 0) {
ret = appData->threadsInPoll;
wc_UnLockMutex(pollCountLock);
}
}
}
#endif
return ret;
}
static void incrementThreadPollCount(SSLAppData* appData)
{
#ifndef USE_WINDOWS_API
wolfSSL_Mutex* pollCountLock = NULL;
if (appData == NULL) {
return;
}
pollCountLock = appData->pollCountLock;
if (pollCountLock == NULL) {
return;
}
if (wc_LockMutex(pollCountLock) != 0) {
return;
}
appData->threadsInPoll++;
wc_UnLockMutex(pollCountLock);
#endif
}
static void decrementThreadPollCount(SSLAppData* appData)
{
#ifndef USE_WINDOWS_API
wolfSSL_Mutex* pollCountLock = NULL;
if (appData == NULL) {
return;
}
pollCountLock = appData->pollCountLock;
if (pollCountLock == NULL) {
return;
}
if (wc_LockMutex(pollCountLock) != 0) {
return;
}
if (appData->threadsInPoll > 0) {
appData->threadsInPoll--;
}
wc_UnLockMutex(pollCountLock);
#endif
}
JNIEXPORT jlong JNICALL Java_com_wolfssl_WolfSSLSession_newSSL
(JNIEnv* jenv, jobject jcl, jlong ctx, jboolean withIOPipe)
{
int ret;
jlong sslPtr = 0;
jobject* g_cachedSSLObj = NULL;
wolfSSL_Mutex* jniSessLock = NULL;
#ifndef USE_WINDOWS_API
wolfSSL_Mutex* pollCountLock = NULL;
#endif
SSLAppData* appData = NULL;
if (jenv == NULL) {
return SSL_FAILURE;
}
/* wolfSSL java caller checks for null pointer */
sslPtr = (jlong)(uintptr_t)wolfSSL_new((WOLFSSL_CTX*)(uintptr_t)ctx);
if (sslPtr != 0) {
/* create global reference to WolfSSLSession jobject */
g_cachedSSLObj = (jobject*)XMALLOC(sizeof(jobject), NULL,
DYNAMIC_TYPE_TMP_BUFFER);
if (g_cachedSSLObj == NULL) {
printf("error mallocing memory in newSSL\n");
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
*g_cachedSSLObj = (*jenv)->NewGlobalRef(jenv, jcl);
if (*g_cachedSSLObj == NULL) {
printf("error storing global WolfSSLSession object\n");
XFREE(g_cachedSSLObj, NULL, DYNAMIC_TYPE_TMP_BUFFER);
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
appData = (SSLAppData*)XMALLOC(sizeof(SSLAppData), NULL,
DYNAMIC_TYPE_TMP_BUFFER);
if (appData == NULL) {
printf("error allocating memory in newSSL for SSLAppData\n");
(*jenv)->DeleteGlobalRef(jenv, *g_cachedSSLObj);
XFREE(g_cachedSSLObj, NULL, DYNAMIC_TYPE_TMP_BUFFER);
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
XMEMSET(appData, 0, sizeof(SSLAppData));
/* store mutex lock in SSL app data, used for I/O and session lock.
* This is freed in freeSSL. */
jniSessLock = (wolfSSL_Mutex*)XMALLOC(sizeof(wolfSSL_Mutex), NULL,
DYNAMIC_TYPE_TMP_BUFFER);
if (!jniSessLock) {
printf("error mallocing memory in newSSL for jniSessLock\n");
(*jenv)->DeleteGlobalRef(jenv, *g_cachedSSLObj);
XFREE(appData, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(g_cachedSSLObj, NULL, DYNAMIC_TYPE_TMP_BUFFER);
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
wc_InitMutex(jniSessLock);
appData->jniSessLock = jniSessLock;
/* set up interrupt pipe for SSLSocket.close() to use if/when needed.
* currently only non-Windows platforms supported due to Windows not
* supporting direct/same pipe() operation. Make read pipe non
* blocking since byte read from it could have already been taken
* out by either reader/writer thread before the other has a chance
* to read it. But, we only use it for waking us up and don't care
* much about actually reading the byte passed over the pipe. */
appData->threadsInPoll = 0;
#ifndef USE_WINDOWS_API
pollCountLock = (wolfSSL_Mutex*)XMALLOC(sizeof(wolfSSL_Mutex), NULL,
DYNAMIC_TYPE_TMP_BUFFER);
if (pollCountLock == NULL) {
printf("error mallocing pollCountLock in newSSL for SSLAppData\n");
(*jenv)->DeleteGlobalRef(jenv, *g_cachedSSLObj);
XFREE(jniSessLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(appData, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(g_cachedSSLObj, NULL, DYNAMIC_TYPE_TMP_BUFFER);
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
wc_InitMutex(pollCountLock);
appData->pollCountLock = pollCountLock;
appData->interruptFds[0] = -1;
appData->interruptFds[1] = -1;
if (withIOPipe == JNI_TRUE) {
ret = pipe(appData->interruptFds);
if (ret == -1) {
printf("error setting up pipe() for interruptFds[] in newSSL\n");
(*jenv)->DeleteGlobalRef(jenv, *g_cachedSSLObj);
XFREE(pollCountLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(jniSessLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(appData, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(g_cachedSSLObj, NULL, DYNAMIC_TYPE_TMP_BUFFER);
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
ret = fcntl(appData->interruptFds[0], F_SETFL,
fcntl(appData->interruptFds[0], F_GETFL, 0) | O_NONBLOCK);
if (ret < 0) {
printf("error setting interruptFds[0] non-blocking in newSSL\n");
closeInterruptPipe(appData);
(*jenv)->DeleteGlobalRef(jenv, *g_cachedSSLObj);
XFREE(pollCountLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(jniSessLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(appData, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(g_cachedSSLObj, NULL, DYNAMIC_TYPE_TMP_BUFFER);
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
}
#endif /* !USE_WINDOWS_API */
/* cache associated WolfSSLSession jobject in native WOLFSSL */
ret = wolfSSL_set_jobject((WOLFSSL*)(uintptr_t)sslPtr, g_cachedSSLObj);
if (ret != SSL_SUCCESS) {
printf("error storing jobject in wolfSSL native session\n");
(*jenv)->DeleteGlobalRef(jenv, *g_cachedSSLObj);
#ifndef USE_WINDOWS_API
closeInterruptPipe(appData);
XFREE(pollCountLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
XFREE(jniSessLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(appData, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(g_cachedSSLObj, NULL, DYNAMIC_TYPE_TMP_BUFFER);
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
/* cache SSLAppData into native WOLFSSL */
if (wolfSSL_set_app_data(
(WOLFSSL*)(uintptr_t)sslPtr, appData) != SSL_SUCCESS) {
printf("error setting WOLFSSL app data in newSSL\n");
(*jenv)->DeleteGlobalRef(jenv, *g_cachedSSLObj);
#ifndef USE_WINDOWS_API
closeInterruptPipe(appData);
XFREE(pollCountLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
XFREE(jniSessLock, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(appData, NULL, DYNAMIC_TYPE_TMP_BUFFER);
XFREE(g_cachedSSLObj, NULL, DYNAMIC_TYPE_TMP_BUFFER);
wolfSSL_set_jobject((WOLFSSL*)(uintptr_t)sslPtr, NULL);
wolfSSL_free((WOLFSSL*)(uintptr_t)sslPtr);
return SSL_FAILURE;
}
}
return sslPtr;
}
JNIEXPORT jint JNICALL Java_com_wolfssl_WolfSSLSession_setFd(JNIEnv* jenv,
jobject jcl, jlong sslPtr, jobject jsock, jint type)
{
int fd;
int ret = SSL_SUCCESS;
jclass jcls;
jfieldID fid;
jobject impl;
jobject fdesc;
#ifdef USE_WINDOWS_API
unsigned long blocking = 0;
#endif
WOLFSSL* ssl = (WOLFSSL*)(uintptr_t)sslPtr;
(void)jcl;
if (jenv == NULL || ssl == NULL || jsock == NULL) {
printf("Error: bad function args, native setFd() wrapper\n");
return SSL_FAILURE;
}
/* get SocketImpl (type 1) or DatagramSocketImpl (2) from Java Socket */
jcls = (*jenv)->GetObjectClass(jenv, jsock);
if (type == 1) {
/* Get SocketImpl field 'impl' from Socket class */
fid = (*jenv)->GetFieldID(jenv, jcls, "impl", "Ljava/net/SocketImpl;");
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
printf("Error: Failed to get SocketImpl impl FieldID\n");
return SSL_FAILURE;
}
/* Get SocketImpl 'impl' object */
impl = (*jenv)->GetObjectField(jenv, jsock, fid);
/* SocketImpl object may hold a delegate object inside on
* some Java versions. Delegate SocketImpl is held inside 'impl'
* object in field 'delegate'. Here we try to get the 'delegate'
* field ID. If NULL, there is no 'delegate' member and we fall back
* to using 'impl' directly. */
jcls = (*jenv)->GetObjectClass(jenv, impl);
fid = (*jenv)->GetFieldID(jenv, jcls, "delegate", "Ljava/net/SocketImpl;");
if (fid != NULL) {
/* delegate field exists, try to get object */
impl = (*jenv)->GetObjectField(jenv, impl, fid);
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
/* Exception while getting delegate field, but does exist */
printf("Error: Exception while getting SocketImpl delegate\n");
return SSL_FAILURE;
}
} else {
/* if delegate field does not exist, can cause NoSuchFieldError
* exception. Clear out before continuing, but don't
* print exception description (we expect it to happen). */
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionClear(jenv);
}
}
} else if (type == 2) {
fid = (*jenv)->GetFieldID(jenv, jcls, "impl",
"Ljava/net/DatagramSocketImpl;");
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
printf("Error: Exception while getting DatagramSocketImpl "
"impl FieldID\n");
return SSL_FAILURE;
}
impl = (*jenv)->GetObjectField(jenv, jsock, fid);
} else {
printf("Invalid Socket class type, not supported\n");
return SSL_FAILURE; /* invalid class type */
}
if (impl == NULL) {
printf("Error: SocketImpl impl is NULL! Not valid\n");
return SSL_FAILURE;
}
/* get FileDescriptor from SocketImpl */
jcls = (*jenv)->GetObjectClass(jenv, impl);
fid = (*jenv)->GetFieldID(jenv, jcls, "fd", "Ljava/io/FileDescriptor;");
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
printf("Error: Exception while getting FileDescriptor fd FieldID\n");
return SSL_FAILURE;
}
fdesc = (*jenv)->GetObjectField(jenv, impl, fid);
if (fdesc == NULL) {
printf("Info: FileDescriptor fd object is NULL!\n");
return SSL_FAILURE;
}
/* get fd from FileDescriptor */
jcls = (*jenv)->GetObjectClass(jenv, fdesc);
#ifdef __ANDROID__
fid = (*jenv)->GetFieldID(jenv, jcls, "descriptor", "I");
#else
fid = (*jenv)->GetFieldID(jenv, jcls, "fd", "I");
#endif
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
printf("Error: Exception while getting fd/descriptor FieldID\n");
return SSL_FAILURE;
}
if (jcls == NULL || fid == NULL) {
printf("Error: jcls or fid NULL while getting fd/descriptor\n");
return SSL_FAILURE;
}
fd = (*jenv)->GetIntField(jenv, fdesc, fid);
/* set socket to non-blocking so we can use select() to detect
* WANT_READ / WANT_WRITE */
#ifdef USE_WINDOWS_API
ret = ioctlsocket(fd, FIONBIO, &blocking);
if (ret == SOCKET_ERROR) {
ret = SSL_FAILURE;
}
else {
ret = SSL_SUCCESS;
}
#else
ret = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
if (ret < 0) {
ret = SSL_FAILURE;
}
else {
ret = SSL_SUCCESS;
}
#endif
if (ret == SSL_SUCCESS) {
ret = wolfSSL_set_fd(ssl, fd);
}
return (jint)ret;
}
JNIEXPORT jint JNICALL Java_com_wolfssl_WolfSSLSession_useCertificateFile
(JNIEnv* jenv, jobject jcl, jlong sslPtr, jstring file, jint format)
{
#if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM)
jint ret = 0;
const char* certFile;
WOLFSSL* ssl = (WOLFSSL*)(uintptr_t)sslPtr;
(void)jcl;
if (jenv == NULL || ssl == NULL) {
return SSL_FAILURE;
}
if (file == NULL) {
return SSL_BAD_FILE;
}
certFile = (*jenv)->GetStringUTFChars(jenv, file, 0);
ret = (jint) wolfSSL_use_certificate_file(ssl, certFile, (int)format);
(*jenv)->ReleaseStringUTFChars(jenv, file, certFile);
return ret;
#else
(void)jenv;
(void)jcl;
(void)sslPtr;
(void)file;
(void)format;
return NOT_COMPILED_IN;
#endif
}
JNIEXPORT jint JNICALL Java_com_wolfssl_WolfSSLSession_usePrivateKeyFile
(JNIEnv* jenv, jobject jcl, jlong sslPtr, jstring file, jint format)
{
#if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM)
jint ret = 0;
const char* keyFile;
WOLFSSL* ssl = (WOLFSSL*)(uintptr_t)sslPtr;
(void)jcl;
if (jenv == NULL || ssl == NULL) {
return SSL_FAILURE;
}
if (file == NULL) {
return SSL_BAD_FILE;
}
keyFile = (*jenv)->GetStringUTFChars(jenv, file, 0);
ret = (jint) wolfSSL_use_PrivateKey_file(ssl, keyFile, (int)format);
(*jenv)->ReleaseStringUTFChars(jenv, file, keyFile);
return ret;
#else
(void)jenv;
(void)jcl;
(void)sslPtr;
(void)file;
(void)format;
return NOT_COMPILED_IN;
#endif
}
JNIEXPORT jint JNICALL Java_com_wolfssl_WolfSSLSession_useCertificateChainFile
(JNIEnv* jenv, jobject jcl, jlong sslPtr, jstring file)
{
#if defined(OPENSSL_EXTRA) && !defined(NO_FILESYSTEM)
jint ret = 0;
const char* chainFile;
WOLFSSL* ssl = (WOLFSSL*)(uintptr_t)sslPtr;
(void)jcl;
if (jenv == NULL || ssl == NULL) {
return SSL_FAILURE;
}
if (file == NULL) {
return SSL_BAD_FILE;
}
chainFile = (*jenv)->GetStringUTFChars(jenv, file, 0);
ret = (jint) wolfSSL_use_certificate_chain_file(ssl, chainFile);
(*jenv)->ReleaseStringUTFChars(jenv, file, chainFile);
return ret;
#else
(void)jenv;
(void)jcl;
(void)sslPtr;
(void)file;
return NOT_COMPILED_IN;
#endif
}
JNIEXPORT void JNICALL Java_com_wolfssl_WolfSSLSession_setUsingNonblock
(JNIEnv* jenv, jobject jcl, jlong sslPtr, jint nonblock)
{
jclass excClass;
WOLFSSL* ssl = (WOLFSSL*)(uintptr_t)sslPtr;
(void)jcl;
if (jenv == NULL) {
return;
}
if (ssl == NULL) {
excClass = (*jenv)->FindClass(jenv, "com/wolfssl/WolfSSLException");
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
return;
}
(*jenv)->ThrowNew(jenv, excClass,
"Input WolfSSLSession object was null in setUsingNonblock");
}
wolfSSL_set_using_nonblock(ssl, nonblock);
}
JNIEXPORT jint JNICALL Java_com_wolfssl_WolfSSLSession_getUsingNonblock
(JNIEnv* jenv, jobject jcl, jlong sslPtr)
{
jclass excClass;
WOLFSSL* ssl = (WOLFSSL*)(uintptr_t)sslPtr;
(void)jcl;
if (jenv == NULL) {
return 0;
}
if (ssl == NULL) {
excClass = (*jenv)->FindClass(jenv, "com/wolfssl/WolfSSLException");
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
return 0;
}
(*jenv)->ThrowNew(jenv, excClass,
"Input WolfSSLSession object was null in getUsingNonblock");
}
return wolfSSL_get_using_nonblock(ssl);
}
JNIEXPORT jint JNICALL Java_com_wolfssl_WolfSSLSession_getFd
(JNIEnv* jenv, jobject jcl, jlong sslPtr)
{
jclass excClass;
WOLFSSL* ssl = (WOLFSSL*)(uintptr_t)sslPtr;
(void)jcl;
if (jenv == NULL) {
return 0;
}
if (ssl == NULL) {
excClass = (*jenv)->FindClass(jenv, "com/wolfssl/WolfSSLException");
if ((*jenv)->ExceptionOccurred(jenv)) {
(*jenv)->ExceptionDescribe(jenv);
(*jenv)->ExceptionClear(jenv);
return 0;
}
(*jenv)->ThrowNew(jenv, excClass,
"Input WolfSSLSession object was null in getFd");
return 0;
}
return wolfSSL_get_fd(ssl);
}
/* enum values used in socketSelect() and socketPoll(). Some of these
* values are also duplicated in WolfSSL.java for access from Java classes.
* If updated here, make sure to update in WolfSSL.java too. */
enum {
WOLFJNI_IO_EVENT_FAIL = -10,
WOLFJNI_IO_EVENT_TIMEOUT = -11,
WOLFJNI_IO_EVENT_RECV_READY = -12,
WOLFJNI_IO_EVENT_SEND_READY = -13,
WOLFJNI_IO_EVENT_ERROR = -14,
WOLFJNI_IO_EVENT_FD_CLOSED = -15,
WOLFJNI_IO_EVENT_POLLHUP = -16,
WOLFJNI_IO_EVENT_INVALID_TIMEOUT = -17
};
/* Windows doesn't have poll(), use select() */
#if defined(WOLFJNI_USE_IO_SELECT) || defined(USE_WINDOWS_API)
/* Perform a select() call on the underlying socket to wait for socket to be
* ready for read/write, or timeout. Note that we explicitly set the underlying
* socket descriptor to non-blocking.
*
* NOTE: the FD_ISSET macro behavior is undefined if the descriptor value is
* less than 0 or greater than or equal to FD_SETSIZE (1024 by default).
*
* On a Java Socket, a timeout of 0 is an infinite timeout. Greater than zero
* is a timeout in milliseconds. Negative timeout is invalid and not supported.
* For select(), a non-NULL timeval struct specifies maximum timeout to wait,
* a NULL timeval struct is an infinite timeout. A zero-valued timeval struct
* will return immediately (no timeout).
*
* @param sockfd socket descriptor to select()
* @param timeout_ms timeout in milliseconds. 0 indicates infinite timeout, to
* match Java timeout behavior. Negative timeout not
* supported, since not supported on Java Socket.
* @param rx set to 1 to monitor readability on socket descriptor,
* otherwise 0 to monitor writability
* @param shutdown Is this being called from shutdownSSL()? Don't select
* on interruptFds in that case, since we already know
* we are closing in that case.
*
* @return possible return values are:
* WOLFJNI_IO_EVENT_FAIL
* WOLFJNI_IO_EVENT_ERROR
* WOLFJNI_IO_EVENT_FD_CLOSED
* WOLFJNI_IO_EVENT_TIMEOUT
* WOLFJNI_IO_EVENT_RECV_READY
* WOLFJNI_IO_EVENT_SEND_READY
* WOLFJNI_IO_EVENT_INVALID_TIMEOUT
*/
static int socketSelect(SSLAppData* appData, int sockfd, int timeout_ms, int rx,
int shutdown)
{
fd_set fds, errfds;
fd_set* recvfds = NULL;
fd_set* sendfds = NULL;
int nfds = sockfd + 1;
int result = 0;
struct timeval timeout;
#ifndef USE_WINDOWS_API
char tmpBuf[1];
#endif
/* Java Socket does not support negative timeouts, sanitize */
if (timeout_ms < 0) {
return WOLFJNI_IO_EVENT_INVALID_TIMEOUT;
}
if (appData == NULL) {
return WOLFJNI_IO_EVENT_ERROR;
}
#ifndef USE_WINDOWS_API
do {
#endif
timeout.tv_sec = timeout_ms / 1000;
timeout.tv_usec = (timeout_ms % 1000) * 1000;
/* file/socket descriptors */
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
#ifndef USE_WINDOWS_API
if ((shutdown == 0) && (appData->interruptFds[0] != -1)) {
FD_SET(appData->interruptFds[0], &fds);
/* nfds should be set to the highest number descriptor plus 1 */
if (appData->interruptFds[0] > sockfd) {
nfds = appData->interruptFds[0] + 1;
}
}
#endif /* !USE_WINDOWS_API */
/* error descriptors */
FD_ZERO(&errfds);
FD_SET(sockfd, &errfds);
if (rx) {
recvfds = &fds;
} else {
sendfds = &fds;
}
incrementThreadPollCount(appData);
if (timeout_ms == 0) {
result = select(nfds, recvfds, sendfds, &errfds, NULL);
} else {
result = select(nfds, recvfds, sendfds, &errfds, &timeout);
}
decrementThreadPollCount(appData);
if (result == 0) {
return WOLFJNI_IO_EVENT_TIMEOUT;
} else if (result > 0) {
if (FD_ISSET(sockfd, &fds)) {
if (rx) {
return WOLFJNI_IO_EVENT_RECV_READY;
} else {
return WOLFJNI_IO_EVENT_SEND_READY;
}
}
else if (FD_ISSET(sockfd, &errfds)) {
return WOLFJNI_IO_EVENT_ERROR;
}
#ifndef USE_WINDOWS_API
else if ((shutdown == 0) && (appData->interruptFds[0] != -1) &&
(FD_ISSET(appData->interruptFds[0], &fds))) {
/* We got interrupted by our interrupt fd, due to a Java
* thread calling SSLSocket.close(). Try to read byte that
* was placed on our interruptFds[0] descriptor, but not
* an error if not there. Another read/write() may have
* already read it off. We just want to be interrupted,
* byte value does not matter. */
do {
read(appData->interruptFds[0], tmpBuf, 1);
} while (errno == EINTR);
return WOLFJNI_IO_EVENT_FD_CLOSED;
}
#endif /* !USE_WINDOWS_API */
}
#ifndef USE_WINDOWS_API
} while ((result == -1) && ((errno == EINTR) || (errno == EAGAIN)));
#endif
/* Return on error, unless errno EINTR or EAGAIN, try again above */
return WOLFJNI_IO_EVENT_FAIL;
}
#else /* !WOLFJNI_USE_IO_SELECT */
/* Perform poll() on underlying socket descriptor to wait for socket to be
* ready for read/write, or timeout. Note that we are explicitly setting
* the underlying descriptor to non-blocking.
*
* On a Java Socket, a timeout of 0 is an infinite timeout. Greater than zero
* is a timeout in milliseconds. Negative timeout is invalid and not supported.
* For poll(), timeout greater than 0 specifies max timeout in milliseconds,
* zero timeout will return immediately (no timeout), and -1 will block
* indefinitely.
*
* @param sockfd socket descriptor to poll()
* @param timeout_ms timeout in milliseconds. 0 indicates infinite timeout, to
* match Java timeout behavior. Negative timeout not
* supported, since not supported on Java Socket.
* @param rx set to 1 to monitor readability on socket descriptor,
* otherwise 0 to ignore readability events
* @param tx set to 1 to monitor writability on socket descriptor,
* otherwise 0 to ignore writability events
* @param shutdown Is this being called from shutdownSSL()? Don't poll
* on interruptFds in that case, since we already know
* we are closing in that case.
*
* @return possible return values are:
* WOLFJNI_IO_EVENT_FAIL
* WOLFJNI_IO_EVENT_ERROR
* WOLFJNI_IO_EVENT_TIMEOUT
* WOLFJNI_IO_EVENT_RECV_READY
* WOLFJNI_IO_EVENT_SEND_READY
* WOLFJNI_IO_EVENT_FD_CLOSED
* WOLFJNI_IO_EVENT_POLLHUP
* WOLFJNI_IO_EVENT_INVALID_TIMEOUT
*/
static int socketPoll(SSLAppData* appData, int sockfd, int timeout_ms,
int rx, int tx, int shutdown)
{
int ret;
int nfds = 2;
int timeout;
struct pollfd fds[2];
char tmpBuf[1];
if (appData == NULL) {
return WOLFJNI_IO_EVENT_ERROR;
}
/* Sanitize timeout and convert from Java to poll() expectations */
timeout = timeout_ms;
if (timeout < 0) {
return WOLFJNI_IO_EVENT_INVALID_TIMEOUT;
} else if (timeout == 0) {
timeout = -1;
}
/* fd for socket I/O */
fds[0].fd = sockfd;
fds[0].events = 0;
if (tx) {
fds[0].events |= POLLOUT | POLLPRI;
}
if (rx) {
fds[0].events |= POLLIN | POLLPRI;
}
if ((shutdown == 0) && (appData->interruptFds[0] != -1)) {
/* fd for interrupt / signaling SSLSocket.close() */
fds[1].fd = appData->interruptFds[0];
fds[1].events = POLLIN | POLLPRI;
}
else {
nfds--;
}