summaryrefslogtreecommitdiff
path: root/cpp/src/IceSSL/OpenSSLPluginI.cpp
blob: dab74335b72ab0865e304852546f57ebf60fe6c2 (plain)
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
// **********************************************************************
//
// Copyright (c) 2003-2005 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <Ice/LoggerUtil.h>
#include <Ice/Properties.h>
#include <Ice/ProtocolPluginFacade.h>
#include <Ice/Communicator.h>
#include <Ice/LocalException.h>

#include <IceSSL/OpenSSLPluginI.h>
#include <IceSSL/TraceLevels.h>
#include <IceSSL/Exception.h>
#include <IceSSL/ConfigParser.h>
#include <IceSSL/OpenSSLJanitors.h>
#include <IceSSL/OpenSSLUtils.h>
#include <IceSSL/SslTransceiver.h>
#include <IceSSL/DefaultCertificateVerifier.h>
#include <IceSSL/SingleCertificateVerifier.h>
#include <IceSSL/SslEndpoint.h>
#include <IceSSL/RSAPrivateKey.h>
#include <IceSSL/DHParams.h>

#include <openssl/rand.h>
#include <openssl/err.h>

#if OPENSSL_VERSION_NUMBER >= 0x0090700fL
#include <openssl/engine.h>
#endif

#include <sstream>

#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#if OPENSSL_VERSION_NUMBER < 0x0090700fL || defined(__FreeBSD__)
#   if !defined(THREADS)
#      error "Thread support not enabled"
#   endif
#else
#   if !defined(OPENSSL_THREADS)
#      error "Thread support not enabled"
#   endif
#endif

using namespace std;
using namespace Ice;
using namespace IceSSL;

void IceInternal::incRef(OpenSSLPluginI* p) { p->__incRef(); }
void IceInternal::decRef(OpenSSLPluginI* p) { p->__decRef(); }

static IceUtil::StaticMutex staticMutex = ICE_STATIC_MUTEX_INITIALIZER;
static int instanceCount = 0;

//
// Plugin factory function
//
extern "C"
{

ICE_SSL_API Ice::Plugin*
create(const CommunicatorPtr& communicator, const string& name, const StringSeq& args)
{
    IceInternal::ProtocolPluginFacadePtr facade = IceInternal::getProtocolPluginFacade(communicator);

    OpenSSLPluginI* plugin = new OpenSSLPluginI(facade);
    try
    {
        plugin->configure();

        //
        // Install the SSL endpoint factory
        //
        IceInternal::EndpointFactoryPtr sslEndpointFactory = new SslEndpointFactory(plugin);
        facade->addEndpointFactory(sslEndpointFactory);
    }
    catch(const Exception& ex)
    {
        Ice::PluginPtr ptr = plugin; // Reclaim the plug-in instance

        Error out(communicator->getLogger());
        out << "exception in IceSSL plug-in:\n" << ex;

        // Can't throw from an extern "C" function
        return 0;
    }
    catch(...)
    {
        Ice::PluginPtr ptr = plugin; // Reclaim the plug-in instance

        Error out(communicator->getLogger());
        out << "unknown exception in IceSSL plug-in";

        // Can't throw from an extern "C" function
        return 0;
    }

    return plugin;
}

}


//
// Thread safety implementation for OpenSSL
//
namespace IceSSL
{

class SslLockKeeper
{
public:

    SslLockKeeper();
    ~SslLockKeeper();

    IceUtil::Mutex sslLocks[CRYPTO_NUM_LOCKS];

};

SslLockKeeper lockKeeper;

}

extern "C"
{
    
static void lockingCallback(int mode, int type, const char *file, int line)
{
    if(mode & CRYPTO_LOCK)
    {
        lockKeeper.sslLocks[type].lock();
    }
    else
    {
        lockKeeper.sslLocks[type].unlock();
    }
}

static unsigned long
idFunction()
{
#if defined(_WIN32)
    return static_cast<unsigned long>(GetCurrentThreadId());
#elif defined(__FreeBSD__) || defined(__APPLE__)
    //
    // On FreeBSD, pthread_t is a pointer to a per-thread structure
    // 
    return reinterpret_cast<unsigned long>(pthread_self());
#elif (defined(__linux) || defined(__sun) || defined(__hpux)) || defined(_AIX)
    //
    // On Linux, Solaris, HP-UX and AIX, pthread_t is an integer
    //
    return static_cast<unsigned long>(pthread_self());
#else
#   error "Unknown platform"
#endif
}
}

IceSSL::SslLockKeeper::SslLockKeeper()
{
    CRYPTO_set_id_callback(idFunction);
    CRYPTO_set_locking_callback(lockingCallback);
}

IceSSL::SslLockKeeper::~SslLockKeeper()
{
    CRYPTO_set_locking_callback(0);
    CRYPTO_set_id_callback(0);
}

//
// Public Methods
//
//
IceSSL::OpenSSLPluginI::OpenSSLPluginI(const IceInternal::ProtocolPluginFacadePtr& protocolPluginFacade) :
    _protocolPluginFacade(protocolPluginFacade),
    _traceLevels(new TraceLevels(_protocolPluginFacade)),
    _logger(_protocolPluginFacade->getCommunicator()->getLogger()),
    _properties(_protocolPluginFacade->getCommunicator()->getProperties()),
    _memDebug(_properties->getPropertyAsIntWithDefault("IceSSL.MemoryDebug", 0)),
    _serverContext(new TraceLevels(protocolPluginFacade), protocolPluginFacade->getCommunicator()),
    _clientContext(new TraceLevels(protocolPluginFacade), protocolPluginFacade->getCommunicator()),
    _randSeeded(0)
{
    //
    // It is possible for multiple instances of OpenSSLPluginI to be created
    // (one for each communicator). We use a mutex-protected counter to know
    // when to initialize and clean up OpenSSL.
    //
    IceUtil::StaticMutex::Lock sync(staticMutex);
    if(instanceCount == 0)
    {
	if(_memDebug != 0)
	{
	    CRYPTO_malloc_debug_init();
	    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
	    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
	}
	else
	{
	    CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
	}

	SSL_library_init();

	SSL_load_error_strings();

	OpenSSL_add_ssl_algorithms();
    }
    ++instanceCount;
}

IceSSL::OpenSSLPluginI::~OpenSSLPluginI()
{
    _serverContext.cleanUp();
    _clientContext.cleanUp();

    unregisterThreads();

    IceUtil::StaticMutex::Lock sync(staticMutex);
    if(--instanceCount == 0)
    {
#if OPENSSL_VERSION_NUMBER >= 0x0090700fL
	ENGINE_cleanup();
	CRYPTO_cleanup_all_ex_data();
#endif

	// TODO: Introduces a 72byte memory leak, if we kidnap the code from OpenSSL 0.9.7a for
	//       ENGINE_cleanup(), we can fix that.

	ERR_free_strings();
	ERR_remove_state(0);

	EVP_cleanup();

	if(_memDebug != 0)
	{
	    CRYPTO_mem_leaks_fp(stderr);
	}
    }
}

SslTransceiverPtr
IceSSL::OpenSSLPluginI::createTransceiver(ContextType connectionType, int socket, int timeout)
{
    IceUtil::RecMutex::Lock sync(_configMutex);

    if(connectionType == ClientServer)
    {
        UnsupportedContextException unsupportedException(__FILE__, __LINE__);

        unsupportedException.message = "unable to create client/server connections";

        throw unsupportedException;
    }

    // Configure the context if need be.
    if(!isConfigured(connectionType))
    {
        configure(connectionType);
    }

    SslTransceiverPtr transceiver;

    if(connectionType == Client)
    {
        transceiver = _clientContext.createTransceiver(socket, this, timeout);
    }
    else if(connectionType == Server)
    {
        transceiver = _serverContext.createTransceiver(socket, this, timeout);
    }

    return transceiver;
}

bool
IceSSL::OpenSSLPluginI::isConfigured(ContextType contextType)
{
    IceUtil::RecMutex::Lock sync(_configMutex);

    bool retCode = false;

    switch(contextType)
    {
        case Client :
        {
            retCode = _clientContext.isConfigured();
            break;
        }

        case Server :
        {
            retCode = _serverContext.isConfigured();
            break;
        }

        case ClientServer :
        {
            retCode = _clientContext.isConfigured() && _serverContext.isConfigured();
            break;
        }
    }

    return retCode;
}

void
IceSSL::OpenSSLPluginI::configure()
{
    string clientConfigFile = _properties->getProperty("IceSSL.Client.Config");
    string serverConfigFile = _properties->getProperty("IceSSL.Server.Config");
    
    bool clientConfig = (clientConfigFile.empty() ? false : true);
    bool serverConfig = (serverConfigFile.empty() ? false : true);

    if(clientConfig && serverConfig)
    {
        configure(ClientServer);
    }
    else if(clientConfig)
    {
        configure(Client);
    }
    else if(serverConfig)
    {
        configure(Server);
    }
}

void
IceSSL::OpenSSLPluginI::configure(ContextType contextType)
{
    IceUtil::RecMutex::Lock sync(_configMutex);

    switch(contextType)
    {
        case Client :
        {
            string configFile = _properties->getProperty("IceSSL.Client.Config");
            string certPath   = _properties->getProperty("IceSSL.Client.CertPath");
            loadConfig(Client, configFile, certPath);
            break;
        }

        case Server :
        {
            string configFile = _properties->getProperty("IceSSL.Server.Config");
            string certPath   = _properties->getProperty("IceSSL.Server.CertPath");
            loadConfig(Server, configFile, certPath);
            break;
        }

        case ClientServer :
        {
            string clientConfigFile = _properties->getProperty("IceSSL.Client.Config");
            string clientCertPath   = _properties->getProperty("IceSSL.Client.CertPath");
            string serverConfigFile = _properties->getProperty("IceSSL.Server.Config");
            string serverCertPath   = _properties->getProperty("IceSSL.Server.CertPath");

            // Short cut, so that we only have to load the file once.
            if((clientConfigFile == serverConfigFile) && (clientCertPath == serverCertPath))
            {
                loadConfig(ClientServer, clientConfigFile, clientCertPath);
            }
            else
            {
                loadConfig(Client, clientConfigFile, clientCertPath);
                loadConfig(Server, serverConfigFile, serverCertPath);
            }
            break;
        }
    }
}

void
IceSSL::OpenSSLPluginI::loadConfig(ContextType contextType,
				   const string& configFile,
				   const string& certPath)
{
    if(configFile.empty())
    {
        ConfigurationLoadingException configEx(__FILE__, __LINE__);

        string contextString;

        switch(contextType)
        {
            case Client :
            {
                contextString = "client";
                break;
            }

            case Server :
            {
                contextString = "server";
                break;
            }

            case ClientServer :
            {
                contextString = "client/server";
                break;
            }
        }

        configEx.message = "no ssl configuration file specified for ";
        configEx.message += contextString;

        throw configEx;
    }

    ConfigParser sslConfig(configFile, certPath, _traceLevels, _logger);

    // Actually parse the file now.
    sslConfig.process();

    if((contextType == Client || contextType == ClientServer))
    {
        GeneralConfig clientGeneral;
        CertificateAuthority clientCertAuth;
        BaseCertificates clientBaseCerts;

        // Walk the parse tree, get the Client configuration.
        if(sslConfig.loadClientConfig(clientGeneral, clientCertAuth, clientBaseCerts))
        {
            initRandSystem(clientGeneral.getRandomBytesFiles());

            _clientContext.configure(clientGeneral, clientCertAuth, clientBaseCerts);
        }
    }

    if((contextType == Server || contextType == ClientServer))
    {
        GeneralConfig serverGeneral;
        CertificateAuthority serverCertAuth;
        BaseCertificates serverBaseCerts;
        TempCertificates serverTempCerts;

        // Walk the parse tree, get the Server configuration.
        if(sslConfig.loadServerConfig(serverGeneral, serverCertAuth, serverBaseCerts, serverTempCerts))
        {
            initRandSystem(serverGeneral.getRandomBytesFiles());

            loadTempCerts(serverTempCerts);

            _serverContext.configure(serverGeneral, serverCertAuth, serverBaseCerts);

            if(_traceLevels->security >= SECURITY_PROTOCOL)
            {
                Trace out(_logger, _traceLevels->securityCat);

                out << "temporary certificates (server)\n";
                out << "-------------------------------\n";
                out << serverTempCerts << "\n";
            }
        }
    }
}

RSA*
IceSSL::OpenSSLPluginI::getRSAKey(int isExport, int keyLength)
{
    IceUtil::Mutex::Lock sync(_tempRSAKeysMutex);

    RSA* rsa_tmp = 0;

    RSAMap::iterator retVal = _tempRSAKeys.find(keyLength);

    // Does the key already exist?
    if(retVal != _tempRSAKeys.end())
    {
        // Yes!  Use it.
        rsa_tmp = (*retVal).second->get();

        assert(rsa_tmp != 0);
    }
    else
    {
        const RSACertMap::iterator& it = _tempRSAFileMap.find(keyLength);

        // First we try to load a private and public key from specified files
        if(it != _tempRSAFileMap.end())
        {
            CertificateDesc& rsaKeyCert = (*it).second;

            const string& privKeyFile = rsaKeyCert.getPrivate().getFileName();
            const string& pubCertFile = rsaKeyCert.getPublic().getFileName();

            RSA* rsaCert = 0;
            RSA* rsaKey = 0;
            BIO* bio = 0;

            if((bio = BIO_new_file(pubCertFile.c_str(), "r")) != 0)
            {
                BIOJanitor bioJanitor(bio);

                rsaCert = PEM_read_bio_RSAPublicKey(bio, 0, 0, 0);
            }

            if(rsaCert != 0)
            {
                if((bio = BIO_new_file(privKeyFile.c_str(), "r")) != 0)
                {
                    BIOJanitor bioJanitor(bio);

                    rsaKey = PEM_read_bio_RSAPrivateKey(bio, &rsaCert, 0, 0);
                }
            }

            // Now, if all was well, the Certificate and Key should both be loaded into
            // rsaCert. We check to ensure that both are not 0, because if either are,
            // one of the reads failed.

            if((rsaCert != 0) && (rsaKey != 0))
            {
                rsa_tmp = rsaCert;
            }
            else
            {
                if(rsaCert != 0)
                {
                    RSA_free(rsaCert);
                    rsaCert = 0;
                }
            }
        }

        // Couldn't load file, last ditch effort - generate a key on the fly.
        if(rsa_tmp == 0)
        {
            rsa_tmp = RSA_generate_key(keyLength, RSA_F4, 0, 0);
        }

        // Save in our temporary key cache.
        if(rsa_tmp != 0)
        {
            _tempRSAKeys[keyLength] = new RSAPrivateKey(rsa_tmp);
        }
        else if(_traceLevels->security >= SECURITY_WARNINGS)
        {
            Trace out(_logger, _traceLevels->securityCat);
            out << "WRN Unable to obtain a " << dec << keyLength << "-bit RSA key.\n";
        }
    }

    return rsa_tmp;
}

DH*
IceSSL::OpenSSLPluginI::getDHParams(int isExport, int keyLength)
{
    IceUtil::Mutex::Lock sync(_tempDHKeysMutex);

    DH* dh_tmp = 0;

    const DHMap::iterator& retVal = _tempDHKeys.find(keyLength);

    // Does the key already exist?
    if(retVal != _tempDHKeys.end())
    {
        // Yes!  Use it.
        dh_tmp = (*retVal).second->get();
    }
    else
    {
        const DHParamsMap::iterator& it = _tempDHParamsFileMap.find(keyLength);

        // First we try to load params from specified files
        if(it != _tempDHParamsFileMap.end())
        {
            DiffieHellmanParamsFile& dhParamsFile = (*it).second;

            string dhFile = dhParamsFile.getFileName();

            dh_tmp = loadDHParam(dhFile.c_str());
        }

        // If that doesn't work, use a compiled-in group.
        if(dh_tmp == 0)
        {
            switch(keyLength)
            {
                case 512 :
                {
                    dh_tmp = getTempDH512();
                    break;
                }
        
                case 1024 :
                {
                    dh_tmp = getTempDH1024();
                    break;
                }

                case 2048 :
                {
                    dh_tmp = getTempDH2048();
                    break;
                }

                case 4096 :
                {
                    dh_tmp = getTempDH4096();
                    break;
                }
            }
        }

        if(dh_tmp != 0)
        {
            // Cache the dh params for quick lookup - no
            // extra processing required then.
            _tempDHKeys[keyLength] = new DHParams(dh_tmp);
        }
        else if(_traceLevels->security >= SECURITY_WARNINGS)
        {
            Trace out(_logger, _traceLevels->securityCat);
            out << "WRN Unable to obtain a " << dec << keyLength << "-bit Diffie-Hellman parameter group.\n";
        }
    }

    return dh_tmp;
}

void
IceSSL::OpenSSLPluginI::setCertificateVerifier(ContextType contextType,
                                               const CertificateVerifierPtr& verifier)
{
    IceUtil::RecMutex::Lock sync(_configMutex);

    IceSSL::CertificateVerifierOpenSSLPtr castVerifier;
    castVerifier = CertificateVerifierOpenSSLPtr::dynamicCast(verifier);

    if(!castVerifier.get())
    {
        CertificateVerifierTypeException cvtEx(__FILE__, __LINE__);
        throw cvtEx;
    }

    castVerifier->setContext(contextType);

    if(contextType == Client || contextType == ClientServer)
    {
        _clientContext.setCertificateVerifier(castVerifier);
    }

    if(contextType == Server || contextType == ClientServer)
    {
        _serverContext.setCertificateVerifier(castVerifier);
    }
}

void
IceSSL::OpenSSLPluginI::addTrustedCertificateBase64(ContextType contextType, const string& certString)
{
    IceUtil::RecMutex::Lock sync(_configMutex);

    if(contextType == Client || contextType == ClientServer)
    {
        _clientContext.addTrustedCertificateBase64(certString);
    }

    if(contextType == Server || contextType == ClientServer)
    {
        _serverContext.addTrustedCertificateBase64(certString);
    }
}

void
IceSSL::OpenSSLPluginI::addTrustedCertificate(ContextType contextType, const Ice::ByteSeq& certSeq)
{
    IceUtil::RecMutex::Lock sync(_configMutex);

    if(contextType == Client || contextType == ClientServer)
    {
        _clientContext.addTrustedCertificate(certSeq);
    }

    if(contextType == Server || contextType == ClientServer)
    {
        _serverContext.addTrustedCertificate(certSeq);
    }
}

void
IceSSL::OpenSSLPluginI::setRSAKeysBase64(ContextType contextType, const string& privateKey, const string& publicKey)
{
    IceUtil::RecMutex::Lock sync(_configMutex);

    if(contextType == Client || contextType == ClientServer)
    {
        _clientContext.setRSAKeysBase64(privateKey, publicKey);
    }

    if(contextType == Server || contextType == ClientServer)
    {
        _serverContext.setRSAKeysBase64(privateKey, publicKey);
    }
}

void
IceSSL::OpenSSLPluginI::setRSAKeys(ContextType contextType,
				   const ByteSeq& privateKey,
				   const ByteSeq& publicKey)
{
    IceUtil::RecMutex::Lock sync(_configMutex);

    if(contextType == Client || contextType == ClientServer)
    {
        _clientContext.setRSAKeys(privateKey, publicKey);
    }

    if(contextType == Server || contextType == ClientServer)
    {
        _serverContext.setRSAKeys(privateKey, publicKey);
    }
}

CertificateVerifierPtr
IceSSL::OpenSSLPluginI::getDefaultCertVerifier()
{
    return new DefaultCertificateVerifier(getTraceLevels(), _protocolPluginFacade->getCommunicator());
}

CertificateVerifierPtr
IceSSL::OpenSSLPluginI::getSingleCertVerifier(const ByteSeq& certSeq)
{
    return new SingleCertificateVerifier(certSeq);
}

void
IceSSL::OpenSSLPluginI::destroy()
{
}

TraceLevelsPtr
IceSSL::OpenSSLPluginI::getTraceLevels() const
{
    return _traceLevels;
}

LoggerPtr
IceSSL::OpenSSLPluginI::getLogger() const
{
    return _logger;
}

StatsPtr
IceSSL::OpenSSLPluginI::getStats() const
{
    //
    // Don't cache the stats object. It might not be set on the
    // communicator when the plug-in is initialized.
    //
    try
    {
	return _protocolPluginFacade->getCommunicator()->getStats();
    }
    catch(const CommunicatorDestroyedException&)
    {
	return 0;
    }
}

PropertiesPtr
IceSSL::OpenSSLPluginI::getProperties() const
{
    return _properties;
}

IceInternal::ProtocolPluginFacadePtr
IceSSL::OpenSSLPluginI::getProtocolPluginFacade() const
{
    return _protocolPluginFacade;
}

//
// Private
//

int
IceSSL::OpenSSLPluginI::seedRand()
{
#ifdef WINDOWS
    RAND_screen();
#endif

    char buffer[1024];
    const char* file = RAND_file_name(buffer, sizeof(buffer));

    if(file == 0)
    {
        return 0;
    }
    
    return RAND_load_file(file, -1);
}

long
IceSSL::OpenSSLPluginI::loadRandFiles(const string& names)
{
    if(!names.empty())
    {
        return 0;
    }

    long tot = 0;
    int egd;

    // Make a modifiable copy of the string.
    char* namesString = new char[names.length() + 1];
    assert(namesString != 0);

    strcpy(namesString, names.c_str());

#ifdef _WIN32
    const char* seps = ";";
#else
    const char* seps = ":";
#endif

    char* token = strtok(namesString, seps);

    while(token != 0)
    {
        egd = RAND_egd(token);

        if(egd > 0)
        {
            tot += egd;
        }
        else
        {
            tot += RAND_load_file(token, -1);
        }

        token = strtok(0, seps);
    }

    if(tot > 512)
    {
        _randSeeded = 1;
    }

    delete []namesString;

    return tot;
}

void
IceSSL::OpenSSLPluginI::initRandSystem(const string& randBytesFiles)
{
    if(_randSeeded)
    {
        return;
    }

    long randBytesLoaded = seedRand();

    if(!randBytesFiles.empty())
    {
        randBytesLoaded += loadRandFiles(randBytesFiles);
    }

    if(!randBytesLoaded && !RAND_status() && (_traceLevels->security >= SECURITY_WARNINGS))
    {
        // In this case, there are two options open to us - specify a random data file using the
        // RANDFILE environment variable, or specify additional random data files in the
        // SSL configuration file.
        Trace out(_logger, _traceLevels->securityCat);
        out << "WRN there is a lack of random data, consider specifying additional random data files";
    }

    _randSeeded = (randBytesLoaded > 0 ? 1 : 0);
}

void
IceSSL::OpenSSLPluginI::loadTempCerts(TempCertificates& tempCerts)
{
    RSAVector::iterator iRSA = tempCerts.getRSACerts().begin();
    RSAVector::iterator eRSA = tempCerts.getRSACerts().end();

    while(iRSA != eRSA)
    {
        _tempRSAFileMap[(*iRSA).getKeySize()] = *iRSA;
        iRSA++;
    }

    DHVector::iterator iDHP = tempCerts.getDHParams().begin();
    DHVector::iterator eDHP = tempCerts.getDHParams().end();

    while(iDHP != eDHP)
    {
        _tempDHParamsFileMap[(*iDHP).getKeySize()] = *iDHP;
        iDHP++;
    }
}

//
// Note: These two methods are used to remember each thread that uses the IceSSL plugin,
//       and then clean up the thread-specific error queue on plugin shutdown.
//

void
IceSSL::OpenSSLPluginI::registerThread()
{
    unsigned long threadID = idFunction();

    IceUtil::Mutex::Lock sync(_threadIdCacheMutex);

    if(find(_threadIdCache.begin(), _threadIdCache.end(), threadID) == _threadIdCache.end())
    {
        _threadIdCache.push_back(threadID);
    }
}

void
IceSSL::OpenSSLPluginI::unregisterThreads()
{
    IceUtil::Mutex::Lock sync(_threadIdCacheMutex);

    for_each(_threadIdCache.begin(), _threadIdCache.end(), ERR_remove_state);
}