Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix thread safety in pairing endpoints and ChannelHandlers #88

Merged
merged 1 commit into from
Jul 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions Sources/HAP/Endpoints/pairSetup().swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,23 @@ func pairSetup(device: Device) -> Responder {
algorithm: algorithm))
}

// TODO: this memory is not freed, not thread-safe either
var sessions: [ObjectIdentifier: Session] = [:]
// TODO: this memory is not freed
var threadUnsafeSessions: [ObjectIdentifier: Session] = [:]
let rwQueue = DispatchQueue(label: "HAP-\(username)-\(device.identifier)-lock", attributes: .concurrent)

func getSession(for context: RequestContext) -> Session? {
var session: Session?
rwQueue.sync { // Concurrent read
session = threadUnsafeSessions[ObjectIdentifier(context.channel)]
}
return session
}

func setSession(for context: RequestContext, to session: Session?) {
rwQueue.async(flags: .barrier) {
threadUnsafeSessions[ObjectIdentifier(context.channel)] = session
}
}

return { context, request in
guard
Expand All @@ -49,18 +64,18 @@ func pairSetup(device: Device) -> Responder {
case .startRequest:
let session = createSession()
response = try controller.startRequest(data, session)
sessions[ObjectIdentifier(context.channel)] = session
setSession(for:context, to: session)

// M3: iOS Device -> Accessory -- `SRP Verify Request'
case .verifyRequest:
guard let session = sessions[ObjectIdentifier(context.channel)] else {
guard let session = getSession(for:context) else {
throw PairSetupController.Error.invalidSetupState
}
response = try controller.verifyRequest(data, session)

// M5: iOS Device -> Accessory -- `Exchange Request'
case .keyExchangeRequest:
guard let session = sessions[ObjectIdentifier(context.channel)] else {
guard let session = getSession(for:context) else {
throw PairSetupController.Error.invalidSetupState
}
response = try controller.keyExchangeRequest(data, session)
Expand All @@ -72,7 +87,7 @@ func pairSetup(device: Device) -> Responder {
} catch {
logger.warning(error)

sessions[ObjectIdentifier(context.channel)] = nil
setSession(for:context, to: nil)

try? device.changePairingState(.notPaired)

Expand Down
24 changes: 19 additions & 5 deletions Sources/HAP/Endpoints/pairVerify().swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,23 @@ fileprivate enum Error: Swift.Error {
func pairVerify(device: Device) -> Responder {
let controller = PairVerifyController(device: device)

// TODO: this memory is not freed, not thread-safe either
var sessions: [ObjectIdentifier: PairVerifyController.Session] = [:]
// TODO: this memory is not freed
var threadUnsafeSessions: [ObjectIdentifier: Session] = [:]
let rwQueue = DispatchQueue(label: "HAP-PairVerify-\(device.identifier)-lock", attributes: .concurrent)

func getSession(for context: RequestContext) -> Session? {
var session: Session?
rwQueue.sync { // Concurrent read
session = threadUnsafeSessions[ObjectIdentifier(context.channel)]
}
return session
}

func setSession(for context: RequestContext, to session: Session?) {
rwQueue.async(flags: .barrier) {
threadUnsafeSessions[ObjectIdentifier(context.channel)] = session
}
}
return { context, request in
guard
let body = request.body.data,
Expand All @@ -31,14 +45,14 @@ func pairVerify(device: Device) -> Responder {

case .startRequest:
let (response, session) = try controller.startRequest(data)
sessions[ObjectIdentifier(context.channel)] = session
setSession(for:context, to: session)
return HTTPResponse(tags: response)

case .finishRequest:
defer {
sessions[ObjectIdentifier(context.channel)] = nil
setSession(for:context, to: nil)
}
guard let session = sessions[ObjectIdentifier(context.channel)] else {
guard let session = getSession(for:context) else {
throw Error.noSession
}

Expand Down
8 changes: 6 additions & 2 deletions Sources/HAP/Server/ChannelHandlers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -193,21 +193,25 @@ class ControllerHandler: ChannelDuplexHandler {

func channelActive(ctx: ChannelHandlerContext) {
let channel = ctx.channel
var channelsCount = 0
channelsSyncQueue.sync {
self.channels[ObjectIdentifier(channel)] = channel
channelsCount = self.channels.count
}
logger.info("Controller \(channel.remoteAddress?.description ?? "N/A") connected, \(self.channels.count) controllers total")
logger.info("Controller \(channel.remoteAddress?.description ?? "N/A") connected, \(channelsCount) controllers total")
ctx.fireChannelActive()
}

func channelInactive(ctx: ChannelHandlerContext) {
let channel = ctx.channel
var channelsCount = 0
channelsSyncQueue.sync {
self.channels.removeValue(forKey: ObjectIdentifier(channel))
self.pairings.removeValue(forKey: ObjectIdentifier(channel))
channelsCount = self.channels.count
}
self.removeSubscriptions?(channel)
logger.info("Controller \(channel.remoteAddress?.description ?? "N/A") disconnected, \(self.channels.count) controllers total")
logger.info("Controller \(channel.remoteAddress?.description ?? "N/A") disconnected, \(channelsCount) controllers total")
ctx.fireChannelInactive()
}

Expand Down