Skip to content

Commit

Permalink
Merge pull request #48 from vapor/global-initialization-sync
Browse files Browse the repository at this point in the history
ensure global context initialization is thread safe
  • Loading branch information
loganwright authored Jun 1, 2017
2 parents 657ae89 + e58fdee commit 33bbe3a
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions Sources/TLS/Context.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import CTLS
import Foundation
import Dispatch

public typealias CContext = UnsafeMutablePointer<SSL_CTX>
public typealias CMethod = UnsafePointer<SSL_METHOD>
Expand All @@ -12,7 +13,16 @@ public typealias CSSL = UnsafeMutablePointer<SSL>
/// The context is used to create secure sockets and should
/// be reused when creating multiple sockets.
public final class Context {
private static var isGloballyInitialized = false
/// Dispatch Once is no longer a thing
/// globally initialized vars guarantee same thread safety
/// https://stackoverflow.com/a/37887068/2611971
private static let isGloballyInitialized: Bool = {
SSL_library_init()
SSL_load_error_strings()
OPENSSL_config(nil)
OPENSSL_add_all_algorithms_conf()
return true
}()

public let certificates: Certificates
public let mode: Mode
Expand All @@ -32,13 +42,7 @@ public final class Context {
verifyCertificates: Bool = true,
cipherSuite: String? = nil
) throws {
if !Context.isGloballyInitialized {
SSL_library_init()
SSL_load_error_strings()
OPENSSL_config(nil)
OPENSSL_add_all_algorithms_conf()
Context.isGloballyInitialized = true
}
guard Context.isGloballyInitialized else { fatalError() }

let method: CMethod
switch mode {
Expand Down

0 comments on commit 33bbe3a

Please sign in to comment.