2018-08-23 08:19:25 +00:00
|
|
|
//
|
|
|
|
// SessionProxy.swift
|
2018-08-23 10:07:55 +00:00
|
|
|
// TunnelKit
|
2018-08-23 08:19:25 +00:00
|
|
|
//
|
|
|
|
// Created by Davide De Rosa on 2/3/17.
|
2018-08-27 18:30:09 +00:00
|
|
|
// Copyright (c) 2018 Davide De Rosa. All rights reserved.
|
|
|
|
//
|
|
|
|
// https://github.com/keeshux
|
|
|
|
//
|
|
|
|
// 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 SwiftyBeaver
|
2018-08-23 10:09:44 +00:00
|
|
|
import __TunnelKitNative
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private let log = SwiftyBeaver.self
|
|
|
|
|
|
|
|
private extension Error {
|
2018-09-07 21:18:28 +00:00
|
|
|
func isTunnelError() -> Bool {
|
|
|
|
let te = self as NSError
|
|
|
|
return te.domain == TunnelKitErrorDomain
|
|
|
|
}
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
func isDataPathOverflow() -> Bool {
|
|
|
|
let te = self as NSError
|
2018-08-23 10:07:55 +00:00
|
|
|
return te.domain == TunnelKitErrorDomain && te.code == TunnelKitErrorCode.dataPathOverflow.rawValue
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Observes major events notified by a `SessionProxy`.
|
|
|
|
public protocol SessionProxyDelegate: class {
|
|
|
|
|
|
|
|
/**
|
|
|
|
Called after starting a session.
|
|
|
|
|
|
|
|
- Parameter remoteAddress: The address of the VPN server.
|
2018-08-24 09:57:09 +00:00
|
|
|
- Parameter reply: The compound `SessionReply` containing tunnel settings.
|
2018-08-23 08:19:25 +00:00
|
|
|
*/
|
2018-08-24 09:57:09 +00:00
|
|
|
func sessionDidStart(_: SessionProxy, remoteAddress: String, reply: SessionReply)
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
Called after stopping a session.
|
|
|
|
|
|
|
|
- Parameter shouldReconnect: When `true`, the session can/should be restarted. Usually because the stop reason was recoverable.
|
|
|
|
- Seealso: `SessionProxy.reconnect(...)`
|
|
|
|
*/
|
|
|
|
func sessionDidStop(_: SessionProxy, shouldReconnect: Bool)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Provides methods to set up and maintain an OpenVPN session.
|
|
|
|
public class SessionProxy {
|
|
|
|
private enum StopMethod {
|
|
|
|
case shutdown
|
|
|
|
|
|
|
|
case reconnect
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Configuration
|
|
|
|
|
2018-08-23 11:43:04 +00:00
|
|
|
private let configuration: Configuration
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2018-09-08 18:29:29 +00:00
|
|
|
private var keepAliveInterval: TimeInterval? {
|
|
|
|
let interval: TimeInterval?
|
|
|
|
if let negInterval = pushReply?.ping, negInterval > 0 {
|
|
|
|
interval = TimeInterval(negInterval)
|
|
|
|
} else if let cfgInterval = configuration.keepAliveInterval, cfgInterval > 0.0 {
|
|
|
|
interval = cfgInterval
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return interval
|
|
|
|
}
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
/// An optional `SessionProxyDelegate` for receiving session events.
|
|
|
|
public weak var delegate: SessionProxyDelegate?
|
|
|
|
|
|
|
|
// MARK: State
|
|
|
|
|
|
|
|
private let queue: DispatchQueue
|
|
|
|
|
|
|
|
private var tlsObserver: NSObjectProtocol?
|
|
|
|
|
|
|
|
private var keys: [UInt8: SessionKey]
|
|
|
|
|
|
|
|
private var oldKeys: [SessionKey]
|
|
|
|
|
|
|
|
private var negotiationKeyIdx: UInt8
|
|
|
|
|
|
|
|
private var currentKeyIdx: UInt8?
|
|
|
|
|
|
|
|
private var negotiationKey: SessionKey {
|
|
|
|
guard let key = keys[negotiationKeyIdx] else {
|
|
|
|
fatalError("Keys are empty or index \(negotiationKeyIdx) not found in \(keys.keys)")
|
|
|
|
}
|
|
|
|
return key
|
|
|
|
}
|
|
|
|
|
|
|
|
private var currentKey: SessionKey? {
|
|
|
|
guard let i = currentKeyIdx else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return keys[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
private var link: LinkInterface?
|
|
|
|
|
|
|
|
private var tunnel: TunnelInterface?
|
|
|
|
|
|
|
|
private var isReliableLink: Bool {
|
|
|
|
return link?.isReliable ?? false
|
|
|
|
}
|
|
|
|
|
2018-09-01 23:30:19 +00:00
|
|
|
private var pushReply: SessionReply?
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private var nextPushRequestDate: Date?
|
|
|
|
|
|
|
|
private var connectedDate: Date?
|
|
|
|
|
2018-09-09 12:55:14 +00:00
|
|
|
private var lastPing: BidirectionalState<Date>
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private var isStopping: Bool
|
|
|
|
|
|
|
|
/// The optional reason why the session stopped.
|
|
|
|
public private(set) var stopError: Error?
|
|
|
|
|
|
|
|
// MARK: Control
|
|
|
|
|
2018-09-09 15:12:39 +00:00
|
|
|
private var controlChannel: ControlChannel
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private var authenticator: Authenticator?
|
|
|
|
|
|
|
|
// MARK: Init
|
|
|
|
|
|
|
|
/**
|
|
|
|
Creates a VPN session.
|
|
|
|
|
|
|
|
- Parameter queue: The `DispatchQueue` where to run the session loop.
|
2018-08-23 11:43:04 +00:00
|
|
|
- Parameter configuration: The `SessionProxy.Configuration` to use for this session.
|
2018-08-23 08:19:25 +00:00
|
|
|
*/
|
2018-08-23 11:43:04 +00:00
|
|
|
public init(queue: DispatchQueue, configuration: Configuration) throws {
|
2018-08-23 08:19:25 +00:00
|
|
|
self.queue = queue
|
2018-08-23 11:43:04 +00:00
|
|
|
self.configuration = configuration
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
keys = [:]
|
|
|
|
oldKeys = []
|
|
|
|
negotiationKeyIdx = 0
|
2018-09-09 12:55:14 +00:00
|
|
|
lastPing = BidirectionalState(withResetValue: Date.distantPast)
|
2018-08-23 08:19:25 +00:00
|
|
|
isStopping = false
|
|
|
|
|
2018-09-09 15:12:39 +00:00
|
|
|
controlChannel = ControlChannel()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
deinit {
|
|
|
|
cleanup()
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Public interface
|
|
|
|
|
|
|
|
/**
|
|
|
|
Establishes the link interface for this session. The interface must be up and running for sending and receiving packets.
|
|
|
|
|
|
|
|
- Precondition: `link` is an active network interface.
|
|
|
|
- Postcondition: The VPN negotiation is started.
|
|
|
|
- Parameter link: The `LinkInterface` on which to establish the VPN session.
|
|
|
|
*/
|
|
|
|
public func setLink(_ link: LinkInterface) {
|
|
|
|
guard (self.link == nil) else {
|
|
|
|
log.warning("Link interface already set!")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.debug("Starting VPN session")
|
|
|
|
|
|
|
|
// WARNING: runs in notification source queue (we know it's "queue", but better be safe than sorry)
|
|
|
|
tlsObserver = NotificationCenter.default.addObserver(forName: .TLSBoxPeerVerificationError, object: nil, queue: nil) { (notification) in
|
|
|
|
self.queue.async {
|
|
|
|
self.deferStop(.shutdown, SessionError.peerVerification)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
self.link = link
|
|
|
|
start()
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Returns `true` if the current session can rebind to a new link with `rebindLink(...)`.
|
|
|
|
|
|
|
|
- Returns: `true` if supports link rebinding.
|
|
|
|
*/
|
|
|
|
public func canRebindLink() -> Bool {
|
2018-09-01 23:30:19 +00:00
|
|
|
return (pushReply?.peerId != nil)
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Rebinds the session to a new link if supported.
|
|
|
|
|
|
|
|
- Precondition: `link` is an active network interface.
|
|
|
|
- Postcondition: The VPN session is active.
|
|
|
|
- Parameter link: The `LinkInterface` on which to establish the VPN session.
|
|
|
|
- Seealso: `canRebindLink()`.
|
|
|
|
*/
|
|
|
|
public func rebindLink(_ link: LinkInterface) {
|
2018-09-01 23:30:19 +00:00
|
|
|
guard let _ = pushReply?.peerId else {
|
2018-08-23 08:19:25 +00:00
|
|
|
log.warning("Session doesn't support link rebinding!")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
isStopping = false
|
|
|
|
stopError = nil
|
|
|
|
|
|
|
|
log.debug("Rebinding VPN session to a new link")
|
|
|
|
self.link = link
|
|
|
|
loopLink()
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Establishes the tunnel interface for this session. The interface must be up and running for sending and receiving packets.
|
|
|
|
|
|
|
|
- Precondition: `tunnel` is an active network interface.
|
|
|
|
- Postcondition: The VPN data channel is open.
|
|
|
|
- Parameter tunnel: The `TunnelInterface` on which to exchange the VPN data traffic.
|
|
|
|
*/
|
|
|
|
public func setTunnel(tunnel: TunnelInterface) {
|
|
|
|
guard (self.tunnel == nil) else {
|
|
|
|
log.warning("Tunnel interface already set!")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
self.tunnel = tunnel
|
|
|
|
loopTunnel()
|
|
|
|
}
|
|
|
|
|
2018-09-09 15:12:39 +00:00
|
|
|
/**
|
|
|
|
Returns the current data bytes count.
|
|
|
|
|
|
|
|
- Returns: The current data bytes count as a pair, inbound first.
|
|
|
|
*/
|
|
|
|
public func dataCount() -> (Int, Int) {
|
|
|
|
return controlChannel.currentDataCount()
|
|
|
|
}
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
/**
|
|
|
|
Shuts down the session with an optional `Error` reason. Does nothing if the session is already stopped or about to stop.
|
|
|
|
|
|
|
|
- Parameter error: An optional `Error` being the reason of the shutdown.
|
|
|
|
*/
|
|
|
|
public func shutdown(error: Error?) {
|
|
|
|
guard !isStopping else {
|
|
|
|
log.warning("Ignore stop request, already stopping!")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
deferStop(.shutdown, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Shuts down the session with an optional `Error` reason and signals a reconnect flag to `SessionProxyDelegate.sessionDidStop(...)`. Does nothing if the session is already stopped or about to stop.
|
|
|
|
|
|
|
|
- Parameter error: An optional `Error` being the reason of the shutdown.
|
|
|
|
- Seealso: `SessionProxyDelegate.sessionDidStop(...)`
|
|
|
|
*/
|
|
|
|
public func reconnect(error: Error?) {
|
|
|
|
guard !isStopping else {
|
|
|
|
log.warning("Ignore stop request, already stopping!")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
deferStop(.reconnect, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: cleanup
|
|
|
|
/**
|
|
|
|
Cleans up the session resources.
|
|
|
|
*/
|
|
|
|
public func cleanup() {
|
|
|
|
log.info("Cleaning up...")
|
|
|
|
|
|
|
|
if let observer = tlsObserver {
|
|
|
|
NotificationCenter.default.removeObserver(observer)
|
|
|
|
tlsObserver = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
keys.removeAll()
|
|
|
|
oldKeys.removeAll()
|
|
|
|
negotiationKeyIdx = 0
|
|
|
|
currentKeyIdx = nil
|
|
|
|
|
|
|
|
nextPushRequestDate = nil
|
|
|
|
connectedDate = nil
|
|
|
|
authenticator = nil
|
2018-09-01 23:30:19 +00:00
|
|
|
pushReply = nil
|
2018-08-23 08:19:25 +00:00
|
|
|
link = nil
|
|
|
|
if !(tunnel?.isPersistent ?? false) {
|
|
|
|
tunnel = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
isStopping = false
|
|
|
|
stopError = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Loop
|
|
|
|
|
|
|
|
// Ruby: start
|
|
|
|
private func start() {
|
|
|
|
loopLink()
|
|
|
|
hardReset()
|
|
|
|
|
|
|
|
guard !keys.isEmpty else {
|
|
|
|
fatalError("Main loop must follow hard reset, keys are empty!")
|
|
|
|
}
|
|
|
|
|
|
|
|
loopNegotiation()
|
|
|
|
}
|
|
|
|
|
|
|
|
private func loopNegotiation() {
|
|
|
|
guard let link = link else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
guard !keys.isEmpty else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
guard !negotiationKey.didHardResetTimeOut(link: link) else {
|
|
|
|
doReconnect(error: SessionError.negotiationTimeout)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
guard !negotiationKey.didNegotiationTimeOut(link: link) else {
|
|
|
|
doShutdown(error: SessionError.negotiationTimeout)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !isReliableLink {
|
|
|
|
pushRequest()
|
|
|
|
flushControlQueue()
|
|
|
|
}
|
|
|
|
|
|
|
|
guard (negotiationKey.controlState == .connected) else {
|
|
|
|
queue.asyncAfter(deadline: .now() + CoreConfiguration.tickInterval) { [weak self] in
|
|
|
|
self?.loopNegotiation()
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// let loop die when negotiation is complete
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: udp_loop
|
|
|
|
private func loopLink() {
|
|
|
|
let loopedLink = link
|
|
|
|
loopedLink?.setReadHandler(queue: queue) { [weak self] (newPackets, error) in
|
|
|
|
guard loopedLink === self?.link else {
|
|
|
|
log.warning("Ignoring read from outdated LINK")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if let error = error {
|
|
|
|
log.error("Failed LINK read: \(error)")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if let packets = newPackets, !packets.isEmpty {
|
|
|
|
self?.maybeRenegotiate()
|
|
|
|
|
|
|
|
// log.verbose("Received \(packets.count) packets from LINK")
|
|
|
|
self?.receiveLink(packets: packets)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: tun_loop
|
|
|
|
private func loopTunnel() {
|
|
|
|
tunnel?.setReadHandler(queue: queue) { [weak self] (newPackets, error) in
|
|
|
|
if let error = error {
|
|
|
|
log.error("Failed TUN read: \(error)")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if let packets = newPackets, !packets.isEmpty {
|
|
|
|
// log.verbose("Received \(packets.count) packets from \(self.tunnelName)")
|
|
|
|
self?.receiveTunnel(packets: packets)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: recv_link
|
|
|
|
private func receiveLink(packets: [Data]) {
|
|
|
|
guard shouldHandlePackets() else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-09-09 12:55:14 +00:00
|
|
|
lastPing.inbound = Date()
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
var dataPacketsByKey = [UInt8: [Data]]()
|
|
|
|
|
|
|
|
for packet in packets {
|
|
|
|
// log.verbose("Received data from LINK (\(packet.count) bytes): \(packet.toHex())")
|
|
|
|
|
|
|
|
guard let firstByte = packet.first else {
|
2018-09-18 16:04:43 +00:00
|
|
|
log.warning("Dropped malformed packet (missing opcode)")
|
2018-08-23 08:19:25 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
let codeValue = firstByte >> 3
|
|
|
|
guard let code = PacketCode(rawValue: codeValue) else {
|
|
|
|
log.warning("Dropped malformed packet (unknown code: \(codeValue))")
|
|
|
|
continue
|
|
|
|
}
|
2018-09-18 16:04:43 +00:00
|
|
|
// log.verbose("Parsed packet with code \(code)")
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
var offset = 1
|
|
|
|
if (code == .dataV2) {
|
2018-09-09 09:40:58 +00:00
|
|
|
guard packet.count >= offset + PacketPeerIdLength else {
|
2018-08-23 08:19:25 +00:00
|
|
|
log.warning("Dropped malformed packet (missing peerId)")
|
|
|
|
continue
|
|
|
|
}
|
2018-09-09 09:40:58 +00:00
|
|
|
offset += PacketPeerIdLength
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (code == .dataV1) || (code == .dataV2) {
|
2018-09-18 16:04:43 +00:00
|
|
|
let key = firstByte & 0b111
|
2018-08-23 08:19:25 +00:00
|
|
|
guard let _ = keys[key] else {
|
|
|
|
log.error("Key with id \(key) not found")
|
|
|
|
deferStop(.shutdown, SessionError.badKey)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// XXX: improve with array reference
|
|
|
|
var dataPackets = dataPacketsByKey[key] ?? [Data]()
|
|
|
|
dataPackets.append(packet)
|
|
|
|
dataPacketsByKey[key] = dataPackets
|
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-09-10 09:12:58 +00:00
|
|
|
let controlPacket: ControlPacket
|
|
|
|
do {
|
2018-09-18 16:04:43 +00:00
|
|
|
let parsedPacket = try controlChannel.readInboundPacket(withData: packet, offset: 0)
|
2018-09-10 09:12:58 +00:00
|
|
|
handleAcks()
|
|
|
|
if parsedPacket.code == .ackV1 {
|
2018-08-23 08:19:25 +00:00
|
|
|
continue
|
|
|
|
}
|
2018-09-10 09:12:58 +00:00
|
|
|
controlPacket = parsedPacket
|
|
|
|
} catch let e {
|
|
|
|
log.warning("Dropped malformed packet: \(e)")
|
2018-08-23 08:19:25 +00:00
|
|
|
continue
|
2018-09-10 09:12:58 +00:00
|
|
|
// deferStop(.shutdown, e)
|
|
|
|
// return
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
2018-09-10 09:12:58 +00:00
|
|
|
sendAck(for: controlPacket)
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2018-09-10 09:12:58 +00:00
|
|
|
let pendingInboundQueue = controlChannel.enqueueInboundPacket(packet: controlPacket)
|
2018-09-09 15:31:11 +00:00
|
|
|
for inboundPacket in pendingInboundQueue {
|
|
|
|
handleControlPacket(inboundPacket)
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// send decrypted packets to tunnel all at once
|
|
|
|
for (keyId, dataPackets) in dataPacketsByKey {
|
|
|
|
guard let sessionKey = keys[keyId] else {
|
|
|
|
log.warning("Accounted a data packet for which the cryptographic key hadn't been found")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
handleDataPackets(dataPackets, key: sessionKey)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: recv_tun
|
|
|
|
private func receiveTunnel(packets: [Data]) {
|
|
|
|
guard shouldHandlePackets() else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
sendDataPackets(packets)
|
2018-09-09 12:55:14 +00:00
|
|
|
lastPing.outbound = Date()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: ping
|
|
|
|
private func ping() {
|
|
|
|
guard (currentKey?.controlState == .connected) else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
let now = Date()
|
2018-09-09 12:55:14 +00:00
|
|
|
guard (now.timeIntervalSince(lastPing.inbound) <= CoreConfiguration.pingTimeout) else {
|
2018-08-23 08:19:25 +00:00
|
|
|
deferStop(.shutdown, SessionError.pingTimeout)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-09-08 18:29:51 +00:00
|
|
|
// postpone ping if elapsed less than keep-alive
|
|
|
|
if let interval = keepAliveInterval {
|
2018-09-09 12:55:14 +00:00
|
|
|
let elapsed = now.timeIntervalSince(lastPing.outbound)
|
2018-08-23 08:19:25 +00:00
|
|
|
guard (elapsed >= interval) else {
|
2018-09-08 18:29:51 +00:00
|
|
|
scheduleNextPing(elapsed: elapsed)
|
2018-08-23 08:19:25 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
log.debug("Send ping")
|
|
|
|
sendDataPackets([DataPacket.pingString])
|
2018-09-09 12:55:14 +00:00
|
|
|
lastPing.outbound = Date()
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2018-09-08 18:29:51 +00:00
|
|
|
scheduleNextPing()
|
|
|
|
}
|
|
|
|
|
|
|
|
private func scheduleNextPing(elapsed: TimeInterval = 0.0) {
|
|
|
|
guard let interval = keepAliveInterval else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
let remaining = min(interval, interval - elapsed)
|
|
|
|
queue.asyncAfter(deadline: .now() + remaining) { [weak self] in
|
|
|
|
self?.ping()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Handshake
|
|
|
|
|
|
|
|
// Ruby: reset_ctrl
|
2018-09-09 15:56:29 +00:00
|
|
|
private func resetControlChannel(forNewSession: Bool) {
|
2018-08-23 08:19:25 +00:00
|
|
|
authenticator = nil
|
2018-09-09 15:56:29 +00:00
|
|
|
do {
|
|
|
|
try controlChannel.reset(forNewSession: forNewSession)
|
|
|
|
} catch let e {
|
|
|
|
deferStop(.shutdown, e)
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: hard_reset
|
|
|
|
private func hardReset() {
|
|
|
|
log.debug("Send hard reset")
|
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
resetControlChannel(forNewSession: true)
|
2018-09-01 23:30:19 +00:00
|
|
|
pushReply = nil
|
2018-08-23 08:19:25 +00:00
|
|
|
negotiationKeyIdx = 0
|
|
|
|
let newKey = SessionKey(id: UInt8(negotiationKeyIdx))
|
|
|
|
keys[negotiationKeyIdx] = newKey
|
|
|
|
log.debug("Negotiation key index is \(negotiationKeyIdx)")
|
|
|
|
|
|
|
|
negotiationKey.state = .hardReset
|
2018-08-23 09:11:15 +00:00
|
|
|
enqueueControlPackets(code: .hardResetClientV2, key: UInt8(negotiationKeyIdx), payload: Data())
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: soft_reset
|
|
|
|
private func softReset() {
|
|
|
|
log.debug("Send soft reset")
|
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
resetControlChannel(forNewSession: false)
|
2018-08-23 08:19:25 +00:00
|
|
|
negotiationKeyIdx = max(1, (negotiationKeyIdx + 1) % ProtocolMacros.numberOfKeys)
|
|
|
|
let newKey = SessionKey(id: UInt8(negotiationKeyIdx))
|
|
|
|
keys[negotiationKeyIdx] = newKey
|
|
|
|
log.debug("Negotiation key index is \(negotiationKeyIdx)")
|
|
|
|
|
|
|
|
negotiationKey.state = .softReset
|
|
|
|
negotiationKey.softReset = true
|
|
|
|
loopNegotiation()
|
|
|
|
enqueueControlPackets(code: .softResetV1, key: UInt8(negotiationKeyIdx), payload: Data())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: on_tls_connect
|
|
|
|
private func onTLSConnect() {
|
|
|
|
log.debug("TLS.connect: Handshake is complete")
|
|
|
|
|
|
|
|
negotiationKey.controlState = .preAuth
|
|
|
|
|
|
|
|
do {
|
2018-09-01 23:30:19 +00:00
|
|
|
authenticator = try Authenticator(configuration.username, pushReply?.authToken ?? configuration.password)
|
2018-08-23 08:19:25 +00:00
|
|
|
try authenticator?.putAuth(into: negotiationKey.tls)
|
|
|
|
} catch let e {
|
|
|
|
deferStop(.shutdown, e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
guard let cipherTextOut = try? negotiationKey.tls.pullCipherText() else {
|
|
|
|
log.verbose("TLS.auth: Still can't pull ciphertext")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.debug("TLS.auth: Pulled ciphertext (\(cipherTextOut.count) bytes)")
|
|
|
|
enqueueControlPackets(code: .controlV1, key: negotiationKey.id, payload: cipherTextOut)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: push_request
|
|
|
|
private func pushRequest() {
|
|
|
|
guard (negotiationKey.controlState == .preIfConfig) else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !isReliableLink {
|
|
|
|
guard let targetDate = nextPushRequestDate, (Date() > targetDate) else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
log.debug("TLS.ifconfig: Put plaintext (PUSH_REQUEST)")
|
|
|
|
try? negotiationKey.tls.putPlainText("PUSH_REQUEST\0")
|
|
|
|
|
|
|
|
guard let cipherTextOut = try? negotiationKey.tls.pullCipherText() else {
|
|
|
|
log.verbose("TLS.ifconfig: Still can't pull ciphertext")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.debug("TLS.ifconfig: Send pulled ciphertext (\(cipherTextOut.count) bytes)")
|
|
|
|
enqueueControlPackets(code: .controlV1, key: negotiationKey.id, payload: cipherTextOut)
|
|
|
|
|
|
|
|
if negotiationKey.softReset {
|
2018-09-01 22:42:14 +00:00
|
|
|
completeConnection()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
nextPushRequestDate = Date().addingTimeInterval(CoreConfiguration.retransmissionLimit)
|
|
|
|
}
|
|
|
|
|
|
|
|
private func maybeRenegotiate() {
|
2018-09-06 23:23:51 +00:00
|
|
|
guard let renegotiatesAfter = configuration.renegotiatesAfter, renegotiatesAfter > 0 else {
|
2018-08-23 08:19:25 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
guard (negotiationKeyIdx == currentKeyIdx) else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
let elapsed = -negotiationKey.startTime.timeIntervalSinceNow
|
|
|
|
if (elapsed > renegotiatesAfter) {
|
|
|
|
log.debug("Renegotiating after \(elapsed) seconds")
|
|
|
|
softReset()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-01 22:42:14 +00:00
|
|
|
private func completeConnection() {
|
|
|
|
setupEncryption()
|
|
|
|
authenticator = nil
|
|
|
|
negotiationKey.controlState = .connected
|
|
|
|
connectedDate = Date()
|
|
|
|
transitionKeys()
|
|
|
|
}
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
// MARK: Control
|
|
|
|
|
|
|
|
// Ruby: handle_ctrl_pkt
|
2018-09-08 11:13:14 +00:00
|
|
|
private func handleControlPacket(_ packet: ControlPacket) {
|
2018-08-23 08:19:25 +00:00
|
|
|
guard (packet.key == negotiationKey.id) else {
|
|
|
|
log.error("Bad key in control packet (\(packet.key) != \(negotiationKey.id))")
|
|
|
|
// deferStop(.shutdown, SessionError.badKey)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if (((packet.code == .hardResetServerV2) && (negotiationKey.state == .hardReset)) ||
|
|
|
|
((packet.code == .softResetV1) && (negotiationKey.state == .softReset))) {
|
|
|
|
|
2018-09-09 09:40:58 +00:00
|
|
|
if negotiationKey.state == .hardReset {
|
2018-09-09 15:56:29 +00:00
|
|
|
controlChannel.remoteSessionId = packet.sessionId
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2018-09-09 15:56:29 +00:00
|
|
|
guard let remoteSessionId = controlChannel.remoteSessionId else {
|
2018-09-09 22:58:50 +00:00
|
|
|
log.error("No remote sessionId (never set)")
|
2018-08-23 08:19:25 +00:00
|
|
|
deferStop(.shutdown, SessionError.missingSessionId)
|
|
|
|
return
|
|
|
|
}
|
2018-09-09 09:40:58 +00:00
|
|
|
guard packet.sessionId == remoteSessionId else {
|
|
|
|
log.error("Packet session mismatch (\(packet.sessionId.toHex()) != \(remoteSessionId.toHex()))")
|
2018-08-23 08:19:25 +00:00
|
|
|
deferStop(.shutdown, SessionError.sessionMismatch)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
negotiationKey.state = .tls
|
|
|
|
|
|
|
|
log.debug("Start TLS handshake")
|
|
|
|
|
2018-08-23 15:24:39 +00:00
|
|
|
negotiationKey.tlsOptional = TLSBox(
|
|
|
|
caPath: configuration.caPath,
|
2018-08-23 15:42:30 +00:00
|
|
|
clientCertificatePath: configuration.clientCertificatePath,
|
|
|
|
clientKeyPath: configuration.clientKeyPath
|
2018-08-23 15:24:39 +00:00
|
|
|
)
|
2018-08-23 08:19:25 +00:00
|
|
|
do {
|
2018-08-23 09:32:38 +00:00
|
|
|
try negotiationKey.tls.start()
|
2018-08-23 08:19:25 +00:00
|
|
|
} catch let e {
|
|
|
|
deferStop(.shutdown, e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
guard let cipherTextOut = try? negotiationKey.tls.pullCipherText() else {
|
|
|
|
deferStop(.shutdown, SessionError.tlsError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.debug("TLS.connect: Pulled ciphertext (\(cipherTextOut.count) bytes)")
|
|
|
|
enqueueControlPackets(code: .controlV1, key: negotiationKey.id, payload: cipherTextOut)
|
|
|
|
}
|
|
|
|
else if ((packet.code == .controlV1) && (negotiationKey.state == .tls)) {
|
2018-09-09 15:56:29 +00:00
|
|
|
guard let remoteSessionId = controlChannel.remoteSessionId else {
|
2018-09-09 22:58:50 +00:00
|
|
|
log.error("No remote sessionId found in packet (control packets before server HARD_RESET)")
|
2018-08-23 08:19:25 +00:00
|
|
|
deferStop(.shutdown, SessionError.missingSessionId)
|
|
|
|
return
|
|
|
|
}
|
2018-09-09 09:40:58 +00:00
|
|
|
guard packet.sessionId == remoteSessionId else {
|
|
|
|
log.error("Packet session mismatch (\(packet.sessionId.toHex()) != \(remoteSessionId.toHex()))")
|
2018-08-23 08:19:25 +00:00
|
|
|
deferStop(.shutdown, SessionError.sessionMismatch)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
guard let cipherTextIn = packet.payload else {
|
|
|
|
log.warning("TLS.connect: Control packet with empty payload?")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.debug("TLS.connect: Put received ciphertext (\(cipherTextIn.count) bytes)")
|
|
|
|
try? negotiationKey.tls.putCipherText(cipherTextIn)
|
|
|
|
|
|
|
|
if let cipherTextOut = try? negotiationKey.tls.pullCipherText() {
|
|
|
|
log.debug("TLS.connect: Send pulled ciphertext (\(cipherTextOut.count) bytes)")
|
|
|
|
enqueueControlPackets(code: .controlV1, key: negotiationKey.id, payload: cipherTextOut)
|
|
|
|
}
|
|
|
|
|
|
|
|
if negotiationKey.shouldOnTLSConnect() {
|
|
|
|
onTLSConnect()
|
|
|
|
}
|
|
|
|
|
|
|
|
do {
|
2018-09-09 15:25:54 +00:00
|
|
|
let controlData = try controlChannel.currentControlData(withTLS: negotiationKey.tls)
|
2018-08-23 08:19:25 +00:00
|
|
|
handleControlData(controlData)
|
|
|
|
} catch _ {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: handle_ctrl_data
|
|
|
|
private func handleControlData(_ data: ZeroingData) {
|
2018-09-09 15:12:39 +00:00
|
|
|
guard let auth = authenticator else {
|
|
|
|
return
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
if CoreConfiguration.logsSensitiveData {
|
|
|
|
log.debug("Pulled plain control data (\(data.count) bytes): \(data.toHex())")
|
|
|
|
} else {
|
|
|
|
log.debug("Pulled plain control data (\(data.count) bytes)")
|
|
|
|
}
|
|
|
|
|
|
|
|
auth.appendControlData(data)
|
|
|
|
|
|
|
|
if (negotiationKey.controlState == .preAuth) {
|
|
|
|
do {
|
|
|
|
guard try auth.parseAuthReply() else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} catch let e {
|
|
|
|
deferStop(.shutdown, e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
negotiationKey.controlState = .preIfConfig
|
|
|
|
nextPushRequestDate = Date().addingTimeInterval(negotiationKey.softReset ? CoreConfiguration.softResetDelay : CoreConfiguration.retransmissionLimit)
|
|
|
|
pushRequest()
|
|
|
|
}
|
|
|
|
|
|
|
|
for message in auth.parseMessages() {
|
|
|
|
if CoreConfiguration.logsSensitiveData {
|
|
|
|
log.debug("Parsed control message (\(message.count) bytes): \"\(message)\"")
|
|
|
|
} else {
|
|
|
|
log.debug("Parsed control message (\(message.count) bytes)")
|
|
|
|
}
|
|
|
|
handleControlMessage(message)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: handle_ctrl_msg
|
|
|
|
private func handleControlMessage(_ message: String) {
|
|
|
|
guard !message.hasPrefix("AUTH_FAILED") else {
|
|
|
|
deferStop(.shutdown, SessionError.badCredentials)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
guard (negotiationKey.controlState == .preIfConfig) else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-09-02 10:33:47 +00:00
|
|
|
if CoreConfiguration.logsSensitiveData {
|
|
|
|
log.debug("Received control message: \"\(message)\"")
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
let reply: PushReply
|
|
|
|
do {
|
|
|
|
guard let optionalReply = try PushReply(message: message) else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
reply = optionalReply
|
2018-09-02 10:33:47 +00:00
|
|
|
log.debug("Received PUSH_REPLY: \"\(reply)\"")
|
2018-08-23 08:19:25 +00:00
|
|
|
} catch let e {
|
|
|
|
deferStop(.shutdown, e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-09-01 23:30:19 +00:00
|
|
|
pushReply = reply
|
2018-09-01 22:42:14 +00:00
|
|
|
completeConnection()
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
guard let remoteAddress = link?.remoteAddress else {
|
|
|
|
fatalError("Could not resolve link remote address")
|
|
|
|
}
|
2018-08-24 09:57:09 +00:00
|
|
|
delegate?.sessionDidStart(self, remoteAddress: remoteAddress, reply: reply)
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2018-09-08 18:29:51 +00:00
|
|
|
scheduleNextPing()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: transition_keys
|
|
|
|
private func transitionKeys() {
|
|
|
|
if let key = currentKey {
|
|
|
|
oldKeys.append(key)
|
|
|
|
}
|
|
|
|
currentKeyIdx = negotiationKeyIdx
|
|
|
|
cleanKeys()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: clean_keys
|
|
|
|
private func cleanKeys() {
|
|
|
|
while (oldKeys.count > 1) {
|
|
|
|
let key = oldKeys.removeFirst()
|
|
|
|
keys.removeValue(forKey: key.id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: q_ctrl
|
|
|
|
private func enqueueControlPackets(code: PacketCode, key: UInt8, payload: Data) {
|
|
|
|
guard let link = link else {
|
|
|
|
log.warning("Not writing to LINK, interface is down")
|
|
|
|
return
|
|
|
|
}
|
2018-09-09 15:31:11 +00:00
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
controlChannel.enqueueOutboundPackets(withCode: code, key: key, payload: payload, maxPacketSize: link.mtu)
|
2018-08-23 08:19:25 +00:00
|
|
|
flushControlQueue()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: flush_ctrl_q_out
|
|
|
|
private func flushControlQueue() {
|
2018-09-10 09:12:58 +00:00
|
|
|
let rawList: [Data]
|
|
|
|
do {
|
|
|
|
rawList = try controlChannel.writeOutboundPackets()
|
|
|
|
} catch let e {
|
|
|
|
log.warning("Failed control packet serialization: \(e)")
|
|
|
|
deferStop(.shutdown, e)
|
|
|
|
return
|
|
|
|
}
|
2018-09-09 15:31:11 +00:00
|
|
|
for raw in rawList {
|
2018-08-23 08:19:25 +00:00
|
|
|
log.debug("Send control packet (\(raw.count) bytes): \(raw.toHex())")
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// WARNING: runs in Network.framework queue
|
|
|
|
link?.writePackets(rawList) { [weak self] (error) in
|
|
|
|
if let error = error {
|
|
|
|
self?.queue.sync {
|
|
|
|
log.error("Failed LINK write during control flush: \(error)")
|
|
|
|
self?.deferStop(.reconnect, SessionError.failedLinkWrite)
|
|
|
|
return
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: setup_keys
|
2018-09-01 22:17:01 +00:00
|
|
|
private func setupEncryption() {
|
2018-08-23 08:19:25 +00:00
|
|
|
guard let auth = authenticator else {
|
2018-09-01 23:39:02 +00:00
|
|
|
fatalError("Setting up encryption without having authenticated")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2018-09-09 15:56:29 +00:00
|
|
|
guard let sessionId = controlChannel.sessionId else {
|
2018-09-01 23:39:02 +00:00
|
|
|
fatalError("Setting up encryption without a local sessionId")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2018-09-09 15:56:29 +00:00
|
|
|
guard let remoteSessionId = controlChannel.remoteSessionId else {
|
2018-09-01 23:39:02 +00:00
|
|
|
fatalError("Setting up encryption without a remote sessionId")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
guard let serverRandom1 = auth.serverRandom1, let serverRandom2 = auth.serverRandom2 else {
|
2018-09-01 23:39:02 +00:00
|
|
|
fatalError("Setting up encryption without server randoms")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2018-09-01 23:39:02 +00:00
|
|
|
guard let pushReply = pushReply else {
|
|
|
|
fatalError("Setting up encryption without a former PUSH_REPLY")
|
|
|
|
}
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
if CoreConfiguration.logsSensitiveData {
|
2018-09-01 23:39:02 +00:00
|
|
|
log.debug("Set up encryption from the following components:")
|
2018-08-23 08:19:25 +00:00
|
|
|
log.debug("\tpreMaster: \(auth.preMaster.toHex())")
|
|
|
|
log.debug("\trandom1: \(auth.random1.toHex())")
|
|
|
|
log.debug("\trandom2: \(auth.random2.toHex())")
|
|
|
|
log.debug("\tserverRandom1: \(serverRandom1.toHex())")
|
|
|
|
log.debug("\tserverRandom2: \(serverRandom2.toHex())")
|
|
|
|
log.debug("\tsessionId: \(sessionId.toHex())")
|
|
|
|
log.debug("\tremoteSessionId: \(remoteSessionId.toHex())")
|
|
|
|
} else {
|
2018-09-01 23:39:02 +00:00
|
|
|
log.debug("Set up encryption")
|
|
|
|
}
|
|
|
|
|
2018-09-07 13:11:44 +00:00
|
|
|
let pushedFraming = pushReply.compressionFraming
|
|
|
|
if let negFraming = pushedFraming {
|
2018-09-11 08:48:37 +00:00
|
|
|
log.info("Negotiated compression framing: \(negFraming.rawValue)")
|
2018-09-07 13:11:44 +00:00
|
|
|
}
|
2018-09-08 18:29:29 +00:00
|
|
|
if let negPing = pushReply.ping {
|
2018-09-11 08:48:37 +00:00
|
|
|
log.info("Negotiated keep-alive: \(negPing) seconds")
|
2018-09-08 18:29:29 +00:00
|
|
|
}
|
2018-09-01 23:39:02 +00:00
|
|
|
let pushedCipher = pushReply.cipher
|
|
|
|
if let negCipher = pushedCipher {
|
2018-09-11 08:48:37 +00:00
|
|
|
log.info("Negotiated cipher: \(negCipher.rawValue)")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
2018-08-23 13:49:21 +00:00
|
|
|
let bridge: EncryptionBridge
|
2018-08-23 08:19:25 +00:00
|
|
|
do {
|
2018-08-23 13:49:21 +00:00
|
|
|
bridge = try EncryptionBridge(
|
2018-09-01 23:39:02 +00:00
|
|
|
pushedCipher ?? configuration.cipher,
|
2018-08-23 13:44:31 +00:00
|
|
|
configuration.digest,
|
|
|
|
auth,
|
|
|
|
sessionId,
|
|
|
|
remoteSessionId
|
|
|
|
)
|
2018-08-23 08:19:25 +00:00
|
|
|
} catch let e {
|
|
|
|
deferStop(.shutdown, e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
negotiationKey.dataPath = DataPath(
|
2018-08-23 13:49:21 +00:00
|
|
|
encrypter: bridge.encrypter(),
|
|
|
|
decrypter: bridge.decrypter(),
|
2018-09-01 23:39:02 +00:00
|
|
|
peerId: pushReply.peerId ?? PacketPeerIdDisabled,
|
2018-09-07 13:11:44 +00:00
|
|
|
compressionFraming: (pushedFraming ?? configuration.compressionFraming).native,
|
2018-08-23 08:19:25 +00:00
|
|
|
maxPackets: link?.packetBufferSize ?? 200,
|
|
|
|
usesReplayProtection: CoreConfiguration.usesReplayProtection
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Data
|
|
|
|
|
|
|
|
// Ruby: handle_data_pkt
|
|
|
|
private func handleDataPackets(_ packets: [Data], key: SessionKey) {
|
2018-09-09 15:12:39 +00:00
|
|
|
controlChannel.addReceivedDataCount(packets.flatCount)
|
2018-08-23 08:19:25 +00:00
|
|
|
do {
|
|
|
|
guard let decryptedPackets = try key.decrypt(packets: packets) else {
|
|
|
|
log.warning("Could not decrypt packets, is SessionKey properly configured (dataPath, peerId)?")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
guard !decryptedPackets.isEmpty else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
tunnel?.writePackets(decryptedPackets, completionHandler: nil)
|
|
|
|
} catch let e {
|
2018-09-07 21:18:28 +00:00
|
|
|
guard !e.isTunnelError() else {
|
2018-08-23 08:19:25 +00:00
|
|
|
deferStop(.shutdown, e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
deferStop(.reconnect, e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: send_data_pkt
|
|
|
|
private func sendDataPackets(_ packets: [Data]) {
|
|
|
|
guard let key = currentKey else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
do {
|
|
|
|
guard let encryptedPackets = try key.encrypt(packets: packets) else {
|
|
|
|
log.warning("Could not encrypt packets, is SessionKey properly configured (dataPath, peerId)?")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
guard !encryptedPackets.isEmpty else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// WARNING: runs in Network.framework queue
|
2018-09-09 15:12:39 +00:00
|
|
|
controlChannel.addSentDataCount(encryptedPackets.flatCount)
|
2018-08-23 08:19:25 +00:00
|
|
|
link?.writePackets(encryptedPackets) { [weak self] (error) in
|
|
|
|
if let error = error {
|
|
|
|
self?.queue.sync {
|
|
|
|
log.error("Data: Failed LINK write during send data: \(error)")
|
|
|
|
self?.deferStop(.reconnect, SessionError.failedLinkWrite)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// log.verbose("Data: \(encryptedPackets.count) packets successfully written to LINK")
|
|
|
|
}
|
|
|
|
} catch let e {
|
2018-09-07 21:18:28 +00:00
|
|
|
guard !e.isTunnelError() else {
|
2018-08-23 08:19:25 +00:00
|
|
|
deferStop(.shutdown, e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
deferStop(.reconnect, e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Acks
|
|
|
|
|
2018-09-10 09:12:58 +00:00
|
|
|
private func handleAcks() {
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
// retry PUSH_REQUEST if ack queue is empty (all sent packets were ack'ed)
|
2018-09-09 15:12:39 +00:00
|
|
|
if isReliableLink && !controlChannel.hasPendingAcks() {
|
2018-08-23 08:19:25 +00:00
|
|
|
pushRequest()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ruby: send_ack
|
2018-09-10 09:12:58 +00:00
|
|
|
private func sendAck(for controlPacket: ControlPacket) {
|
|
|
|
log.debug("Send ack for received packetId \(controlPacket.packetId)")
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
let raw: Data
|
|
|
|
do {
|
2018-09-10 09:12:58 +00:00
|
|
|
raw = try controlChannel.writeAcks(
|
|
|
|
withKey: controlPacket.key,
|
|
|
|
ackPacketIds: [controlPacket.packetId],
|
|
|
|
ackRemoteSessionId: controlPacket.sessionId
|
|
|
|
)
|
2018-09-09 15:56:29 +00:00
|
|
|
} catch let e {
|
|
|
|
deferStop(.shutdown, e)
|
2018-09-09 09:40:58 +00:00
|
|
|
return
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
// WARNING: runs in Network.framework queue
|
|
|
|
link?.writePacket(raw) { [weak self] (error) in
|
|
|
|
if let error = error {
|
|
|
|
self?.queue.sync {
|
2018-09-10 09:12:58 +00:00
|
|
|
log.error("Failed LINK write during send ack for packetId \(controlPacket.packetId): \(error)")
|
2018-08-23 08:19:25 +00:00
|
|
|
self?.deferStop(.reconnect, SessionError.failedLinkWrite)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2018-09-10 09:12:58 +00:00
|
|
|
log.debug("Ack successfully written to LINK for packetId \(controlPacket.packetId)")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Stop
|
|
|
|
|
|
|
|
private func shouldHandlePackets() -> Bool {
|
|
|
|
return (!isStopping && !keys.isEmpty)
|
|
|
|
}
|
|
|
|
|
|
|
|
private func deferStop(_ method: StopMethod, _ error: Error?) {
|
|
|
|
isStopping = true
|
|
|
|
|
|
|
|
switch method {
|
|
|
|
case .shutdown:
|
|
|
|
doShutdown(error: error)
|
|
|
|
|
|
|
|
case .reconnect:
|
|
|
|
doReconnect(error: error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func doShutdown(error: Error?) {
|
|
|
|
if let error = error {
|
|
|
|
log.error("Trigger shutdown (error: \(error))")
|
|
|
|
} else {
|
|
|
|
log.info("Trigger shutdown on request")
|
|
|
|
}
|
|
|
|
stopError = error
|
|
|
|
delegate?.sessionDidStop(self, shouldReconnect: false)
|
|
|
|
}
|
|
|
|
|
|
|
|
private func doReconnect(error: Error?) {
|
|
|
|
if let error = error {
|
|
|
|
log.error("Trigger reconnection (error: \(error))")
|
|
|
|
} else {
|
|
|
|
log.info("Trigger reconnection on request")
|
|
|
|
}
|
|
|
|
stopError = error
|
|
|
|
delegate?.sessionDidStop(self, shouldReconnect: true)
|
|
|
|
}
|
|
|
|
}
|