tunnelkit/TunnelKit/Sources/AppExtension/Transport/NEUDPSocket.swift

197 lines
7.2 KiB
Swift
Raw Normal View History

2018-08-23 08:19:25 +00:00
//
// NEUDPInterface.swift
// TunnelKit
2018-08-23 08:19:25 +00:00
//
// Created by Davide De Rosa on 8/27/17.
2020-01-11 08:26:41 +00:00
// Copyright (c) 2020 Davide De Rosa. All rights reserved.
//
// https://github.com/passepartoutvpn
//
// This file is part of TunnelKit.
//
// TunnelKit is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// TunnelKit 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with TunnelKit. If not, see <http://www.gnu.org/licenses/>.
//
// This file incorporates work covered by the following copyright and
// permission notice:
//
// Copyright (c) 2018-Present Private Internet Access
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
2018-08-23 08:19:25 +00:00
import Foundation
import NetworkExtension
import SwiftyBeaver
private let log = SwiftyBeaver.self
2019-05-24 12:58:25 +00:00
/// UDP implementation of a `GenericSocket` via NetworkExtension.
2019-05-23 19:49:20 +00:00
public class NEUDPSocket: NSObject, GenericSocket {
2018-08-23 08:19:25 +00:00
private static var linkContext = 0
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public let impl: NWUDPSession
2018-08-23 08:19:25 +00:00
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public init(impl: NWUDPSession) {
2018-08-23 08:19:25 +00:00
self.impl = impl
isActive = false
isShutdown = false
}
// MARK: GenericSocket
private weak var queue: DispatchQueue?
private var isActive: Bool
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public private(set) var isShutdown: Bool
2018-08-23 08:19:25 +00:00
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public var remoteAddress: String? {
2018-08-23 08:19:25 +00:00
return (impl.resolvedEndpoint as? NWHostEndpoint)?.hostname
}
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public var hasBetterPath: Bool {
2018-08-23 08:19:25 +00:00
return impl.hasBetterPath
}
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public weak var delegate: GenericSocketDelegate?
2018-08-23 08:19:25 +00:00
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public func observe(queue: DispatchQueue, activeTimeout: Int) {
2018-08-23 08:19:25 +00:00
isActive = false
self.queue = queue
queue.schedule(after: .milliseconds(activeTimeout)) { [weak self] in
guard let _self = self else {
return
}
guard _self.isActive else {
_self.delegate?.socketDidTimeout(_self)
return
}
}
2018-08-24 10:44:17 +00:00
impl.addObserver(self, forKeyPath: #keyPath(NWUDPSession.state), options: [.initial, .new], context: &NEUDPSocket.linkContext)
impl.addObserver(self, forKeyPath: #keyPath(NWUDPSession.hasBetterPath), options: .new, context: &NEUDPSocket.linkContext)
2018-08-23 08:19:25 +00:00
}
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public func unobserve() {
2018-08-24 10:44:17 +00:00
impl.removeObserver(self, forKeyPath: #keyPath(NWUDPSession.state), context: &NEUDPSocket.linkContext)
impl.removeObserver(self, forKeyPath: #keyPath(NWUDPSession.hasBetterPath), context: &NEUDPSocket.linkContext)
2018-08-23 08:19:25 +00:00
}
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public func shutdown() {
2018-08-23 08:19:25 +00:00
impl.cancel()
}
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public func upgraded() -> GenericSocket? {
2018-08-23 08:19:25 +00:00
guard impl.hasBetterPath else {
return nil
}
2018-08-24 10:44:17 +00:00
return NEUDPSocket(impl: NWUDPSession(upgradeFor: impl))
2018-08-23 08:19:25 +00:00
}
// MARK: Connection KVO (any queue)
2019-05-24 12:58:25 +00:00
/// :nodoc:
2019-05-23 19:49:20 +00:00
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
2018-08-24 10:44:17 +00:00
guard (context == &NEUDPSocket.linkContext) else {
2018-08-23 08:19:25 +00:00
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
// if let keyPath = keyPath {
// log.debug("KVO change reported (\(anyPointer(object)).\(keyPath))")
// }
queue?.async {
self.observeValueInTunnelQueue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
private func observeValueInTunnelQueue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// if let keyPath = keyPath {
// log.debug("KVO change reported (\(anyPointer(object)).\(keyPath))")
// }
guard let impl = object as? NWUDPSession, (impl == self.impl) else {
log.warning("Discard KVO change from old socket")
return
}
guard let keyPath = keyPath else {
return
}
switch keyPath {
case #keyPath(NWUDPSession.state):
if let resolvedEndpoint = impl.resolvedEndpoint {
2018-10-24 16:25:04 +00:00
log.debug("Socket state is \(impl.state) (endpoint: \(impl.endpoint.maskedDescription) -> \(resolvedEndpoint.maskedDescription))")
2018-08-23 08:19:25 +00:00
} else {
2018-10-24 16:25:04 +00:00
log.debug("Socket state is \(impl.state) (endpoint: \(impl.endpoint.maskedDescription) -> in progress)")
2018-08-23 08:19:25 +00:00
}
switch impl.state {
case .ready:
guard !isActive else {
return
}
isActive = true
delegate?.socketDidBecomeActive(self)
case .cancelled:
isShutdown = true
delegate?.socket(self, didShutdownWithFailure: false)
case .failed:
isShutdown = true
// if timedOut {
// delegate?.socketShouldChangeProtocol(self)
// }
delegate?.socket(self, didShutdownWithFailure: true)
default:
break
}
case #keyPath(NWUDPSession.hasBetterPath):
guard impl.hasBetterPath else {
break
}
log.debug("Socket has a better path")
delegate?.socketHasBetterPath(self)
default:
break
}
}
}
2019-05-23 19:49:20 +00:00
/// :nodoc:
2018-08-24 10:44:17 +00:00
extension NEUDPSocket {
2019-05-23 19:49:20 +00:00
public override var description: String {
2018-08-23 08:19:25 +00:00
guard let hostEndpoint = impl.endpoint as? NWHostEndpoint else {
2018-10-24 16:06:39 +00:00
return impl.endpoint.maskedDescription
2018-08-23 08:19:25 +00:00
}
2018-11-05 14:48:34 +00:00
return "\(hostEndpoint.hostname.maskedDescription):\(hostEndpoint.port)"
2018-08-23 08:19:25 +00:00
}
}