/
selfserv.c
2768 lines (2445 loc) · 84.9 KB
/
selfserv.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* -r flag is interepreted as follows:
* 1 -r means request, not require, on initial handshake.
* 2 -r's mean request and require, on initial handshake.
* 3 -r's mean request, not require, on second handshake.
* 4 -r's mean request and require, on second handshake.
*/
#include <stdio.h>
#include <string.h>
#include "secutil.h"
#if defined(XP_UNIX)
#include <unistd.h>
#endif
#if defined(_WINDOWS)
#include <process.h> /* for getpid() */
#endif
#include <signal.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include "nspr.h"
#include "prio.h"
#include "prerror.h"
#include "prnetdb.h"
#include "prclist.h"
#include "plgetopt.h"
#include "pk11func.h"
#include "secitem.h"
#include "nss.h"
#include "ssl.h"
#include "sslproto.h"
#include "sslexp.h"
#include "cert.h"
#include "certt.h"
#include "ocsp.h"
#ifndef PORT_Sprintf
#define PORT_Sprintf sprintf
#endif
#ifndef PORT_Strstr
#define PORT_Strstr strstr
#endif
#ifndef PORT_Malloc
#define PORT_Malloc PR_Malloc
#endif
int NumSidCacheEntries = 1024;
static int handle_connection(PRFileDesc *, PRFileDesc *);
static const char envVarName[] = { SSL_ENV_VAR_NAME };
static const char inheritableSockName[] = { "SELFSERV_LISTEN_SOCKET" };
#define MAX_VIRT_SERVER_NAME_ARRAY_INDEX 10
#define MAX_CERT_NICKNAME_ARRAY_INDEX 10
#define DEFAULT_BULK_TEST 16384
#define MAX_BULK_TEST 1048576 /* 1 MB */
static PRBool testBulk;
static PRUint32 testBulkSize = DEFAULT_BULK_TEST;
static PRInt32 testBulkTotal;
static char *testBulkBuf;
static PRDescIdentity log_layer_id = PR_INVALID_IO_LAYER;
static PRFileDesc *loggingFD;
static PRIOMethods loggingMethods;
static PRBool logStats;
static PRBool loggingLayer;
static int logPeriod = 30;
static PRInt32 loggerOps;
static PRInt32 loggerBytes;
static PRInt32 loggerBytesTCP;
static PRInt32 bulkSentChunks;
static enum ocspStaplingModeEnum {
osm_disabled, /* server doesn't support stapling */
osm_good, /* supply a signed good status */
osm_revoked, /* supply a signed revoked status */
osm_unknown, /* supply a signed unknown status */
osm_failure, /* supply a unsigned failure status, "try later" */
osm_badsig, /* supply a good status response with a bad signature */
osm_corrupted, /* supply a corrupted data block as the status */
osm_random, /* use a random response for each connection */
osm_ocsp /* retrieve ocsp status from external ocsp server,
use empty status if server is unavailable */
} ocspStaplingMode = osm_disabled;
typedef enum ocspStaplingModeEnum ocspStaplingModeType;
static char *ocspStaplingCA = NULL;
static SECItemArray *certStatus[MAX_CERT_NICKNAME_ARRAY_INDEX] = { NULL };
const int ssl3CipherSuites[] = {
-1, /* SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA* a */
-1, /* SSL_FORTEZZA_DMS_WITH_RC4_128_SHA * b */
TLS_RSA_WITH_RC4_128_MD5, /* c */
TLS_RSA_WITH_3DES_EDE_CBC_SHA, /* d */
TLS_RSA_WITH_DES_CBC_SHA, /* e */
-1, /* TLS_RSA_EXPORT_WITH_RC4_40_MD5 * f */
-1, /* TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 * g */
-1, /* SSL_FORTEZZA_DMS_WITH_NULL_SHA * h */
TLS_RSA_WITH_NULL_MD5, /* i */
-1, /* SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA * j */
-1, /* SSL_RSA_FIPS_WITH_DES_CBC_SHA * k */
-1, /* TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA * l */
-1, /* TLS_RSA_EXPORT1024_WITH_RC4_56_SHA * m */
TLS_RSA_WITH_RC4_128_SHA, /* n */
TLS_DHE_DSS_WITH_RC4_128_SHA, /* o */
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, /* p */
TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, /* q */
TLS_DHE_RSA_WITH_DES_CBC_SHA, /* r */
TLS_DHE_DSS_WITH_DES_CBC_SHA, /* s */
TLS_DHE_DSS_WITH_AES_128_CBC_SHA, /* t */
TLS_DHE_RSA_WITH_AES_128_CBC_SHA, /* u */
TLS_RSA_WITH_AES_128_CBC_SHA, /* v */
TLS_DHE_DSS_WITH_AES_256_CBC_SHA, /* w */
TLS_DHE_RSA_WITH_AES_256_CBC_SHA, /* x */
TLS_RSA_WITH_AES_256_CBC_SHA, /* y */
TLS_RSA_WITH_NULL_SHA, /* z */
0
};
/* data and structures for shutdown */
static int stopping;
static PRBool noDelay;
static int requestCert;
static int verbose;
static SECItem bigBuf;
static int configureDHE = -1; /* -1: don't configure, 0 disable, >=1 enable*/
static int configureReuseECDHE = -1; /* -1: don't configure, 0 refresh, >=1 reuse*/
static int configureWeakDHE = -1; /* -1: don't configure, 0 disable, >=1 enable*/
static PRThread *acceptorThread;
static PRLogModuleInfo *lm;
#define PRINTF \
if (verbose) \
printf
#define FPRINTF \
if (verbose) \
fprintf
#define FLUSH \
if (verbose) { \
fflush(stdout); \
fflush(stderr); \
}
#define VLOG(arg) PR_LOG(lm, PR_LOG_DEBUG, arg)
static void
PrintUsageHeader(const char *progName)
{
fprintf(stderr,
"Usage: %s -n rsa_nickname -p port [-BDENRZbjlmrsuvx] [-w password]\n"
" [-t threads] [-i pid_file] [-c ciphers] [-Y] [-d dbdir] [-g numblocks]\n"
" [-f password_file] [-L [seconds]] [-M maxProcs] [-P dbprefix]\n"
" [-V [min-version]:[max-version]] [-a sni_name]\n"
" [ T <good|revoked|unknown|badsig|corrupted|none|ocsp>] [-A ca]\n"
" [-C SSLCacheEntries] [-S dsa_nickname] -Q [-I groups]"
" [-e ec_nickname]"
"\n"
" -U [0|1] -H [0|1|2] -W [0|1]\n"
"\n",
progName);
}
static void
PrintParameterUsage()
{
fputs(
"-V [min]:[max] restricts the set of enabled SSL/TLS protocol versions.\n"
" All versions are enabled by default.\n"
" Possible values for min/max: ssl3 tls1.0 tls1.1 tls1.2\n"
" Example: \"-V ssl3:\" enables SSL 3 and newer.\n"
"-D means disable Nagle delays in TCP\n"
"-R means disable detection of rollback from TLS to SSL3\n"
"-a configure server for SNI.\n"
"-k expected name negotiated on server sockets\n"
"-b means try binding to the port and exit\n"
"-m means test the model-socket feature of SSL_ImportFD.\n"
"-r flag is interepreted as follows:\n"
" 1 -r means request, not require, cert on initial handshake.\n"
" 2 -r's mean request and require, cert on initial handshake.\n"
" 3 -r's mean request, not require, cert on second handshake.\n"
" 4 -r's mean request and require, cert on second handshake.\n"
"-s means disable SSL socket locking for performance\n"
"-u means enable Session Ticket extension for TLS.\n"
"-v means verbose output\n"
"-z means enable compression.\n"
"-L seconds means log statistics every 'seconds' seconds (default=30).\n"
"-M maxProcs tells how many processes to run in a multi-process server\n"
"-N means do NOT use the server session cache. Incompatible with -M.\n"
"-t threads -- specify the number of threads to use for connections.\n"
"-i pid_file file to write the process id of selfserve\n"
"-l means use local threads instead of global threads\n"
"-g numblocks means test throughput by sending total numblocks chunks\n"
" of size 16kb to the client, 0 means unlimited (default=0)\n"
"-j means measure TCP throughput (for use with -g option)\n"
"-C SSLCacheEntries sets the maximum number of entries in the SSL\n"
" session cache\n"
"-T <mode> enable OCSP stapling. Possible modes:\n"
" none: don't send cert status (default)\n"
" good, revoked, unknown: Include locally signed response. Requires: -A\n"
" failure: return a failure response (try later, unsigned)\n"
" badsig: use a good status but with an invalid signature\n"
" corrupted: stapled cert status is an invalid block of data\n"
" random: each connection uses a random status from this list:\n"
" good, revoked, unknown, failure, badsig, corrupted\n"
" ocsp: fetch from external OCSP server using AIA, or none\n"
"-A <ca> Nickname of a CA used to sign a stapled cert status\n"
"-U override default ECDHE ephemeral key reuse, 0: refresh, 1: reuse\n"
"-H override default DHE server support, 0: disable, 1: enable, "
" 2: require DH named groups [RFC7919]\n"
"-W override default DHE server weak parameters support, 0: disable, 1: enable\n"
"-c Restrict ciphers\n"
"-Y prints cipher values allowed for parameter -c and exits\n"
"-G enables the extended master secret extension [RFC7627]\n"
"-Q enables ALPN for HTTP/1.1 [RFC7301]\n"
"-I comma separated list of enabled groups for TLS key exchange.\n"
" The following values are valid:\n"
" P256, P384, P521, x25519, FF2048, FF3072, FF4096, FF6144, FF8192\n"
"-Z enable 0-RTT (for TLS 1.3; also use -u)\n",
stderr);
}
static void
Usage(const char *progName)
{
PrintUsageHeader(progName);
PrintParameterUsage();
}
static void
PrintCipherUsage(const char *progName)
{
PrintUsageHeader(progName);
fputs(
"-c ciphers Letter(s) chosen from the following list\n"
"c SSL3 RSA WITH RC4 128 MD5\n"
"d SSL3 RSA WITH 3DES EDE CBC SHA\n"
"e SSL3 RSA WITH DES CBC SHA\n"
"f SSL3 RSA EXPORT WITH RC4 40 MD5\n"
"g SSL3 RSA EXPORT WITH RC2 CBC 40 MD5\n"
"i SSL3 RSA WITH NULL MD5\n"
"j SSL3 RSA FIPS WITH 3DES EDE CBC SHA\n"
"k SSL3 RSA FIPS WITH DES CBC SHA\n"
"l SSL3 RSA EXPORT WITH DES CBC SHA\t(new)\n"
"m SSL3 RSA EXPORT WITH RC4 56 SHA\t(new)\n"
"n SSL3 RSA WITH RC4 128 SHA\n"
"o TLS_DHE_DSS_WITH_RC4_128_SHA\n"
"p TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA\n"
"q TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA\n"
"r TLS_DHE_RSA_WITH_DES_CBC_SHA\n"
"s TLS_DHE_DSS_WITH_DES_CBC_SHA\n"
"t TLS_DHE_DSS_WITH_AES_128_CBC_SHA\n"
"u TLS_DHE_RSA_WITH_AES_128_CBC_SHA\n"
"v SSL3 RSA WITH AES 128 CBC SHA\n"
"w TLS_DHE_DSS_WITH_AES_256_CBC_SHA\n"
"x TLS_DHE_RSA_WITH_AES_256_CBC_SHA\n"
"y SSL3 RSA WITH AES 256 CBC SHA\n"
"z SSL3 RSA WITH NULL SHA\n"
"\n"
":WXYZ Use cipher with hex code { 0xWX , 0xYZ } in TLS\n",
stderr);
}
static const char *
errWarn(char *funcString)
{
PRErrorCode perr = PR_GetError();
const char *errString = SECU_Strerror(perr);
fprintf(stderr, "selfserv: %s returned error %d:\n%s\n",
funcString, perr, errString);
return errString;
}
static void
errExit(char *funcString)
{
errWarn(funcString);
exit(3);
}
/**************************************************************************
**
** Routines for disabling SSL ciphers.
**
**************************************************************************/
/* disable all the SSL cipher suites */
void
disableAllSSLCiphers(void)
{
const PRUint16 *cipherSuites = SSL_ImplementedCiphers;
int i = SSL_NumImplementedCiphers;
SECStatus rv;
while (--i >= 0) {
PRUint16 suite = cipherSuites[i];
rv = SSL_CipherPrefSetDefault(suite, PR_FALSE);
if (rv != SECSuccess) {
printf("SSL_CipherPrefSetDefault rejected suite 0x%04x (i = %d)\n",
suite, i);
errWarn("SSL_CipherPrefSetDefault");
}
}
}
static SECStatus
mySSLAuthCertificate(void *arg, PRFileDesc *fd, PRBool checkSig,
PRBool isServer)
{
SECStatus rv;
CERTCertificate *peerCert;
peerCert = SSL_PeerCertificate(fd);
if (peerCert) {
PRINTF("selfserv: Subject: %s\nselfserv: Issuer : %s\n",
peerCert->subjectName, peerCert->issuerName);
CERT_DestroyCertificate(peerCert);
}
rv = SSL_AuthCertificate(arg, fd, checkSig, isServer);
if (rv == SECSuccess) {
PRINTF("selfserv: -- SSL3: Certificate Validated.\n");
} else {
int err = PR_GetError();
FPRINTF(stderr, "selfserv: -- SSL3: Certificate Invalid, err %d.\n%s\n",
err, SECU_Strerror(err));
}
FLUSH;
return rv;
}
void
printSSLStatistics()
{
SSL3Statistics *ssl3stats = SSL_GetStatistics();
printf(
"selfserv: %ld cache hits; %ld cache misses, %ld cache not reusable\n"
" %ld stateless resumes, %ld ticket parse failures\n",
ssl3stats->hch_sid_cache_hits, ssl3stats->hch_sid_cache_misses,
ssl3stats->hch_sid_cache_not_ok, ssl3stats->hch_sid_stateless_resumes,
ssl3stats->hch_sid_ticket_parse_failures);
}
void
printSecurityInfo(PRFileDesc *fd)
{
CERTCertificate *cert = NULL;
SECStatus result;
SSLChannelInfo channel;
SSLCipherSuiteInfo suite;
if (verbose)
printSSLStatistics();
result = SSL_GetChannelInfo(fd, &channel, sizeof channel);
if (result == SECSuccess &&
channel.length == sizeof channel &&
channel.cipherSuite) {
result = SSL_GetCipherSuiteInfo(channel.cipherSuite,
&suite, sizeof suite);
if (result == SECSuccess) {
FPRINTF(stderr,
"selfserv: SSL version %d.%d using %d-bit %s with %d-bit %s MAC\n",
channel.protocolVersion >> 8, channel.protocolVersion & 0xff,
suite.effectiveKeyBits, suite.symCipherName,
suite.macBits, suite.macAlgorithmName);
FPRINTF(stderr,
"selfserv: Server Auth: %d-bit %s, Key Exchange: %d-bit %s\n"
" Compression: %s, Extended Master Secret: %s\n",
channel.authKeyBits, suite.authAlgorithmName,
channel.keaKeyBits, suite.keaTypeName,
channel.compressionMethodName,
channel.extendedMasterSecretUsed ? "Yes" : "No");
}
}
if (verbose) {
SECItem *hostInfo = SSL_GetNegotiatedHostInfo(fd);
if (hostInfo) {
char namePref[] = "selfserv: Negotiated server name: ";
fprintf(stderr, "%s", namePref);
fwrite(hostInfo->data, hostInfo->len, 1, stderr);
SECITEM_FreeItem(hostInfo, PR_TRUE);
hostInfo = NULL;
fprintf(stderr, "\n");
}
}
if (requestCert)
cert = SSL_PeerCertificate(fd);
else
cert = SSL_LocalCertificate(fd);
if (cert) {
char *ip = CERT_NameToAscii(&cert->issuer);
char *sp = CERT_NameToAscii(&cert->subject);
if (sp) {
FPRINTF(stderr, "selfserv: subject DN: %s\n", sp);
PORT_Free(sp);
}
if (ip) {
FPRINTF(stderr, "selfserv: issuer DN: %s\n", ip);
PORT_Free(ip);
}
CERT_DestroyCertificate(cert);
cert = NULL;
}
FLUSH;
}
static int MakeCertOK;
static SECStatus
myBadCertHandler(void *arg, PRFileDesc *fd)
{
int err = PR_GetError();
if (!MakeCertOK)
fprintf(stderr,
"selfserv: -- SSL: Client Certificate Invalid, err %d.\n%s\n",
err, SECU_Strerror(err));
return (MakeCertOK ? SECSuccess : SECFailure);
}
/* Simple SNI socket config function that does not use SSL_ReconfigFD.
* Only uses one server name but verifies that the names match. */
PRInt32
mySSLSNISocketConfig(PRFileDesc *fd, const SECItem *sniNameArr,
PRUint32 sniNameArrSize, void *arg)
{
PRInt32 i = 0;
const SECItem *current = sniNameArr;
const char **nameArr = (const char **)arg;
secuPWData *pwdata;
CERTCertificate *cert = NULL;
SECKEYPrivateKey *privKey = NULL;
PORT_Assert(fd && sniNameArr);
if (!fd || !sniNameArr) {
return SSL_SNI_SEND_ALERT;
}
pwdata = SSL_RevealPinArg(fd);
for (; current && (PRUint32)i < sniNameArrSize; i++) {
unsigned int j = 0;
for (; j < MAX_VIRT_SERVER_NAME_ARRAY_INDEX && nameArr[j]; j++) {
if (!PORT_Strncmp(nameArr[j],
(const char *)current[i].data,
current[i].len) &&
PORT_Strlen(nameArr[j]) == current[i].len) {
const char *nickName = nameArr[j];
if (j == 0) {
/* default cert */
return 0;
}
/* if pwdata is NULL, then we would not get the key and
* return an error status. */
cert = PK11_FindCertFromNickname(nickName, &pwdata);
if (cert == NULL) {
goto loser; /* Send alert */
}
privKey = PK11_FindKeyByAnyCert(cert, &pwdata);
if (privKey == NULL) {
goto loser; /* Send alert */
}
if (SSL_ConfigServerCert(fd, cert, privKey, NULL, 0) != SECSuccess) {
goto loser; /* Send alert */
}
SECKEY_DestroyPrivateKey(privKey);
CERT_DestroyCertificate(cert);
return i;
}
}
}
loser:
if (privKey) {
SECKEY_DestroyPrivateKey(privKey);
}
if (cert) {
CERT_DestroyCertificate(cert);
}
return SSL_SNI_SEND_ALERT;
}
/**************************************************************************
** Begin thread management routines and data.
**************************************************************************/
#define MIN_THREADS 3
#define DEFAULT_THREADS 8
#define MAX_THREADS 4096
#define MAX_PROCS 25
static int maxThreads = DEFAULT_THREADS;
typedef struct jobStr {
PRCList link;
PRFileDesc *tcp_sock;
PRFileDesc *model_sock;
} JOB;
static PZLock *qLock; /* this lock protects all data immediately below */
static PRLock *lastLoadedCrlLock; /* this lock protects lastLoadedCrl variable */
static PZCondVar *jobQNotEmptyCv;
static PZCondVar *freeListNotEmptyCv;
static PZCondVar *threadCountChangeCv;
static int threadCount;
static PRCList jobQ;
static PRCList freeJobs;
static JOB *jobTable;
SECStatus
setupJobs(int maxJobs)
{
int i;
jobTable = (JOB *)PR_Calloc(maxJobs, sizeof(JOB));
if (!jobTable)
return SECFailure;
PR_INIT_CLIST(&jobQ);
PR_INIT_CLIST(&freeJobs);
for (i = 0; i < maxJobs; ++i) {
JOB *pJob = jobTable + i;
PR_APPEND_LINK(&pJob->link, &freeJobs);
}
return SECSuccess;
}
typedef int startFn(PRFileDesc *a, PRFileDesc *b);
typedef enum { rs_idle = 0,
rs_running = 1,
rs_zombie = 2 } runState;
typedef struct perThreadStr {
PRFileDesc *a;
PRFileDesc *b;
int rv;
startFn *startFunc;
PRThread *prThread;
runState state;
} perThread;
static perThread *threads;
void
thread_wrapper(void *arg)
{
perThread *slot = (perThread *)arg;
slot->rv = (*slot->startFunc)(slot->a, slot->b);
/* notify the thread exit handler. */
PZ_Lock(qLock);
slot->state = rs_zombie;
--threadCount;
PZ_NotifyAllCondVar(threadCountChangeCv);
PZ_Unlock(qLock);
}
int
jobLoop(PRFileDesc *a, PRFileDesc *b)
{
PRCList *myLink = 0;
JOB *myJob;
PZ_Lock(qLock);
do {
myLink = 0;
while (PR_CLIST_IS_EMPTY(&jobQ) && !stopping) {
PZ_WaitCondVar(jobQNotEmptyCv, PR_INTERVAL_NO_TIMEOUT);
}
if (!PR_CLIST_IS_EMPTY(&jobQ)) {
myLink = PR_LIST_HEAD(&jobQ);
PR_REMOVE_AND_INIT_LINK(myLink);
}
PZ_Unlock(qLock);
myJob = (JOB *)myLink;
/* myJob will be null when stopping is true and jobQ is empty */
if (!myJob)
break;
handle_connection(myJob->tcp_sock, myJob->model_sock);
PZ_Lock(qLock);
PR_APPEND_LINK(myLink, &freeJobs);
PZ_NotifyCondVar(freeListNotEmptyCv);
} while (PR_TRUE);
return 0;
}
SECStatus
launch_threads(
startFn *startFunc,
PRFileDesc *a,
PRFileDesc *b,
PRBool local)
{
int i;
SECStatus rv = SECSuccess;
/* create the thread management serialization structs */
qLock = PZ_NewLock(nssILockSelfServ);
jobQNotEmptyCv = PZ_NewCondVar(qLock);
freeListNotEmptyCv = PZ_NewCondVar(qLock);
threadCountChangeCv = PZ_NewCondVar(qLock);
/* create monitor for crl reload procedure */
lastLoadedCrlLock = PR_NewLock();
/* allocate the array of thread slots */
threads = PR_Calloc(maxThreads, sizeof(perThread));
if (NULL == threads) {
fprintf(stderr, "Oh Drat! Can't allocate the perThread array\n");
return SECFailure;
}
/* 5 is a little extra, intended to keep the jobQ from underflowing.
** That is, from going empty while not stopping and clients are still
** trying to contact us.
*/
rv = setupJobs(maxThreads + 5);
if (rv != SECSuccess)
return rv;
PZ_Lock(qLock);
for (i = 0; i < maxThreads; ++i) {
perThread *slot = threads + i;
slot->state = rs_running;
slot->a = a;
slot->b = b;
slot->startFunc = startFunc;
slot->prThread = PR_CreateThread(PR_USER_THREAD,
thread_wrapper, slot, PR_PRIORITY_NORMAL,
(PR_TRUE ==
local)
? PR_LOCAL_THREAD
: PR_GLOBAL_THREAD,
PR_JOINABLE_THREAD, 0);
if (slot->prThread == NULL) {
printf("selfserv: Failed to launch thread!\n");
slot->state = rs_idle;
rv = SECFailure;
break;
}
++threadCount;
}
PZ_Unlock(qLock);
return rv;
}
#define DESTROY_CONDVAR(name) \
if (name) { \
PZ_DestroyCondVar(name); \
name = NULL; \
}
#define DESTROY_LOCK(name) \
if (name) { \
PZ_DestroyLock(name); \
name = NULL; \
}
void
terminateWorkerThreads(void)
{
int i;
VLOG(("selfserv: server_thread: waiting on stopping"));
PZ_Lock(qLock);
PZ_NotifyAllCondVar(jobQNotEmptyCv);
PZ_Unlock(qLock);
/* Wait for worker threads to terminate. */
for (i = 0; i < maxThreads; ++i) {
perThread *slot = threads + i;
if (slot->prThread) {
PR_JoinThread(slot->prThread);
}
}
/* The worker threads empty the jobQ before they terminate. */
PZ_Lock(qLock);
PORT_Assert(threadCount == 0);
PORT_Assert(PR_CLIST_IS_EMPTY(&jobQ));
PZ_Unlock(qLock);
DESTROY_CONDVAR(jobQNotEmptyCv);
DESTROY_CONDVAR(freeListNotEmptyCv);
DESTROY_CONDVAR(threadCountChangeCv);
PR_DestroyLock(lastLoadedCrlLock);
DESTROY_LOCK(qLock);
PR_Free(jobTable);
PR_Free(threads);
}
static void
logger(void *arg)
{
PRFloat64 seconds;
PRFloat64 opsPerSec;
PRIntervalTime period;
PRIntervalTime previousTime;
PRIntervalTime latestTime;
PRInt32 previousOps;
PRInt32 ops;
PRIntervalTime logPeriodTicks = PR_TicksPerSecond();
PRFloat64 secondsPerTick = 1.0 / (PRFloat64)logPeriodTicks;
int iterations = 0;
int secondsElapsed = 0;
static PRInt64 totalPeriodBytes = 0;
static PRInt64 totalPeriodBytesTCP = 0;
previousOps = loggerOps;
previousTime = PR_IntervalNow();
for (;;) {
/* OK, implementing a new sleep algorithm here... always sleep
* for 1 second but print out info at the user-specified interval.
* This way, we don't overflow all of our PR_Atomic* functions and
* we don't have to use locks.
*/
PR_Sleep(logPeriodTicks);
secondsElapsed++;
totalPeriodBytes += PR_ATOMIC_SET(&loggerBytes, 0);
totalPeriodBytesTCP += PR_ATOMIC_SET(&loggerBytesTCP, 0);
if (secondsElapsed != logPeriod) {
continue;
}
/* when we reach the user-specified logging interval, print out all
* data
*/
secondsElapsed = 0;
latestTime = PR_IntervalNow();
ops = loggerOps;
period = latestTime - previousTime;
seconds = (PRFloat64)period * secondsPerTick;
opsPerSec = (ops - previousOps) / seconds;
if (testBulk) {
if (iterations == 0) {
if (loggingLayer == PR_TRUE) {
printf("Conn.--------App Data--------TCP Data\n");
} else {
printf("Conn.--------App Data\n");
}
}
if (loggingLayer == PR_TRUE) {
printf("%4.d %5.3f MB/s %5.3f MB/s\n", ops,
totalPeriodBytes / (seconds * 1048576.0),
totalPeriodBytesTCP / (seconds * 1048576.0));
} else {
printf("%4.d %5.3f MB/s\n", ops,
totalPeriodBytes / (seconds * 1048576.0));
}
totalPeriodBytes = 0;
totalPeriodBytesTCP = 0;
/* Print the "legend" every 20 iterations */
iterations = (iterations + 1) % 20;
} else {
printf("%.2f ops/second, %d threads\n", opsPerSec, threadCount);
}
fflush(stdout);
previousOps = ops;
previousTime = latestTime;
if (stopping) {
break;
}
}
}
/**************************************************************************
** End thread management routines.
**************************************************************************/
PRBool useModelSocket = PR_FALSE;
static SSLVersionRange enabledVersions;
PRBool disableRollBack = PR_FALSE;
PRBool NoReuse = PR_FALSE;
PRBool hasSidCache = PR_FALSE;
PRBool disableLocking = PR_FALSE;
PRBool enableSessionTickets = PR_FALSE;
PRBool enableCompression = PR_FALSE;
PRBool failedToNegotiateName = PR_FALSE;
PRBool enableExtendedMasterSecret = PR_FALSE;
PRBool zeroRTT = PR_FALSE;
PRBool enableALPN = PR_FALSE;
SSLNamedGroup *enabledGroups = NULL;
unsigned int enabledGroupsCount = 0;
static char *virtServerNameArray[MAX_VIRT_SERVER_NAME_ARRAY_INDEX];
static int virtServerNameIndex = 1;
static char *certNicknameArray[MAX_CERT_NICKNAME_ARRAY_INDEX];
static int certNicknameIndex = 0;
static const char stopCmd[] = { "GET /stop " };
static const char getCmd[] = { "GET " };
static const char EOFmsg[] = { "EOF\r\n\r\n\r\n" };
static const char outHeader[] = {
"HTTP/1.0 200 OK\r\n"
"Server: Generic Web Server\r\n"
"Date: Tue, 26 Aug 1997 22:10:05 GMT\r\n"
"Content-type: text/plain\r\n"
"\r\n"
};
static const char crlCacheErr[] = { "CRL ReCache Error: " };
PRUint16 cipherlist[100];
int nciphers;
void
savecipher(int c)
{
if (nciphers < sizeof cipherlist / sizeof(cipherlist[0]))
cipherlist[nciphers++] = (PRUint16)c;
}
#ifdef FULL_DUPLEX_CAPABLE
struct lockedVarsStr {
PZLock *lock;
int count;
int waiters;
PZCondVar *condVar;
};
typedef struct lockedVarsStr lockedVars;
void
lockedVars_Init(lockedVars *lv)
{
lv->count = 0;
lv->waiters = 0;
lv->lock = PZ_NewLock(nssILockSelfServ);
lv->condVar = PZ_NewCondVar(lv->lock);
}
void
lockedVars_Destroy(lockedVars *lv)
{
PZ_DestroyCondVar(lv->condVar);
lv->condVar = NULL;
PZ_DestroyLock(lv->lock);
lv->lock = NULL;
}
void
lockedVars_WaitForDone(lockedVars *lv)
{
PZ_Lock(lv->lock);
while (lv->count > 0) {
PZ_WaitCondVar(lv->condVar, PR_INTERVAL_NO_TIMEOUT);
}
PZ_Unlock(lv->lock);
}
int /* returns count */
lockedVars_AddToCount(lockedVars *lv, int addend)
{
int rv;
PZ_Lock(lv->lock);
rv = lv->count += addend;
if (rv <= 0) {
PZ_NotifyCondVar(lv->condVar);
}
PZ_Unlock(lv->lock);
return rv;
}
int
do_writes(
PRFileDesc *ssl_sock,
PRFileDesc *model_sock)
{
int sent = 0;
int count = 0;
lockedVars *lv = (lockedVars *)model_sock;
VLOG(("selfserv: do_writes: starting"));
while (sent < bigBuf.len) {
count = PR_Write(ssl_sock, bigBuf.data + sent, bigBuf.len - sent);
if (count < 0) {
errWarn("PR_Write bigBuf");
break;
}
FPRINTF(stderr, "selfserv: PR_Write wrote %d bytes from bigBuf\n", count);
sent += count;
}
if (count >= 0) { /* last write didn't fail. */
PR_Shutdown(ssl_sock, PR_SHUTDOWN_SEND);
}
/* notify the reader that we're done. */
lockedVars_AddToCount(lv, -1);
FLUSH;
VLOG(("selfserv: do_writes: exiting"));
return (sent < bigBuf.len) ? SECFailure : SECSuccess;
}
static int
handle_fdx_connection(
PRFileDesc *tcp_sock,
PRFileDesc *model_sock)
{
PRFileDesc *ssl_sock = NULL;
SECStatus result;
int firstTime = 1;
lockedVars lv;
PRSocketOptionData opt;
char buf[10240];
VLOG(("selfserv: handle_fdx_connection: starting"));
opt.option = PR_SockOpt_Nonblocking;
opt.value.non_blocking = PR_FALSE;
PR_SetSocketOption(tcp_sock, &opt);
if (useModelSocket && model_sock) {
SECStatus rv;
ssl_sock = SSL_ImportFD(model_sock, tcp_sock);
if (!ssl_sock) {
errWarn("SSL_ImportFD with model");
goto cleanup;
}
rv = SSL_ResetHandshake(ssl_sock, /* asServer */ 1);
if (rv != SECSuccess) {
errWarn("SSL_ResetHandshake");
goto cleanup;
}
} else {
ssl_sock = tcp_sock;
}
lockedVars_Init(&lv);
lockedVars_AddToCount(&lv, 1);
/* Attempt to launch the writer thread. */
result = launch_thread(do_writes, ssl_sock, (PRFileDesc *)&lv);
if (result == SECSuccess)
do {
/* do reads here. */
int count;
count = PR_Read(ssl_sock, buf, sizeof buf);
if (count < 0) {
errWarn("FDX PR_Read");
break;
}
FPRINTF(stderr, "selfserv: FDX PR_Read read %d bytes.\n", count);
if (firstTime) {
firstTime = 0;
printSecurityInfo(ssl_sock);
}
} while (lockedVars_AddToCount(&lv, 0) > 0);
/* Wait for writer to finish */
lockedVars_WaitForDone(&lv);
lockedVars_Destroy(&lv);
FLUSH;
cleanup:
if (ssl_sock) {
PR_Close(ssl_sock);
} else if (tcp_sock) {
PR_Close(tcp_sock);
}
VLOG(("selfserv: handle_fdx_connection: exiting"));
return SECSuccess;
}
#endif
static SECItem *lastLoadedCrl = NULL;
static SECStatus
reload_crl(PRFileDesc *crlFile)
{
SECItem *crlDer;
CERTCertDBHandle *certHandle = CERT_GetDefaultCertDB();
SECStatus rv;