2018-09-09 15:12:39 +00:00
|
|
|
//
|
|
|
|
// ControlChannel.swift
|
|
|
|
// TunnelKit
|
|
|
|
//
|
|
|
|
// Created by Davide De Rosa on 9/9/18.
|
2019-03-09 10:44:18 +00:00
|
|
|
// Copyright (c) 2019 Davide De Rosa. All rights reserved.
|
2018-09-09 15:12:39 +00:00
|
|
|
//
|
2019-05-14 08:58:47 +00:00
|
|
|
// https://github.com/passepartoutvpn
|
2018-09-09 15:12:39 +00:00
|
|
|
//
|
|
|
|
// 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/>.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import __TunnelKitNative
|
2018-09-09 15:31:11 +00:00
|
|
|
import SwiftyBeaver
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2018-09-09 15:31:11 +00:00
|
|
|
private let log = SwiftyBeaver.self
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2018-09-10 09:12:58 +00:00
|
|
|
class ControlChannelError: Error, CustomStringConvertible {
|
|
|
|
let description: String
|
|
|
|
|
|
|
|
init(_ message: String) {
|
|
|
|
description = "\(String(describing: ControlChannelError.self))(\(message))"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-09 15:12:39 +00:00
|
|
|
class ControlChannel {
|
2018-09-09 23:26:04 +00:00
|
|
|
private let serializer: ControlChannelSerializer
|
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
private(set) var sessionId: Data?
|
|
|
|
|
2018-09-09 22:58:50 +00:00
|
|
|
var remoteSessionId: Data? {
|
|
|
|
didSet {
|
|
|
|
if let id = remoteSessionId {
|
|
|
|
log.debug("Control: Remote sessionId is \(id.toHex())")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-09-09 15:56:29 +00:00
|
|
|
|
2018-09-09 15:31:11 +00:00
|
|
|
private var queue: BidirectionalState<[ControlPacket]>
|
2018-09-09 15:12:39 +00:00
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
private var currentPacketId: BidirectionalState<UInt32>
|
2018-09-09 15:12:39 +00:00
|
|
|
|
|
|
|
private var pendingAcks: Set<UInt32>
|
|
|
|
|
2018-09-09 15:25:54 +00:00
|
|
|
private var plainBuffer: ZeroingData
|
2018-09-09 15:12:39 +00:00
|
|
|
|
|
|
|
private var dataCount: BidirectionalState<Int>
|
2018-09-09 23:26:04 +00:00
|
|
|
|
|
|
|
convenience init() {
|
|
|
|
self.init(serializer: PlainSerializer())
|
|
|
|
}
|
|
|
|
|
2018-09-19 20:15:16 +00:00
|
|
|
convenience init(withAuthKey key: StaticKey, digest: SessionProxy.Digest) throws {
|
|
|
|
self.init(serializer: try AuthSerializer(withKey: key, digest: digest))
|
|
|
|
}
|
|
|
|
|
2018-10-19 14:52:37 +00:00
|
|
|
convenience init(withCryptKey key: StaticKey) throws {
|
|
|
|
self.init(serializer: try CryptSerializer(withKey: key))
|
|
|
|
}
|
|
|
|
|
2018-09-09 23:26:04 +00:00
|
|
|
private init(serializer: ControlChannelSerializer) {
|
|
|
|
self.serializer = serializer
|
2018-09-09 15:56:29 +00:00
|
|
|
sessionId = nil
|
|
|
|
remoteSessionId = nil
|
2018-09-09 15:12:39 +00:00
|
|
|
queue = BidirectionalState(withResetValue: [])
|
2018-09-09 15:56:29 +00:00
|
|
|
currentPacketId = BidirectionalState(withResetValue: 0)
|
2018-09-09 15:12:39 +00:00
|
|
|
pendingAcks = []
|
|
|
|
plainBuffer = Z(count: TLSBoxMaxBufferLength)
|
|
|
|
dataCount = BidirectionalState(withResetValue: 0)
|
|
|
|
}
|
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
func reset(forNewSession: Bool) throws {
|
|
|
|
if forNewSession {
|
|
|
|
try sessionId = SecureRandom.data(length: PacketSessionIdLength)
|
|
|
|
remoteSessionId = nil
|
|
|
|
}
|
|
|
|
queue.reset()
|
|
|
|
currentPacketId.reset()
|
|
|
|
pendingAcks.removeAll()
|
|
|
|
plainBuffer.zero()
|
|
|
|
dataCount.reset()
|
2018-09-10 09:12:58 +00:00
|
|
|
serializer.reset()
|
2018-09-09 15:56:29 +00:00
|
|
|
}
|
2018-09-10 09:12:58 +00:00
|
|
|
|
2018-09-18 16:04:43 +00:00
|
|
|
func readInboundPacket(withData data: Data, offset: Int) throws -> ControlPacket {
|
|
|
|
let packet = try serializer.deserialize(data: data, start: offset, end: nil)
|
2018-09-10 09:12:58 +00:00
|
|
|
log.debug("Control: Read packet \(packet)")
|
|
|
|
if let ackIds = packet.ackIds as? [UInt32], let ackRemoteSessionId = packet.ackRemoteSessionId {
|
|
|
|
try readAcks(ackIds, acksRemoteSessionId: ackRemoteSessionId)
|
|
|
|
}
|
|
|
|
return packet
|
|
|
|
}
|
|
|
|
|
|
|
|
func enqueueInboundPacket(packet: ControlPacket) -> [ControlPacket] {
|
2018-09-09 15:31:11 +00:00
|
|
|
queue.inbound.append(packet)
|
|
|
|
queue.inbound.sort { $0.packetId < $1.packetId }
|
|
|
|
|
|
|
|
var toHandle: [ControlPacket] = []
|
|
|
|
for queuedPacket in queue.inbound {
|
2018-09-09 15:56:29 +00:00
|
|
|
if queuedPacket.packetId < currentPacketId.inbound {
|
2018-09-09 15:31:11 +00:00
|
|
|
queue.inbound.removeFirst()
|
|
|
|
continue
|
|
|
|
}
|
2018-09-09 15:56:29 +00:00
|
|
|
if queuedPacket.packetId != currentPacketId.inbound {
|
2018-09-09 15:31:11 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
toHandle.append(queuedPacket)
|
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
currentPacketId.inbound += 1
|
2018-09-09 15:31:11 +00:00
|
|
|
queue.inbound.removeFirst()
|
|
|
|
}
|
|
|
|
return toHandle
|
2018-09-09 15:12:39 +00:00
|
|
|
}
|
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
func enqueueOutboundPackets(withCode code: PacketCode, key: UInt8, payload: Data, maxPacketSize: Int) {
|
|
|
|
guard let sessionId = sessionId else {
|
|
|
|
fatalError("Missing sessionId, do reset(forNewSession: true) first")
|
|
|
|
}
|
|
|
|
|
|
|
|
let oldIdOut = currentPacketId.outbound
|
2018-09-09 15:31:11 +00:00
|
|
|
var queuedCount = 0
|
|
|
|
var offset = 0
|
|
|
|
|
|
|
|
repeat {
|
|
|
|
let subPayloadLength = min(maxPacketSize, payload.count - offset)
|
|
|
|
let subPayloadData = payload.subdata(offset: offset, count: subPayloadLength)
|
2018-09-09 15:56:29 +00:00
|
|
|
let packet = ControlPacket(code: code, key: key, sessionId: sessionId, packetId: currentPacketId.outbound, payload: subPayloadData)
|
2018-09-09 15:31:11 +00:00
|
|
|
|
|
|
|
queue.outbound.append(packet)
|
2018-09-09 15:56:29 +00:00
|
|
|
currentPacketId.outbound += 1
|
2018-09-09 15:31:11 +00:00
|
|
|
offset += maxPacketSize
|
|
|
|
queuedCount += subPayloadLength
|
|
|
|
} while (offset < payload.count)
|
|
|
|
|
|
|
|
assert(queuedCount == payload.count)
|
|
|
|
|
|
|
|
// packet count
|
2018-09-09 15:56:29 +00:00
|
|
|
let packetCount = currentPacketId.outbound - oldIdOut
|
2018-09-09 15:31:11 +00:00
|
|
|
if (packetCount > 1) {
|
2018-09-09 22:58:50 +00:00
|
|
|
log.debug("Control: Enqueued \(packetCount) packets [\(oldIdOut)-\(currentPacketId.outbound - 1)]")
|
2018-09-09 15:31:11 +00:00
|
|
|
} else {
|
2018-09-09 22:58:50 +00:00
|
|
|
log.debug("Control: Enqueued 1 packet [\(oldIdOut)]")
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-10 09:12:58 +00:00
|
|
|
func writeOutboundPackets() throws -> [Data] {
|
2018-09-09 15:31:11 +00:00
|
|
|
var rawList: [Data] = []
|
|
|
|
for packet in queue.outbound {
|
|
|
|
if let sentDate = packet.sentDate {
|
|
|
|
let timeAgo = -sentDate.timeIntervalSinceNow
|
|
|
|
guard (timeAgo >= CoreConfiguration.retransmissionLimit) else {
|
2018-09-09 22:58:50 +00:00
|
|
|
log.debug("Control: Skip writing packet with packetId \(packet.packetId) (sent on \(sentDate), \(timeAgo) seconds ago)")
|
2018-09-09 15:31:11 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-10 09:12:58 +00:00
|
|
|
log.debug("Control: Write control packet \(packet)")
|
|
|
|
|
|
|
|
let raw = try serializer.serialize(packet: packet)
|
2018-09-09 15:31:11 +00:00
|
|
|
rawList.append(raw)
|
|
|
|
packet.sentDate = Date()
|
2018-09-09 15:56:29 +00:00
|
|
|
|
2018-09-09 15:31:11 +00:00
|
|
|
// track pending acks for sent packets
|
|
|
|
pendingAcks.insert(packet.packetId)
|
|
|
|
}
|
|
|
|
// log.verbose("Packets now pending ack: \(pendingAcks)")
|
|
|
|
return rawList
|
2018-09-09 15:12:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func hasPendingAcks() -> Bool {
|
|
|
|
return !pendingAcks.isEmpty
|
|
|
|
}
|
|
|
|
|
2018-09-10 09:12:58 +00:00
|
|
|
// Ruby: handle_acks
|
|
|
|
private func readAcks(_ packetIds: [UInt32], acksRemoteSessionId: Data) throws {
|
2018-09-09 15:56:29 +00:00
|
|
|
guard let sessionId = sessionId else {
|
|
|
|
throw SessionError.missingSessionId
|
|
|
|
}
|
|
|
|
guard acksRemoteSessionId == sessionId else {
|
2018-09-09 22:58:50 +00:00
|
|
|
log.error("Control: Ack session mismatch (\(acksRemoteSessionId.toHex()) != \(sessionId.toHex()))")
|
2018-09-09 15:56:29 +00:00
|
|
|
throw SessionError.sessionMismatch
|
|
|
|
}
|
2018-09-09 15:31:11 +00:00
|
|
|
|
|
|
|
// drop queued out packets if ack-ed
|
|
|
|
for (i, packet) in queue.outbound.enumerated() {
|
|
|
|
if packetIds.contains(packet.packetId) {
|
|
|
|
queue.outbound.remove(at: i)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// remove ack-ed packets from pending
|
|
|
|
pendingAcks.subtract(packetIds)
|
|
|
|
|
|
|
|
// log.verbose("Packets still pending ack: \(pendingAcks)")
|
|
|
|
}
|
|
|
|
|
2018-09-09 15:56:29 +00:00
|
|
|
func writeAcks(withKey key: UInt8, ackPacketIds: [UInt32], ackRemoteSessionId: Data) throws -> Data {
|
|
|
|
guard let sessionId = sessionId else {
|
|
|
|
throw SessionError.missingSessionId
|
|
|
|
}
|
2018-09-10 09:12:58 +00:00
|
|
|
let packet = ControlPacket(key: key, sessionId: sessionId, ackIds: ackPacketIds as [NSNumber], ackRemoteSessionId: ackRemoteSessionId)
|
|
|
|
log.debug("Control: Write ack packet \(packet)")
|
|
|
|
return try serializer.serialize(packet: packet)
|
2018-09-09 15:31:11 +00:00
|
|
|
}
|
|
|
|
|
2018-09-09 15:25:54 +00:00
|
|
|
func currentControlData(withTLS tls: TLSBox) throws -> ZeroingData {
|
|
|
|
var length = 0
|
|
|
|
try tls.pullRawPlainText(plainBuffer.mutableBytes, length: &length)
|
|
|
|
return plainBuffer.withOffset(0, count: length)
|
|
|
|
}
|
|
|
|
|
2018-09-09 15:12:39 +00:00
|
|
|
func addReceivedDataCount(_ count: Int) {
|
|
|
|
dataCount.inbound += count
|
|
|
|
}
|
|
|
|
|
|
|
|
func addSentDataCount(_ count: Int) {
|
|
|
|
dataCount.outbound += count
|
|
|
|
}
|
|
|
|
|
|
|
|
func currentDataCount() -> (Int, Int) {
|
|
|
|
return dataCount.pair
|
|
|
|
}
|
|
|
|
}
|