
#import <foundation/foundation.h>

#import <stdio.h>	// I need this for the ssl include
#import <ssl/ssl.h>
#import <ssl/err.h>

#import "CTXHandler.h"

static	CTXHandler	*sharedCTXHandler = nil;

//
// I need this Class, because earlier versions (before 0.5.2a) of 
// the SSLeay-lib had problems to allocate and freeing the CTX-Structure.
// 
// I could remove this Class now, but who knows what the future brings ;-)...
//
@implementation CTXHandler

+ sharedCTXHandler
{
	static BOOL	fInit = NO;
	
	if (fInit == NO)
	{
		SSL_load_error_strings();
		fInit = YES;
	}
	
	if (sharedCTXHandler == nil)
	{
		CTXHandler	*tempCTXHandler;
		
		tempCTXHandler = [[CTXHandler alloc] init];
		if ([tempCTXHandler setDefaultVerifyPaths] == NO) 
		{
			[tempCTXHandler release];
			[NSException raise:@"CannotLoadCertificates"
			format:@"CTXHandler: Cannot load certificates via setDefaultVerifyPaths"];
		}
		else
			sharedCTXHandler = tempCTXHandler;
	}

	return sharedCTXHandler;
}

- init
{
	[super init];
	
	_ctx = SSL_CTX_new();
	
	return self;
}

- (void)dealloc
{
	if (_ctx != NULL)
	{
		SSL_CTX_free(_ctx);
		_ctx = NULL;
	}
	
	[super dealloc];
}

- (SSL_CTX *)ctx
{
	return _ctx;
}

- (BOOL)setDefaultVerifyPaths
{
	if (!SSL_set_default_verify_paths(_ctx)) 
		return NO;
		
	return YES;
}

@end
