ObjFW  Check-in [7636fc0143]

Overview
Comment:OFOpenSSLTLSStream: Add server support
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | tls-server
Files: files | file ages | folders
SHA3-256: 7636fc01435d037080c19cbca48d33dc4d160513e9de5c452f6d8b0cbf4a86b7
User & Date: js on 2024-11-18 23:18:29
Other Links: branch diff | manifest | tags
Context
2024-11-18
23:27
OFGnuTLSTLSStream: Restore old close behavior Leaf check-in: 716f5721f5 user: js tags: tls-server
23:18
OFOpenSSLTLSStream: Add server support check-in: 7636fc0143 user: js tags: tls-server
20:58
OFX509Certificate*: Rename constructors check-in: 8f1fe21441 user: js tags: tls-server
Changes

Modified src/tls/Makefile from [6ba02952f9] to [d454b3a231].

15
16
17
18
19
20
21
22



23
24
25
26
27
28
29
15
16
17
18
19
20
21

22
23
24
25
26
27
28
29
30
31







-
+
+
+







       ${USE_SRCS_OPENSSL}		\
       ${USE_SRCS_SECURETRANSPORT}

SRCS_GNUTLS = OFGnuTLSTLSStream.m			\
	      OFGnuTLSX509Certificate.m			\
	      OFGnuTLSX509CertificatePrivateKey.m
SRCS_MBEDTLS = OFMbedTLSTLSStream.m
SRCS_OPENSSL = OFOpenSSLTLSStream.m
SRCS_OPENSSL = OFOpenSSLTLSStream.m			\
	       OFOpenSSLX509Certificate.m		\
	       OFOpenSSLX509CertificatePrivateKey.m
SRCS_SECURETRANSPORT = OFSecureTransportTLSStream.m

includesubdir = ObjFWTLS

include ../../buildsys.mk

install-extra:

Modified src/tls/OFGnuTLSTLSStream.m from [e559b50391] to [4722d3e575].

246
247
248
249
250
251
252
253


254
255
256

257
258
259
260
261
262
263
246
247
248
249
250
251
252

253
254
255
256

257
258
259
260
261
262
263
264







-
+
+


-
+







		    GNUTLS_E_SUCCESS)
			@throw [OFTLSHandshakeFailedException
			    exceptionWithStream: self
					   host: host
				      errorCode: initFailedErrorCode];

		if (_verifiesCertificates)
			gnutls_session_set_verify_cert(_session, _host.UTF8String, 0);
			gnutls_session_set_verify_cert(_session,
			    _host.UTF8String, 0);
	}

	if (_certificateChain != nil) {
	if (_certificateChain.count > 0) {
		OFGnuTLSX509CertificatePrivateKey *privateKey =
		    (OFGnuTLSX509CertificatePrivateKey *)_privateKey;
		OFMutableData *certs = [OFMutableData
		    dataWithItemSize: sizeof(gnutls_x509_crt_t)
			    capacity: _certificateChain.count];

		for (OFGnuTLSX509Certificate *cert in _certificateChain) {

Modified src/tls/OFGnuTLSX509Certificate.m from [1050c14b20] to [d29d7aa45b].

74
75
76
77
78
79
80


81
82
83
84
85
86
87
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89







+
+







			@throw e;
		} @finally {
			[certificate release];
		}
	}

	gnutls_free(certs);

	[chain makeImmutable];

	objc_autoreleasePoolPop(pool);

	return chain;
}

- (instancetype)of_initWithGnuTLSCertificate: (gnutls_x509_crt_t)certificate

Modified src/tls/OFOpenSSLTLSStream.h from [117120b8e9] to [f6715b95ac].

25
26
27
28
29
30
31
32

33
34

35
36
37
38
39
40
25
26
27
28
29
30
31

32
33

34
35
36
37
38
39
40







-
+

-
+






OF_ASSUME_NONNULL_BEGIN

#define OFOpenSSLTLSStreamBufferSize 512

OF_SUBCLASSING_RESTRICTED
@interface OFOpenSSLTLSStream: OFTLSStream <OFStreamDelegate>
{
	bool _handshakeDone;
	BIO *_readBIO, *_writeBIO;
	SSL *_SSL;
	BIO *_readBIO, *_writeBIO;
	bool _server, _handshakeDone;
	OFString *_host;
	char _buffer[OFOpenSSLTLSStreamBufferSize];
}
@end

OF_ASSUME_NONNULL_END

Modified src/tls/OFOpenSSLTLSStream.m from [eaf4116fbc] to [e3dec501da].

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
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







+

+
+













-
+







 */

#include "config.h"

#include <errno.h>

#import "OFOpenSSLTLSStream.h"
#import "OFArray.h"
#import "OFData.h"
#import "OFOpenSSLX509Certificate.h"
#import "OFOpenSSLX509CertificatePrivateKey.h"

#include <openssl/err.h>

#import "OFAlreadyOpenException.h"
#import "OFInitializationFailedException.h"
#import "OFNotOpenException.h"
#import "OFReadFailedException.h"
#import "OFTLSHandshakeFailedException.h"
#import "OFWriteFailedException.h"

#define bufferSize OFOpenSSLTLSStreamBufferSize

int _ObjFWTLS_reference;
static SSL_CTX *clientContext;
static SSL_CTX *clientContext, *serverContext;

static OFTLSStreamErrorCode
verifyResultToErrorCode(const SSL *SSL_)
{
	switch (SSL_get_verify_result(SSL_)) {
	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
91
92
93
94
95
96
97




98
99
100
101
102
103
104
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111







+
+
+
+







	SSL_load_error_strings();
	SSL_library_init();

	if ((clientContext = SSL_CTX_new(TLS_client_method())) == NULL ||
	    SSL_CTX_set_default_verify_paths(clientContext) != 1)
		@throw [OFInitializationFailedException
		    exceptionWithClass: self];

	if ((serverContext = SSL_CTX_new(TLS_server_method())) == NULL)
		@throw [OFInitializationFailedException
		    exceptionWithClass: self];
}

- (instancetype)initWithStream: (OFStream <OFReadyForReadingObserving,
				     OFReadyForWritingObserving> *)stream
{
	self = [super initWithStream: stream];

253
254
255
256
257
258
259
260
261



262
263
264
265
266
267
268
260
261
262
263
264
265
266


267
268
269
270
271
272
273
274
275
276







-
-
+
+
+







	    SSL_has_pending(_SSL) || BIO_ctrl_pending(_readBIO) > 0);
#else
	return (_underlyingStream.hasDataInReadBuffer ||
	    SSL_pending(_SSL) > 0 || BIO_ctrl_pending(_readBIO) > 0);
#endif
}

- (void)asyncPerformClientHandshakeWithHost: (OFString *)host
				runLoopMode: (OFRunLoopMode)runLoopMode
- (void)of_asyncPerformHandshakeWithHost: (OFString *)host
				  server: (bool)server
			     runLoopMode: (OFRunLoopMode)runLoopMode
{
	static const OFTLSStreamErrorCode initFailedErrorCode =
	    OFTLSStreamErrorCodeInitializationFailed;
	void *pool = objc_autoreleasePoolPush();
	id exception = nil;
	int status;

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
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







-
+









+
+
+
+
-
+


+

+
-
-
-
-
-
+
+
+
+
+

-
-
+
+

-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







				   host: host
			      errorCode: initFailedErrorCode];
	}

	BIO_set_mem_eof_return(_readBIO, -1);
	BIO_set_mem_eof_return(_writeBIO, -1);

	if ((_SSL = SSL_new(clientContext)) == NULL) {
	if ((_SSL = SSL_new(server ? serverContext : clientContext)) == NULL) {
		BIO_free(_readBIO);
		BIO_free(_writeBIO);
		@throw [OFTLSHandshakeFailedException
		    exceptionWithStream: self
				   host: host
			      errorCode: initFailedErrorCode];
	}

	SSL_set_bio(_SSL, _readBIO, _writeBIO);

	if (server)
		SSL_set_accept_state(_SSL);
	else
	SSL_set_connect_state(_SSL);
		SSL_set_connect_state(_SSL);

	_host = [host copy];
	_server = server;

	if (!server) {
	if (SSL_set_tlsext_host_name(_SSL, _host.UTF8String) != 1)
		@throw [OFTLSHandshakeFailedException
		    exceptionWithStream: self
				   host: host
			      errorCode: initFailedErrorCode];
		if (SSL_set_tlsext_host_name(_SSL, _host.UTF8String) != 1)
			@throw [OFTLSHandshakeFailedException
			    exceptionWithStream: self
					   host: host
				      errorCode: initFailedErrorCode];

	if (_verifiesCertificates) {
		SSL_set_verify(_SSL, SSL_VERIFY_PEER, NULL);
		if (_verifiesCertificates) {
			SSL_set_verify(_SSL, SSL_VERIFY_PEER, NULL);

		if (SSL_set1_host(_SSL, _host.UTF8String) != 1)
			@throw [OFTLSHandshakeFailedException
			    exceptionWithStream: self
					   host: host
				      errorCode: initFailedErrorCode];
			if (SSL_set1_host(_SSL, _host.UTF8String) != 1)
				@throw [OFTLSHandshakeFailedException
				    exceptionWithStream: self
						   host: host
					      errorCode: initFailedErrorCode];
		}
	}

	if (_certificateChain.count > 0) {
		OFOpenSSLX509Certificate *certificate =
		    (OFOpenSSLX509Certificate *)_certificateChain.firstObject;
		OFOpenSSLX509CertificatePrivateKey *privateKey =
		    (OFOpenSSLX509CertificatePrivateKey *)_privateKey;
		bool first = true;

		if (SSL_use_certificate(_SSL,
		    certificate.of_openSSLCertificate) != 1 ||
		    SSL_use_PrivateKey(_SSL,
		    privateKey.of_openSSLPrivateKey) != 1)
			@throw [OFTLSHandshakeFailedException
			    exceptionWithStream: self
					   host: host
				      errorCode: initFailedErrorCode];

		for (OFOpenSSLX509Certificate *iter in _certificateChain) {
			if (first) {
				first = false;
				continue;
			}

			if (SSL_add1_chain_cert(_SSL,
			    iter.of_openSSLCertificate) != 1)
				@throw [OFTLSHandshakeFailedException
				    exceptionWithStream: self
						   host: host
					      errorCode: initFailedErrorCode];
		}
	}

	ERR_clear_error();
	status = SSL_do_handshake(_SSL);

	while (BIO_ctrl_pending(_writeBIO) > 0) {
		int tmp = BIO_read(_writeBIO, _buffer, bufferSize);
356
357
358
359
360
361
362

363
364
365
366
367
368












369
370















371
372
373
374
375
376
377
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







+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+


+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







			    exceptionWithStream: self
					   host: host
				      errorCode: OFTLSStreamErrorCodeUnknown];
			break;
		}
	}

	if (server) {
	if ([_delegate respondsToSelector:
	    @selector(stream:didPerformClientHandshakeWithHost:exception:)])
		[_delegate		       stream: self
		    didPerformClientHandshakeWithHost: host
					    exception: exception];

		if ([_delegate respondsToSelector: @selector(
		    streamDidPerformServerHandshake:exception:)])
			[_delegate streamDidPerformServerHandshake: self
							 exception: exception];
	} else {
		if ([_delegate respondsToSelector: @selector(
		    stream:didPerformClientHandshakeWithHost:exception:)])
			[_delegate		       stream: self
			    didPerformClientHandshakeWithHost: host
						    exception: exception];
	}

	objc_autoreleasePoolPop(pool);
}

- (void)asyncPerformClientHandshakeWithHost: (OFString *)host
				runLoopMode: (OFRunLoopMode)runLoopMode
{
	[self of_asyncPerformHandshakeWithHost: host
					server: false
				   runLoopMode: runLoopMode];
}

- (void)asyncPerformServerHandshakeWithRunLoopMode: (OFRunLoopMode)runLoopMode
{
	[self of_asyncPerformHandshakeWithHost: nil
					server: true
				   runLoopMode: runLoopMode];
}

-      (bool)stream: (OFStream *)stream
  didReadIntoBuffer: (void *)buffer
	     length: (size_t)length
	  exception: (id)exception
{
	if (exception == nil) {
419
420
421
422
423
424
425

426
427
428
429
430











431
432
433
434
435
436
437
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







+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+







						   host: _host
					      errorCode: unknownErrorCode];
				break;
			}
		}
	}

	if (_server) {
	if ([_delegate respondsToSelector:
	    @selector(stream:didPerformClientHandshakeWithHost:exception:)])
		[_delegate		       stream: self
		    didPerformClientHandshakeWithHost: _host
					    exception: exception];
		if ([_delegate respondsToSelector: @selector(
		    streamDidPerformServerHandshake:exception:)])
			[_delegate streamDidPerformServerHandshake: self
							 exception: exception];
	} else {
		if ([_delegate respondsToSelector: @selector(
		    stream:didPerformClientHandshakeWithHost:exception:)])
			[_delegate		       stream: self
			    didPerformClientHandshakeWithHost: _host
						    exception: exception];
	}

	[_delegate release];

	return false;
}

- (OFData *)stream: (OFStream *)stream
492
493
494
495
496
497
498

499
500
501
502
503











504
505
506
507
508
509
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







+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+






						   host: _host
					      errorCode: unknownErrorCode];
				break;
			}
		}
	}

	if (_server) {
	if ([_delegate respondsToSelector:
	    @selector(stream:didPerformClientHandshakeWithHost:exception:)])
		[_delegate		       stream: self
		    didPerformClientHandshakeWithHost: _host
					    exception: exception];
		if ([_delegate respondsToSelector: @selector(
		    streamDidPerformServerHandshake:exception:)])
			[_delegate streamDidPerformServerHandshake: self
							 exception: exception];
	} else {
		if ([_delegate respondsToSelector: @selector(
		    stream:didPerformClientHandshakeWithHost:exception:)])
			[_delegate		       stream: self
			    didPerformClientHandshakeWithHost: _host
						    exception: exception];
	}

	[_delegate release];

	return nil;
}
@end

Added src/tls/OFOpenSSLX509Certificate.h version [1ef3e50fe9].






































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * Copyright (c) 2008-2024 Jonathan Schleifer <js@nil.im>
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3.0 only,
 * as published by the Free Software Foundation.
 *
 * 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 Lesser General Public License
 * version 3.0 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3.0 along with this program. If not, see
 * <https://www.gnu.org/licenses/>.
 */

#import "OFX509Certificate.h"

#include <openssl/ssl.h>

OF_ASSUME_NONNULL_BEGIN

OF_SUBCLASSING_RESTRICTED
@interface OFOpenSSLX509Certificate: OFX509Certificate
{
	X509 *_certificate;
}

@property (readonly, nonatomic) X509 *of_openSSLCertificate;

- (instancetype)of_initWithOpenSSLCertificate: (X509 *)certificate;
@end

OF_ASSUME_NONNULL_END

Added src/tls/OFOpenSSLX509Certificate.m version [c2d21fe57d].













































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * Copyright (c) 2008-2024 Jonathan Schleifer <js@nil.im>
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3.0 only,
 * as published by the Free Software Foundation.
 *
 * 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 Lesser General Public License
 * version 3.0 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3.0 along with this program. If not, see
 * <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#import "OFOpenSSLX509Certificate.h"
#import "OFArray.h"
#import "OFData.h"

#import "OFInvalidFormatException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"

@implementation OFOpenSSLX509Certificate
@synthesize of_openSSLCertificate = _certificate;

+ (void)load
{
	if (OFX509CertificateImplementation == Nil)
		OFX509CertificateImplementation = self;
}

+ (OFArray OF_GENERIC(OFX509Certificate *) *)
    certificateChainFromPEMFileAtIRI: (OFIRI *)IRI
{
	OFMutableArray *chain = [OFMutableArray array];
	void *pool = objc_autoreleasePoolPush();
	OFData *data = [OFData dataWithContentsOfIRI: IRI];
	BIO *bio;

	if (data.count * data.itemSize > INT_MAX)
		@throw [OFOutOfRangeException exception];

	bio = BIO_new_mem_buf(data.items, (int)(data.count * data.itemSize));
	if (bio == NULL)
		@throw [OFOutOfMemoryException
		    exceptionWithRequestedSize: data.count * data.itemSize];

	@try {
		for (;;) {
			OFOpenSSLX509Certificate *certificate;
			X509 *cert = X509_new();

			if (cert == NULL)
				@throw [OFOutOfMemoryException exception];

			if (PEM_read_bio_X509(bio, &cert, NULL, NULL) == NULL) {
				X509_free(cert);
				break;
			}

			@try {
				certificate = [[self alloc]
				    of_initWithOpenSSLCertificate: cert];
			} @catch (id e) {
				X509_free(cert);
				@throw e;
			}

			@try {
				[chain addObject: certificate];
			} @finally {
				[certificate release];
			}
		}
	} @finally {
		BIO_free(bio);
	}

	[chain makeImmutable];

	objc_autoreleasePoolPop(pool);

	return chain;
}

- (instancetype)of_initWithOpenSSLCertificate: (X509 *)certificate
{
	self = [super init];

	_certificate = certificate;

	return self;
}

- (void)dealloc
{
	X509_free(_certificate);

	[super dealloc];
}
@end

Added src/tls/OFOpenSSLX509CertificatePrivateKey.h version [aaf86452d6].






































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * Copyright (c) 2008-2024 Jonathan Schleifer <js@nil.im>
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3.0 only,
 * as published by the Free Software Foundation.
 *
 * 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 Lesser General Public License
 * version 3.0 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3.0 along with this program. If not, see
 * <https://www.gnu.org/licenses/>.
 */

#import "OFX509CertificatePrivateKey.h"

#include <openssl/ssl.h>

OF_ASSUME_NONNULL_BEGIN

OF_SUBCLASSING_RESTRICTED
@interface OFOpenSSLX509CertificatePrivateKey: OFX509CertificatePrivateKey
{
	EVP_PKEY *_privateKey;
}

@property (readonly, nonatomic) EVP_PKEY *of_openSSLPrivateKey;

- (instancetype)of_initWithOpenSSLPrivateKey: (EVP_PKEY *)privateKey;
@end

OF_ASSUME_NONNULL_END

Added src/tls/OFOpenSSLX509CertificatePrivateKey.m version [c27359e3ef].




























































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * Copyright (c) 2008-2024 Jonathan Schleifer <js@nil.im>
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3.0 only,
 * as published by the Free Software Foundation.
 *
 * 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 Lesser General Public License
 * version 3.0 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3.0 along with this program. If not, see
 * <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#import "OFOpenSSLX509CertificatePrivateKey.h"
#import "OFData.h"

#import "OFInitializationFailedException.h"
#import "OFInvalidFormatException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"

@implementation OFOpenSSLX509CertificatePrivateKey
@synthesize of_openSSLPrivateKey = _privateKey;

+ (void)load
{
	if (OFX509CertificatePrivateKeyImplementation == Nil)
		OFX509CertificatePrivateKeyImplementation = self;
}

+ (instancetype)privateKeyFromPEMFileAtIRI: (OFIRI *)IRI
{
	void *pool = objc_autoreleasePoolPush();
	OFData *data = [OFData dataWithContentsOfIRI: IRI];
	BIO *bio;
	OFOpenSSLX509CertificatePrivateKey *privateKey;

	if (data.count * data.itemSize > INT_MAX)
		@throw [OFOutOfRangeException exception];

	bio = BIO_new_mem_buf(data.items, (int)(data.count * data.itemSize));
	if (bio == NULL)
		@throw [OFOutOfMemoryException
		    exceptionWithRequestedSize: data.count * data.itemSize];

	@try {
		EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);

		if (key == NULL)
			@throw [OFInvalidFormatException exception];

		@try {
			privateKey = [[self alloc]
			    of_initWithOpenSSLPrivateKey: key];
		} @catch (id e) {
			EVP_PKEY_free(key);
			@throw e;
		}
	} @finally {
		BIO_free(bio);
	}

	objc_autoreleasePoolPop(pool);

	return [privateKey autorelease];
}

- (instancetype)of_initWithOpenSSLPrivateKey: (EVP_PKEY *)privateKey
{
	self = [super init];

	_privateKey = privateKey;

	return self;
}

- (void)dealloc
{
	EVP_PKEY_free(_privateKey);

	[super dealloc];
}
@end