mirror of
https://github.com/leonboe1/QuickDrop.git
synced 2026-11-21 13:55:58 +00:00
Reformatting
This commit is contained in:
1 parent
05fa6043fe
commit
6c6c79cdad
5 files changed
+118
-146
No files matched your search
@@ -1,12 +1,12 @@
|
|||||||
//
|
//
|
||||||
// Data+URLSafeBase64.swift
|
// Data+Extensions.swift
|
||||||
// QuickDrop
|
// QuickDrop
|
||||||
//
|
//
|
||||||
// Created by Grishka on 08.04.2023.
|
// Created by Grishka on 08.04.2023.
|
||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import CoreFoundation
|
import CoreFoundation
|
||||||
|
import Foundation
|
||||||
|
|
||||||
extension Data {
|
extension Data {
|
||||||
func urlSafeBase64EncodedString() -> String {
|
func urlSafeBase64EncodedString() -> String {
|
||||||
@@ -24,7 +24,7 @@ extension Data{
|
|||||||
static func randomData(length: Int) -> Data {
|
static func randomData(length: Int) -> Data {
|
||||||
var data = Data(count: length)
|
var data = Data(count: length)
|
||||||
data.withUnsafeMutableBytes {
|
data.withUnsafeMutableBytes {
|
||||||
guard 0 == SecRandomCopyBytes(kSecRandomDefault, length, $0.baseAddress!) else { fatalError() }
|
guard SecRandomCopyBytes(kSecRandomDefault, length, $0.baseAddress!) == 0 else { fatalError() }
|
||||||
}
|
}
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,18 +5,17 @@
|
|||||||
// Created by Grishka on 08.04.2023.
|
// Created by Grishka on 08.04.2023.
|
||||||
//
|
//
|
||||||
|
|
||||||
|
import AppKit
|
||||||
|
import CommonCrypto
|
||||||
|
import CryptoKit
|
||||||
import Foundation
|
import Foundation
|
||||||
import Network
|
import Network
|
||||||
import CryptoKit
|
|
||||||
import CommonCrypto
|
|
||||||
import System
|
import System
|
||||||
import AppKit
|
|
||||||
|
|
||||||
import SwiftECC
|
|
||||||
import BigInt
|
import BigInt
|
||||||
|
import SwiftECC
|
||||||
|
|
||||||
class InboundNearbyConnection: NearbyConnection {
|
class InboundNearbyConnection: NearbyConnection {
|
||||||
|
|
||||||
private var currentState: State = .initial
|
private var currentState: State = .initial
|
||||||
public var delegate: InboundNearbyConnectionDelegate?
|
public var delegate: InboundNearbyConnectionDelegate?
|
||||||
private var cipherCommitment: Data?
|
private var cipherCommitment: Data?
|
||||||
@@ -32,7 +31,6 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
}
|
}
|
||||||
|
|
||||||
override func handleConnectionClosure() {
|
override func handleConnectionClosure() {
|
||||||
|
|
||||||
super.handleConnectionClosure()
|
super.handleConnectionClosure()
|
||||||
currentState = .disconnected
|
currentState = .disconnected
|
||||||
do {
|
do {
|
||||||
@@ -48,8 +46,7 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override internal func processReceivedFrame(frameData:Data){
|
override func processReceivedFrame(frameData: Data) {
|
||||||
|
|
||||||
if currentState != .receivingFiles {
|
if currentState != .receivingFiles {
|
||||||
log("Received frame in state \(currentState)...")
|
log("Received frame in state \(currentState)...")
|
||||||
}
|
}
|
||||||
@@ -70,13 +67,11 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
let frame = try Location_Nearby_Connections_OfflineFrame(serializedBytes: frameData)
|
let frame = try Location_Nearby_Connections_OfflineFrame(serializedBytes: frameData)
|
||||||
try processConnectionResponseFrame(frame)
|
try processConnectionResponseFrame(frame)
|
||||||
default:
|
default:
|
||||||
|
|
||||||
var smsg: Securemessage_SecureMessage
|
var smsg: Securemessage_SecureMessage
|
||||||
|
|
||||||
do {
|
do {
|
||||||
smsg = try Securemessage_SecureMessage(serializedBytes: frameData)
|
smsg = try Securemessage_SecureMessage(serializedBytes: frameData)
|
||||||
}
|
} catch {
|
||||||
catch {
|
|
||||||
log("Error deserializing secure message. Trying again....")
|
log("Error deserializing secure message. Trying again....")
|
||||||
|
|
||||||
// last 32 bytes = HMAC key
|
// last 32 bytes = HMAC key
|
||||||
@@ -110,11 +105,11 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
log("Received HMAC/Signature Key: \(recvHmacKey?.withUnsafeBytes { Data(Array($0)) }.map { String(format: "%02x", $0) }.joined() ?? "nil")")
|
log("Received HMAC/Signature Key: \(recvHmacKey?.withUnsafeBytes { Data(Array($0)) }.map { String(format: "%02x", $0) }.joined() ?? "nil")")
|
||||||
log("Sent HMAC/Signature Key: \(sendHmacKey?.withUnsafeBytes { Data(Array($0)) }.map { String(format: "%02x", $0) }.joined() ?? "nil")")
|
log("Sent HMAC/Signature Key: \(sendHmacKey?.withUnsafeBytes { Data(Array($0)) }.map { String(format: "%02x", $0) }.joined() ?? "nil")")
|
||||||
|
|
||||||
self.protocolError()
|
protocolError()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override internal func processTransferSetupFrame(_ frame:Sharing_Nearby_Frame) throws{
|
override func processTransferSetupFrame(_ frame: Sharing_Nearby_Frame) throws {
|
||||||
if frame.hasV1 && frame.v1.hasType, case .cancel = frame.v1.type {
|
if frame.hasV1 && frame.v1.hasType, case .cancel = frame.v1.type {
|
||||||
log("Transfer canceled")
|
log("Transfer canceled")
|
||||||
try sendDisconnectionAndDisconnect()
|
try sendDisconnectionAndDisconnect()
|
||||||
@@ -190,7 +185,7 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
let deviceNameLength = Int(endpointInfo[17])
|
let deviceNameLength = Int(endpointInfo[17])
|
||||||
guard endpointInfo.count >= deviceNameLength + 18 else { throw NearbyError.protocolError("Endpoint info too short to contain the device name") }
|
guard endpointInfo.count >= deviceNameLength + 18 else { throw NearbyError.protocolError("Endpoint info too short to contain the device name") }
|
||||||
guard let deviceName = String(data: endpointInfo[18 ..< (18 + deviceNameLength)], encoding: .utf8) else { throw NearbyError.protocolError("Device name is not valid UTF-8") }
|
guard let deviceName = String(data: endpointInfo[18 ..< (18 + deviceNameLength)], encoding: .utf8) else { throw NearbyError.protocolError("Device name is not valid UTF-8") }
|
||||||
let rawDeviceType:Int=Int(endpointInfo[0] & 7) >> 1
|
let rawDeviceType = Int(endpointInfo[0] & 7) >> 1
|
||||||
remoteDeviceInfo = RemoteDeviceInfo(name: deviceName, type: RemoteDeviceInfo.DeviceType.fromRawValue(value: rawDeviceType))
|
remoteDeviceInfo = RemoteDeviceInfo(name: deviceName, type: RemoteDeviceInfo.DeviceType.fromRawValue(value: rawDeviceType))
|
||||||
currentState = .receivedConnectionRequest
|
currentState = .receivedConnectionRequest
|
||||||
}
|
}
|
||||||
@@ -288,7 +283,7 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
resp.v1.connectionResponse.status = 0
|
resp.v1.connectionResponse.status = 0
|
||||||
resp.v1.connectionResponse.osInfo = Location_Nearby_Connections_OsInfo()
|
resp.v1.connectionResponse.osInfo = Location_Nearby_Connections_OsInfo()
|
||||||
resp.v1.connectionResponse.osInfo.type = .apple
|
resp.v1.connectionResponse.osInfo.type = .apple
|
||||||
sendFrameAsync(try resp.serializedData())
|
try sendFrameAsync(resp.serializedData())
|
||||||
|
|
||||||
encryptionDone = true
|
encryptionDone = true
|
||||||
|
|
||||||
@@ -348,18 +343,16 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
currentState = .waitingForUserConsent
|
currentState = .waitingForUserConsent
|
||||||
|
|
||||||
if frame.v1.introduction.fileMetadata.count > 0 && frame.v1.introduction.textMetadata.isEmpty {
|
if frame.v1.introduction.fileMetadata.count > 0 && frame.v1.introduction.textMetadata.isEmpty {
|
||||||
|
|
||||||
let saveDirectory = SaveFilesManager.shared.getSaveDirectory()
|
let saveDirectory = SaveFilesManager.shared.getSaveDirectory()
|
||||||
|
|
||||||
for file in frame.v1.introduction.fileMetadata {
|
for file in frame.v1.introduction.fileMetadata {
|
||||||
|
|
||||||
let dest = makeFileDestinationURL(saveDirectory.appendingPathComponent(file.name))
|
let dest = makeFileDestinationURL(saveDirectory.appendingPathComponent(file.name))
|
||||||
let info = InternalFileInfo(meta: FileMetadata(name: file.name, size: file.size, mimeType: file.mimeType),
|
let info = InternalFileInfo(meta: FileMetadata(name: file.name, size: file.size, mimeType: file.mimeType),
|
||||||
payloadID: file.payloadID,
|
payloadID: file.payloadID,
|
||||||
destinationURL: dest)
|
destinationURL: dest)
|
||||||
transferredFiles[file.payloadID] = info
|
transferredFiles[file.payloadID] = info
|
||||||
}
|
}
|
||||||
let metadata=TransferMetadata(files: transferredFiles.map({$0.value.meta}), id: id, pinCode: pinCode)
|
let metadata = TransferMetadata(files: transferredFiles.map { $0.value.meta }, id: id, pinCode: pinCode)
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.delegate?.obtainUserConsent(for: metadata, from: self.remoteDeviceInfo!, connection: self)
|
self.delegate?.obtainUserConsent(for: metadata, from: self.remoteDeviceInfo!, connection: self)
|
||||||
}
|
}
|
||||||
@@ -372,7 +365,6 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
self.delegate?.obtainUserConsent(for: metadata, from: self.remoteDeviceInfo!, connection: self)
|
self.delegate?.obtainUserConsent(for: metadata, from: self.remoteDeviceInfo!, connection: self)
|
||||||
}
|
}
|
||||||
} else if case .text = meta.type {
|
} else if case .text = meta.type {
|
||||||
|
|
||||||
let saveDirectory = SaveFilesManager.shared.getSaveDirectory()
|
let saveDirectory = SaveFilesManager.shared.getSaveDirectory()
|
||||||
|
|
||||||
let dateFormatter = DateFormatter()
|
let dateFormatter = DateFormatter()
|
||||||
@@ -404,7 +396,6 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func acceptTransfer(storeInTemp: Bool) {
|
private func acceptTransfer(storeInTemp: Bool) {
|
||||||
|
|
||||||
if currentState == .disconnected {
|
if currentState == .disconnected {
|
||||||
log("Detected timeout, not accepting transfer")
|
log("Detected timeout, not accepting transfer")
|
||||||
return
|
return
|
||||||
@@ -444,7 +435,6 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private func rejectTransfer(with reason: Sharing_Nearby_ConnectionResponseFrame.Status = .reject) {
|
private func rejectTransfer(with reason: Sharing_Nearby_ConnectionResponseFrame.Status = .reject) {
|
||||||
var frame = Sharing_Nearby_Frame()
|
var frame = Sharing_Nearby_Frame()
|
||||||
frame.version = .v1
|
frame.version = .v1
|
||||||
@@ -459,7 +449,6 @@ class InboundNearbyConnection: NearbyConnection{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private func deletePartiallyReceivedFiles() throws {
|
private func deletePartiallyReceivedFiles() throws {
|
||||||
for (_, file) in transferredFiles {
|
for (_, file) in transferredFiles {
|
||||||
guard file.created else { continue }
|
guard file.created else { continue }
|
||||||
@@ -473,26 +462,21 @@ protocol InboundNearbyConnectionDelegate{
|
|||||||
func connectionWasTerminated(connection: InboundNearbyConnection, error: Error?)
|
func connectionWasTerminated(connection: InboundNearbyConnection, error: Error?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public class SaveFilesManager {
|
public class SaveFilesManager {
|
||||||
|
|
||||||
private init() {}
|
private init() {}
|
||||||
|
|
||||||
public static let shared = SaveFilesManager()
|
public static let shared = SaveFilesManager()
|
||||||
|
|
||||||
internal let tempDirectory: URL = FileManager.default.temporaryDirectory.appendingPathComponent("Pending")
|
let tempDirectory: URL = FileManager.default.temporaryDirectory.appendingPathComponent("Pending")
|
||||||
private var securityScopeUrl: URL?
|
private var securityScopeUrl: URL?
|
||||||
|
|
||||||
private var filesFinishedDownloading = [URL]()
|
private var filesFinishedDownloading = [URL]()
|
||||||
|
|
||||||
|
|
||||||
public func registerFileFinishedDownloading(_ fileURL: URL) {
|
public func registerFileFinishedDownloading(_ fileURL: URL) {
|
||||||
filesFinishedDownloading.append(fileURL)
|
filesFinishedDownloading.append(fileURL)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public func movePendingFilesToTarget() {
|
public func movePendingFilesToTarget() {
|
||||||
|
|
||||||
if !isPlusVersion() {
|
if !isPlusVersion() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -506,7 +490,6 @@ public class SaveFilesManager {
|
|||||||
let target = getSaveDirectory()
|
let target = getSaveDirectory()
|
||||||
|
|
||||||
for file in files {
|
for file in files {
|
||||||
|
|
||||||
let fileName = file.lastPathComponent
|
let fileName = file.lastPathComponent
|
||||||
let destinationURL = target.appendingPathComponent(fileName)
|
let destinationURL = target.appendingPathComponent(fileName)
|
||||||
|
|
||||||
@@ -542,7 +525,6 @@ public class SaveFilesManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public func stopAccessingSecurityScopedResource() {
|
public func stopAccessingSecurityScopedResource() {
|
||||||
guard let url = securityScopeUrl else {
|
guard let url = securityScopeUrl else {
|
||||||
return
|
return
|
||||||
@@ -550,19 +532,16 @@ public class SaveFilesManager {
|
|||||||
|
|
||||||
log("Stopping access to security scoped resource: \(url)")
|
log("Stopping access to security scoped resource: \(url)")
|
||||||
url.stopAccessingSecurityScopedResource()
|
url.stopAccessingSecurityScopedResource()
|
||||||
self.securityScopeUrl = nil
|
securityScopeUrl = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public func getSaveDirectory() -> URL {
|
public func getSaveDirectory() -> URL {
|
||||||
|
|
||||||
if let securityScopeUrl = securityScopeUrl {
|
if let securityScopeUrl = securityScopeUrl {
|
||||||
log("Using existing security scope URL: \(securityScopeUrl)")
|
log("Using existing security scope URL: \(securityScopeUrl)")
|
||||||
return securityScopeUrl
|
return securityScopeUrl
|
||||||
}
|
}
|
||||||
|
|
||||||
if let bookmarkData = UserDefaults.standard.data(forKey: UserDefaultsKeys.saveFolderBookmark.rawValue) {
|
if let bookmarkData = UserDefaults.standard.data(forKey: UserDefaultsKeys.saveFolderBookmark.rawValue) {
|
||||||
|
|
||||||
var isStale = false
|
var isStale = false
|
||||||
|
|
||||||
do {
|
do {
|
||||||
@@ -570,10 +549,9 @@ public class SaveFilesManager {
|
|||||||
|
|
||||||
if !isStale {
|
if !isStale {
|
||||||
if url.startAccessingSecurityScopedResource() {
|
if url.startAccessingSecurityScopedResource() {
|
||||||
|
|
||||||
log("Successfully accessed security scoped resource: \(url)")
|
log("Successfully accessed security scoped resource: \(url)")
|
||||||
|
|
||||||
self.securityScopeUrl = url
|
securityScopeUrl = url
|
||||||
return url
|
return url
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -606,7 +584,8 @@ extension String {
|
|||||||
while index < endIndex {
|
while index < endIndex {
|
||||||
let nextIndex = self.index(index, offsetBy: 2)
|
let nextIndex = self.index(index, offsetBy: 2)
|
||||||
if nextIndex <= endIndex,
|
if nextIndex <= endIndex,
|
||||||
let byte = UInt8(self[index..<nextIndex], radix: 16) {
|
let byte = UInt8(self[index ..< nextIndex], radix: 16)
|
||||||
|
{
|
||||||
data.append(byte)
|
data.append(byte)
|
||||||
} else {
|
} else {
|
||||||
break // or handle invalid hex gracefully
|
break // or handle invalid hex gracefully
|
||||||
|
|||||||
@@ -5,39 +5,39 @@
|
|||||||
// Created by Grishka on 09.04.2023.
|
// Created by Grishka on 09.04.2023.
|
||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import Network
|
|
||||||
import CommonCrypto
|
import CommonCrypto
|
||||||
import CryptoKit
|
import CryptoKit
|
||||||
|
import Foundation
|
||||||
|
import Network
|
||||||
import System
|
import System
|
||||||
|
|
||||||
import SwiftECC
|
|
||||||
import BigInt
|
import BigInt
|
||||||
|
import SwiftECC
|
||||||
|
|
||||||
class NearbyConnection {
|
class NearbyConnection {
|
||||||
internal static let SANE_FRAME_LENGTH=5*1024*1024
|
static let SANE_FRAME_LENGTH = 5 * 1024 * 1024
|
||||||
private static let dispatchQueue = DispatchQueue(label: "com.leonboettger.quickdrop.queue", qos: .utility) // FIFO (non-concurrent) queue to avoid those exciting concurrency bugs
|
private static let dispatchQueue = DispatchQueue(label: "com.leonboettger.quickdrop.queue", qos: .utility) // FIFO (non-concurrent) queue to avoid those exciting concurrency bugs
|
||||||
|
|
||||||
internal let connection:NWConnection
|
let connection: NWConnection
|
||||||
internal var remoteDeviceInfo:RemoteDeviceInfo?
|
var remoteDeviceInfo: RemoteDeviceInfo?
|
||||||
private var payloadBuffers: [Int64: NSMutableData] = [:]
|
private var payloadBuffers: [Int64: NSMutableData] = [:]
|
||||||
internal var encryptionDone:Bool=false
|
var encryptionDone: Bool = false
|
||||||
internal var transferredFiles:[Int64:InternalFileInfo]=[:]
|
var transferredFiles: [Int64: InternalFileInfo] = [:]
|
||||||
public let id: String
|
public let id: String
|
||||||
internal var lastError:Error?
|
var lastError: Error?
|
||||||
private var connectionClosed: Bool = false
|
private var connectionClosed: Bool = false
|
||||||
|
|
||||||
// UKEY2-related state
|
// UKEY2-related state
|
||||||
internal var publicKey:ECPublicKey?
|
var publicKey: ECPublicKey?
|
||||||
internal var privateKey:ECPrivateKey?
|
var privateKey: ECPrivateKey?
|
||||||
internal var ukeyClientInitMsgData:Data?
|
var ukeyClientInitMsgData: Data?
|
||||||
internal var ukeyServerInitMsgData:Data?
|
var ukeyServerInitMsgData: Data?
|
||||||
|
|
||||||
// SecureMessage encryption keys
|
// SecureMessage encryption keys
|
||||||
internal var decryptKey:[UInt8]?
|
var decryptKey: [UInt8]?
|
||||||
internal var encryptKey:[UInt8]?
|
var encryptKey: [UInt8]?
|
||||||
internal var recvHmacKey:SymmetricKey?
|
var recvHmacKey: SymmetricKey?
|
||||||
internal var sendHmacKey:SymmetricKey?
|
var sendHmacKey: SymmetricKey?
|
||||||
|
|
||||||
// SecureMessage sequence numbers
|
// SecureMessage sequence numbers
|
||||||
private var serverSeq: Int32 = 0
|
private var serverSeq: Int32 = 0
|
||||||
@@ -55,7 +55,7 @@ class NearbyConnection{
|
|||||||
if case .ready = state {
|
if case .ready = state {
|
||||||
self.connectionReady()
|
self.connectionReady()
|
||||||
self.receiveFrameAsync()
|
self.receiveFrameAsync()
|
||||||
} else if case .failed(let err) = state {
|
} else if case let .failed(err) = state {
|
||||||
self.lastError = err
|
self.lastError = err
|
||||||
log("Error opening socket: \(err)")
|
log("Error opening socket: \(err)")
|
||||||
self.handleConnectionClosure()
|
self.handleConnectionClosure()
|
||||||
@@ -67,36 +67,36 @@ class NearbyConnection{
|
|||||||
|
|
||||||
func connectionReady() {}
|
func connectionReady() {}
|
||||||
|
|
||||||
internal func handleConnectionClosure(){
|
func handleConnectionClosure() {
|
||||||
log("Connection closed")
|
log("Connection closed")
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func protocolError(){
|
func protocolError() {
|
||||||
disconnect()
|
disconnect()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func processReceivedFrame(frameData:Data){
|
func processReceivedFrame(frameData _: Data) {
|
||||||
fatalError()
|
fatalError()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func processTransferSetupFrame(_ frame:Sharing_Nearby_Frame) throws{
|
func processTransferSetupFrame(_: Sharing_Nearby_Frame) throws {
|
||||||
fatalError()
|
fatalError()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func isServer() -> Bool{
|
func isServer() -> Bool {
|
||||||
fatalError()
|
fatalError()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func processFileChunk(frame:Location_Nearby_Connections_PayloadTransferFrame) throws{
|
func processFileChunk(frame _: Location_Nearby_Connections_PayloadTransferFrame) throws {
|
||||||
protocolError()
|
protocolError()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func processBytesPayload(payload:Data, id:Int64)throws ->Bool{
|
func processBytesPayload(payload _: Data, id _: Int64) throws -> Bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
private func receiveFrameAsync() {
|
private func receiveFrameAsync() {
|
||||||
connection.receive(minimumIncompleteLength: 4, maximumLength: 4) { content, contentContext, isComplete, error in
|
connection.receive(minimumIncompleteLength: 4, maximumLength: 4) { content, _, isComplete, error in
|
||||||
if self.connectionClosed {
|
if self.connectionClosed {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -113,7 +113,7 @@ class NearbyConnection{
|
|||||||
assertionFailure()
|
assertionFailure()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
let frameLength:UInt32=UInt32(content[0]) << 24 | UInt32(content[1]) << 16 | UInt32(content[2]) << 8 | UInt32(content[3])
|
let frameLength = UInt32(content[0]) << 24 | UInt32(content[1]) << 16 | UInt32(content[2]) << 8 | UInt32(content[3])
|
||||||
guard frameLength < NearbyConnection.SANE_FRAME_LENGTH else {
|
guard frameLength < NearbyConnection.SANE_FRAME_LENGTH else {
|
||||||
self.lastError = NearbyError.protocolError("Unexpected packet length")
|
self.lastError = NearbyError.protocolError("Unexpected packet length")
|
||||||
self.protocolError()
|
self.protocolError()
|
||||||
@@ -124,7 +124,7 @@ class NearbyConnection{
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func receiveFrameAsync(length: UInt32) {
|
private func receiveFrameAsync(length: UInt32) {
|
||||||
connection.receive(minimumIncompleteLength: Int(length), maximumLength: Int(length)) { content, contentContext, isComplete, error in
|
connection.receive(minimumIncompleteLength: Int(length), maximumLength: Int(length)) { content, _, isComplete, _ in
|
||||||
if self.connectionClosed {
|
if self.connectionClosed {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -141,7 +141,7 @@ class NearbyConnection{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func sendFrameAsync(_ frame:Data, completion:(()->Void)?=nil){
|
func sendFrameAsync(_ frame: Data, completion: (() -> Void)? = nil) {
|
||||||
if connectionClosed {
|
if connectionClosed {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -151,27 +151,27 @@ class NearbyConnection{
|
|||||||
UInt8(truncatingIfNeeded: length >> 24),
|
UInt8(truncatingIfNeeded: length >> 24),
|
||||||
UInt8(truncatingIfNeeded: length >> 16),
|
UInt8(truncatingIfNeeded: length >> 16),
|
||||||
UInt8(truncatingIfNeeded: length >> 8),
|
UInt8(truncatingIfNeeded: length >> 8),
|
||||||
UInt8(truncatingIfNeeded: length)
|
UInt8(truncatingIfNeeded: length),
|
||||||
])
|
])
|
||||||
lengthPrefixedData.append(frame)
|
lengthPrefixedData.append(frame)
|
||||||
connection.send(content: lengthPrefixedData, completion: .contentProcessed({ error in
|
connection.send(content: lengthPrefixedData, completion: .contentProcessed { _ in
|
||||||
if let completion = completion {
|
if let completion = completion {
|
||||||
completion()
|
completion()
|
||||||
}
|
}
|
||||||
}))
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func encryptAndSendOfflineFrame(_ frame:Location_Nearby_Connections_OfflineFrame, completion:(()->Void)?=nil) throws{
|
func encryptAndSendOfflineFrame(_ frame: Location_Nearby_Connections_OfflineFrame, completion: (() -> Void)? = nil) throws {
|
||||||
var d2dMsg = Securegcm_DeviceToDeviceMessage()
|
var d2dMsg = Securegcm_DeviceToDeviceMessage()
|
||||||
serverSeq += 1
|
serverSeq += 1
|
||||||
d2dMsg.sequenceNumber = serverSeq
|
d2dMsg.sequenceNumber = serverSeq
|
||||||
d2dMsg.message = try frame.serializedData()
|
d2dMsg.message = try frame.serializedData()
|
||||||
|
|
||||||
let serializedMsg=[UInt8](try d2dMsg.serializedData())
|
let serializedMsg = try [UInt8](d2dMsg.serializedData())
|
||||||
let iv = Data.randomData(length: 16)
|
let iv = Data.randomData(length: 16)
|
||||||
var encryptedData = Data(count: serializedMsg.count + 16)
|
var encryptedData = Data(count: serializedMsg.count + 16)
|
||||||
var encryptedLength: size_t = 0
|
var encryptedLength: size_t = 0
|
||||||
encryptedData.withUnsafeMutableBytes({
|
encryptedData.withUnsafeMutableBytes {
|
||||||
let status = CCCrypt(
|
let status = CCCrypt(
|
||||||
CCOperation(kCCEncrypt),
|
CCOperation(kCCEncrypt),
|
||||||
CCAlgorithm(kCCAlgorithmAES128),
|
CCAlgorithm(kCCAlgorithmAES128),
|
||||||
@@ -183,7 +183,7 @@ class NearbyConnection{
|
|||||||
&encryptedLength
|
&encryptedLength
|
||||||
)
|
)
|
||||||
guard status == kCCSuccess else { fatalError("CCCrypt error: \(status)") }
|
guard status == kCCSuccess else { fatalError("CCCrypt error: \(status)") }
|
||||||
})
|
}
|
||||||
|
|
||||||
var hb = Securemessage_HeaderAndBody()
|
var hb = Securemessage_HeaderAndBody()
|
||||||
hb.body = encryptedData.prefix(encryptedLength)
|
hb.body = encryptedData.prefix(encryptedLength)
|
||||||
@@ -199,14 +199,14 @@ class NearbyConnection{
|
|||||||
var smsg = Securemessage_SecureMessage()
|
var smsg = Securemessage_SecureMessage()
|
||||||
smsg.headerAndBody = try hb.serializedData()
|
smsg.headerAndBody = try hb.serializedData()
|
||||||
smsg.signature = Data(HMAC<SHA256>.authenticationCode(for: smsg.headerAndBody, using: sendHmacKey!))
|
smsg.signature = Data(HMAC<SHA256>.authenticationCode(for: smsg.headerAndBody, using: sendHmacKey!))
|
||||||
sendFrameAsync(try smsg.serializedData(), completion: completion)
|
try sendFrameAsync(smsg.serializedData(), completion: completion)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func sendTransferSetupFrame(_ frame:Sharing_Nearby_Frame) throws{
|
func sendTransferSetupFrame(_ frame: Sharing_Nearby_Frame) throws {
|
||||||
try sendBytesPayload(data: try frame.serializedData(), id: Int64.random(in: Int64.min...Int64.max))
|
try sendBytesPayload(data: frame.serializedData(), id: Int64.random(in: Int64.min ... Int64.max))
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func sendBytesPayload(data:Data, id:Int64) throws{
|
func sendBytesPayload(data: Data, id: Int64) throws {
|
||||||
var transfer = Location_Nearby_Connections_PayloadTransferFrame()
|
var transfer = Location_Nearby_Connections_PayloadTransferFrame()
|
||||||
transfer.packetType = .data
|
transfer.packetType = .data
|
||||||
transfer.payloadChunk.offset = 0
|
transfer.payloadChunk.offset = 0
|
||||||
@@ -231,7 +231,7 @@ class NearbyConnection{
|
|||||||
try encryptAndSendOfflineFrame(wrapper)
|
try encryptAndSendOfflineFrame(wrapper)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func decryptAndProcessReceivedSecureMessage(_ smsg:Securemessage_SecureMessage) throws{
|
func decryptAndProcessReceivedSecureMessage(_ smsg: Securemessage_SecureMessage) throws {
|
||||||
guard smsg.hasSignature, smsg.hasHeaderAndBody else { throw NearbyError.requiredFieldMissing("secureMessage.signature|headerAndBody") }
|
guard smsg.hasSignature, smsg.hasHeaderAndBody else { throw NearbyError.requiredFieldMissing("secureMessage.signature|headerAndBody") }
|
||||||
|
|
||||||
if NearbyConnectionManager.shared.checkSignature {
|
if NearbyConnectionManager.shared.checkSignature {
|
||||||
@@ -242,8 +242,8 @@ class NearbyConnection{
|
|||||||
let headerAndBody = try Securemessage_HeaderAndBody(serializedBytes: smsg.headerAndBody)
|
let headerAndBody = try Securemessage_HeaderAndBody(serializedBytes: smsg.headerAndBody)
|
||||||
var decryptedData = Data(count: headerAndBody.body.count)
|
var decryptedData = Data(count: headerAndBody.body.count)
|
||||||
|
|
||||||
var decryptedLength:Int=0
|
var decryptedLength = 0
|
||||||
decryptedData.withUnsafeMutableBytes({
|
decryptedData.withUnsafeMutableBytes {
|
||||||
let status = CCCrypt(
|
let status = CCCrypt(
|
||||||
CCOperation(kCCDecrypt),
|
CCOperation(kCCDecrypt),
|
||||||
CCAlgorithm(kCCAlgorithmAES128),
|
CCAlgorithm(kCCAlgorithmAES128),
|
||||||
@@ -255,7 +255,7 @@ class NearbyConnection{
|
|||||||
&decryptedLength
|
&decryptedLength
|
||||||
)
|
)
|
||||||
guard status == kCCSuccess else { fatalError("CCCrypt error: \(status)") }
|
guard status == kCCSuccess else { fatalError("CCCrypt error: \(status)") }
|
||||||
})
|
}
|
||||||
decryptedData = decryptedData.prefix(decryptedLength)
|
decryptedData = decryptedData.prefix(decryptedLength)
|
||||||
let d2dMsg = try Securegcm_DeviceToDeviceMessage(serializedBytes: decryptedData)
|
let d2dMsg = try Securegcm_DeviceToDeviceMessage(serializedBytes: decryptedData)
|
||||||
guard d2dMsg.hasMessage, d2dMsg.hasSequenceNumber else { throw NearbyError.requiredFieldMissing("d2dMessage.message|sequenceNumber") }
|
guard d2dMsg.hasMessage, d2dMsg.hasSequenceNumber else { throw NearbyError.requiredFieldMissing("d2dMessage.message|sequenceNumber") }
|
||||||
@@ -263,11 +263,11 @@ class NearbyConnection{
|
|||||||
guard d2dMsg.sequenceNumber == clientSeq else { throw NearbyError.protocolError("Wrong sequence number. Expected \(clientSeq), got \(d2dMsg.sequenceNumber)") }
|
guard d2dMsg.sequenceNumber == clientSeq else { throw NearbyError.protocolError("Wrong sequence number. Expected \(clientSeq), got \(d2dMsg.sequenceNumber)") }
|
||||||
let offlineFrame = try Location_Nearby_Connections_OfflineFrame(serializedBytes: d2dMsg.message)
|
let offlineFrame = try Location_Nearby_Connections_OfflineFrame(serializedBytes: d2dMsg.message)
|
||||||
|
|
||||||
if offlineFrame.hasV1 && offlineFrame.v1.hasType, case .payloadTransfer = offlineFrame.v1.type {
|
if offlineFrame.hasV1, offlineFrame.v1.hasType, case .payloadTransfer = offlineFrame.v1.type {
|
||||||
guard offlineFrame.v1.hasPayloadTransfer else { throw NearbyError.requiredFieldMissing("offlineFrame.v1.payloadTransfer") }
|
guard offlineFrame.v1.hasPayloadTransfer else { throw NearbyError.requiredFieldMissing("offlineFrame.v1.payloadTransfer") }
|
||||||
let payloadTransfer = offlineFrame.v1.payloadTransfer
|
let payloadTransfer = offlineFrame.v1.payloadTransfer
|
||||||
let header=payloadTransfer.payloadHeader;
|
let header = payloadTransfer.payloadHeader
|
||||||
let chunk=payloadTransfer.payloadChunk;
|
let chunk = payloadTransfer.payloadChunk
|
||||||
guard header.hasType, header.hasID else { throw NearbyError.requiredFieldMissing("payloadHeader.type|id") }
|
guard header.hasType, header.hasID else { throw NearbyError.requiredFieldMissing("payloadHeader.type|id") }
|
||||||
guard payloadTransfer.hasPayloadChunk, chunk.hasOffset, chunk.hasFlags else { throw NearbyError.requiredFieldMissing("payloadTransfer.payloadChunk|offset|flags") }
|
guard payloadTransfer.hasPayloadChunk, chunk.hasOffset, chunk.hasFlags else { throw NearbyError.requiredFieldMissing("payloadTransfer.payloadChunk|offset|flags") }
|
||||||
if case .bytes = header.type {
|
if case .bytes = header.type {
|
||||||
@@ -289,7 +289,7 @@ class NearbyConnection{
|
|||||||
}
|
}
|
||||||
if (chunk.flags & 1) == 1 {
|
if (chunk.flags & 1) == 1 {
|
||||||
payloadBuffers.removeValue(forKey: payloadID)
|
payloadBuffers.removeValue(forKey: payloadID)
|
||||||
if !(try processBytesPayload(payload: Data(buffer), id: payloadID)){
|
if try !processBytesPayload(payload: Data(buffer), id: payloadID) {
|
||||||
let innerFrame = try Sharing_Nearby_Frame(serializedBytes: buffer as Data)
|
let innerFrame = try Sharing_Nearby_Frame(serializedBytes: buffer as Data)
|
||||||
try processTransferSetupFrame(innerFrame)
|
try processTransferSetupFrame(innerFrame)
|
||||||
}
|
}
|
||||||
@@ -297,7 +297,7 @@ class NearbyConnection{
|
|||||||
} else if case .file = header.type {
|
} else if case .file = header.type {
|
||||||
try processFileChunk(frame: payloadTransfer)
|
try processFileChunk(frame: payloadTransfer)
|
||||||
}
|
}
|
||||||
}else if offlineFrame.hasV1 && offlineFrame.v1.hasType, case .keepAlive = offlineFrame.v1.type{
|
} else if offlineFrame.hasV1, offlineFrame.v1.hasType, case .keepAlive = offlineFrame.v1.type {
|
||||||
log("Sent keep-alive")
|
log("Sent keep-alive")
|
||||||
sendKeepAlive(ack: true)
|
sendKeepAlive(ack: true)
|
||||||
} else {
|
} else {
|
||||||
@@ -305,12 +305,12 @@ class NearbyConnection{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static func pinCodeFromAuthKey(_ key:SymmetricKey) -> String{
|
static func pinCodeFromAuthKey(_ key: SymmetricKey) -> String {
|
||||||
var hash:Int=0
|
var hash = 0
|
||||||
var multiplier:Int=1
|
var multiplier = 1
|
||||||
let keyBytes:[UInt8]=key.withUnsafeBytes({
|
let keyBytes: [UInt8] = key.withUnsafeBytes {
|
||||||
return [UInt8]($0)
|
[UInt8]($0)
|
||||||
})
|
}
|
||||||
|
|
||||||
for _byte in keyBytes {
|
for _byte in keyBytes {
|
||||||
let byte = Int(Int8(bitPattern: _byte))
|
let byte = Int(Int8(bitPattern: _byte))
|
||||||
@@ -321,32 +321,32 @@ class NearbyConnection{
|
|||||||
return String(format: "%04d", abs(hash))
|
return String(format: "%04d", abs(hash))
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static func hkdfExtract(salt:Data, ikm:Data) -> Data{
|
static func hkdfExtract(salt: Data, ikm: Data) -> Data {
|
||||||
return HMAC<SHA256>.authenticationCode(for: ikm, using: SymmetricKey(data: salt)).withUnsafeBytes({return Data(bytes: $0.baseAddress!, count: $0.count)})
|
return HMAC<SHA256>.authenticationCode(for: ikm, using: SymmetricKey(data: salt)).withUnsafeBytes { Data(bytes: $0.baseAddress!, count: $0.count) }
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static func hkdfExpand(prk:Data, info:Data, length:Int) -> Data{
|
static func hkdfExpand(prk: Data, info: Data, length: Int) -> Data {
|
||||||
var okm = Data()
|
var okm = Data()
|
||||||
var t = Data()
|
var t = Data()
|
||||||
var i = 0
|
var i = 0
|
||||||
while okm.count < length {
|
while okm.count < length {
|
||||||
i = i + 1
|
i = i + 1
|
||||||
let toDigest = t + info + Data([UInt8(truncatingIfNeeded: i)])
|
let toDigest = t + info + Data([UInt8(truncatingIfNeeded: i)])
|
||||||
t=HMAC<SHA256>.authenticationCode(for: toDigest, using: SymmetricKey(data: prk)).withUnsafeBytes({return Data(bytes: $0.baseAddress!, count: $0.count)})
|
t = HMAC<SHA256>.authenticationCode(for: toDigest, using: SymmetricKey(data: prk)).withUnsafeBytes { Data(bytes: $0.baseAddress!, count: $0.count) }
|
||||||
okm = okm + t
|
okm = okm + t
|
||||||
}
|
}
|
||||||
return okm.subdata(in: 0 ..< length)
|
return okm.subdata(in: 0 ..< length)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static func hkdf(inputKeyMaterial:SymmetricKey, salt:Data, info:Data, outputByteCount:Int) -> SymmetricKey{
|
static func hkdf(inputKeyMaterial: SymmetricKey, salt: Data, info: Data, outputByteCount: Int) -> SymmetricKey {
|
||||||
if #available(macOS 11.0, *) {
|
if #available(macOS 11.0, *) {
|
||||||
return HKDF<SHA256>.deriveKey(inputKeyMaterial: inputKeyMaterial, salt: salt, info: info, outputByteCount: outputByteCount)
|
return HKDF<SHA256>.deriveKey(inputKeyMaterial: inputKeyMaterial, salt: salt, info: info, outputByteCount: outputByteCount)
|
||||||
} else {
|
} else {
|
||||||
return SymmetricKey(data: hkdfExpand(prk: hkdfExtract(salt: salt, ikm: inputKeyMaterial.withUnsafeBytes({return Data(bytes: $0.baseAddress!, count: $0.count)})), info: info, length: outputByteCount))
|
return SymmetricKey(data: hkdfExpand(prk: hkdfExtract(salt: salt, ikm: inputKeyMaterial.withUnsafeBytes { Data(bytes: $0.baseAddress!, count: $0.count) }), info: info, length: outputByteCount))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func finalizeKeyExchange(peerKey:Securemessage_GenericPublicKey) throws{
|
func finalizeKeyExchange(peerKey: Securemessage_GenericPublicKey) throws {
|
||||||
guard peerKey.hasEcP256PublicKey else { throw NearbyError.requiredFieldMissing("peerKey.ecP256PublicKey") }
|
guard peerKey.hasEcP256PublicKey else { throw NearbyError.requiredFieldMissing("peerKey.ecP256PublicKey") }
|
||||||
|
|
||||||
let domain = Domain.instance(curve: .EC256r1)
|
let domain = Domain.instance(curve: .EC256r1)
|
||||||
@@ -360,7 +360,7 @@ class NearbyConnection{
|
|||||||
}
|
}
|
||||||
let key = try ECPublicKey(domain: domain, w: Point(BInt(magnitude: [UInt8](clientX)), BInt(magnitude: [UInt8](clientY))))
|
let key = try ECPublicKey(domain: domain, w: Point(BInt(magnitude: [UInt8](clientX)), BInt(magnitude: [UInt8](clientY))))
|
||||||
|
|
||||||
let dhs=(try privateKey?.domain.multiplyPoint(key.w, privateKey!.s).x.asMagnitudeBytes())!
|
let dhs = try (privateKey?.domain.multiplyPoint(key.w, privateKey!.s).x.asMagnitudeBytes())!
|
||||||
var sha = SHA256()
|
var sha = SHA256()
|
||||||
sha.update(data: dhs)
|
sha.update(data: dhs)
|
||||||
let derivedSecretKey = Data(sha.finalize())
|
let derivedSecretKey = Data(sha.finalize())
|
||||||
@@ -373,7 +373,7 @@ class NearbyConnection{
|
|||||||
|
|
||||||
pinCode = NearbyConnection.pinCodeFromAuthKey(authString)
|
pinCode = NearbyConnection.pinCodeFromAuthKey(authString)
|
||||||
|
|
||||||
let salt:Data=Data([0x82, 0xAA, 0x55, 0xA0, 0xD3, 0x97, 0xF8, 0x83, 0x46, 0xCA, 0x1C,
|
let salt = Data([0x82, 0xAA, 0x55, 0xA0, 0xD3, 0x97, 0xF8, 0x83, 0x46, 0xCA, 0x1C,
|
||||||
0xEE, 0x8D, 0x39, 0x09, 0xB9, 0x5F, 0x13, 0xFA, 0x7D, 0xEB, 0x1D,
|
0xEE, 0x8D, 0x39, 0x09, 0xB9, 0x5F, 0x13, 0xFA, 0x7D, 0xEB, 0x1D,
|
||||||
0x4A, 0xB3, 0x83, 0x76, 0xB8, 0x25, 0x6D, 0xA8, 0x55, 0x10])
|
0x4A, 0xB3, 0x83, 0x76, 0xB8, 0x25, 0x6D, 0xA8, 0x55, 0x10])
|
||||||
|
|
||||||
@@ -384,9 +384,9 @@ class NearbyConnection{
|
|||||||
sha.update(data: "SecureMessage".data(using: .utf8)!)
|
sha.update(data: "SecureMessage".data(using: .utf8)!)
|
||||||
let smsgSalt = Data(sha.finalize())
|
let smsgSalt = Data(sha.finalize())
|
||||||
|
|
||||||
let clientKey=NearbyConnection.hkdf(inputKeyMaterial: d2dClientKey, salt: smsgSalt, info: "ENC:2".data(using: .utf8)!, outputByteCount: 32).withUnsafeBytes({return [UInt8]($0)})
|
let clientKey = NearbyConnection.hkdf(inputKeyMaterial: d2dClientKey, salt: smsgSalt, info: "ENC:2".data(using: .utf8)!, outputByteCount: 32).withUnsafeBytes { [UInt8]($0) }
|
||||||
let clientHmacKey = NearbyConnection.hkdf(inputKeyMaterial: d2dClientKey, salt: smsgSalt, info: "SIG:1".data(using: .utf8)!, outputByteCount: 32)
|
let clientHmacKey = NearbyConnection.hkdf(inputKeyMaterial: d2dClientKey, salt: smsgSalt, info: "SIG:1".data(using: .utf8)!, outputByteCount: 32)
|
||||||
let serverKey=NearbyConnection.hkdf(inputKeyMaterial: d2dServerKey, salt: smsgSalt, info: "ENC:2".data(using: .utf8)!, outputByteCount: 32).withUnsafeBytes({return [UInt8]($0)})
|
let serverKey = NearbyConnection.hkdf(inputKeyMaterial: d2dServerKey, salt: smsgSalt, info: "ENC:2".data(using: .utf8)!, outputByteCount: 32).withUnsafeBytes { [UInt8]($0) }
|
||||||
let serverHmacKey = NearbyConnection.hkdf(inputKeyMaterial: d2dServerKey, salt: smsgSalt, info: "SIG:1".data(using: .utf8)!, outputByteCount: 32)
|
let serverHmacKey = NearbyConnection.hkdf(inputKeyMaterial: d2dServerKey, salt: smsgSalt, info: "SIG:1".data(using: .utf8)!, outputByteCount: 32)
|
||||||
|
|
||||||
if isServer() {
|
if isServer() {
|
||||||
@@ -402,14 +402,14 @@ class NearbyConnection{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func disconnect(){
|
func disconnect() {
|
||||||
connection.send(content: nil, isComplete: true, completion: .contentProcessed({ error in
|
connection.send(content: nil, isComplete: true, completion: .contentProcessed { _ in
|
||||||
self.handleConnectionClosure()
|
self.handleConnectionClosure()
|
||||||
}))
|
})
|
||||||
connectionClosed = true
|
connectionClosed = true
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func sendDisconnectionAndDisconnect() throws{
|
func sendDisconnectionAndDisconnect() throws {
|
||||||
var offlineFrame = Location_Nearby_Connections_OfflineFrame()
|
var offlineFrame = Location_Nearby_Connections_OfflineFrame()
|
||||||
offlineFrame.version = .v1
|
offlineFrame.version = .v1
|
||||||
offlineFrame.v1.type = .disconnection
|
offlineFrame.v1.type = .disconnection
|
||||||
@@ -418,12 +418,12 @@ class NearbyConnection{
|
|||||||
if encryptionDone {
|
if encryptionDone {
|
||||||
try encryptAndSendOfflineFrame(offlineFrame)
|
try encryptAndSendOfflineFrame(offlineFrame)
|
||||||
} else {
|
} else {
|
||||||
sendFrameAsync(try offlineFrame.serializedData())
|
try sendFrameAsync(offlineFrame.serializedData())
|
||||||
}
|
}
|
||||||
disconnect()
|
disconnect()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func sendUkey2Alert(type:Securegcm_Ukey2Alert.AlertType){
|
func sendUkey2Alert(type: Securegcm_Ukey2Alert.AlertType) {
|
||||||
var alert = Securegcm_Ukey2Alert()
|
var alert = Securegcm_Ukey2Alert()
|
||||||
alert.type = type
|
alert.type = type
|
||||||
var msg = Securegcm_Ukey2Message()
|
var msg = Securegcm_Ukey2Message()
|
||||||
@@ -433,7 +433,7 @@ class NearbyConnection{
|
|||||||
disconnect()
|
disconnect()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal func sendKeepAlive(ack:Bool){
|
func sendKeepAlive(ack: Bool) {
|
||||||
var offlineFrame = Location_Nearby_Connections_OfflineFrame()
|
var offlineFrame = Location_Nearby_Connections_OfflineFrame()
|
||||||
offlineFrame.version = .v1
|
offlineFrame.version = .v1
|
||||||
offlineFrame.v1.type = .keepAlive
|
offlineFrame.v1.type = .keepAlive
|
||||||
@@ -443,7 +443,7 @@ class NearbyConnection{
|
|||||||
if encryptionDone {
|
if encryptionDone {
|
||||||
try encryptAndSendOfflineFrame(offlineFrame)
|
try encryptAndSendOfflineFrame(offlineFrame)
|
||||||
} else {
|
} else {
|
||||||
sendFrameAsync(try offlineFrame.serializedData())
|
try sendFrameAsync(offlineFrame.serializedData())
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
log("Error sending KEEP_ALIVE: \(error)")
|
log("Error sending KEEP_ALIVE: \(error)")
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ public struct RemoteDeviceInfo{
|
|||||||
}
|
}
|
||||||
|
|
||||||
init(info: EndpointInfo) {
|
init(info: EndpointInfo) {
|
||||||
self.name=info.name
|
name = info.name
|
||||||
self.type=info.deviceType
|
type = info.deviceType
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum DeviceType: Int32 {
|
public enum DeviceType: Int32 {
|
||||||
@@ -48,7 +48,6 @@ public struct RemoteDeviceInfo{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public enum NearbyError: Error {
|
public enum NearbyError: Error {
|
||||||
case protocolError(_ message: String)
|
case protocolError(_ message: String)
|
||||||
case requiredFieldMissing(_ message: String)
|
case requiredFieldMissing(_ message: String)
|
||||||
@@ -107,9 +106,9 @@ struct EndpointInfo{
|
|||||||
let deviceNameLength = Int(data[17])
|
let deviceNameLength = Int(data[17])
|
||||||
guard data.count >= deviceNameLength + 18 else { return nil }
|
guard data.count >= deviceNameLength + 18 else { return nil }
|
||||||
guard let deviceName = String(data: data[18 ..< (18 + deviceNameLength)], encoding: .utf8) else { return nil }
|
guard let deviceName = String(data: data[18 ..< (18 + deviceNameLength)], encoding: .utf8) else { return nil }
|
||||||
let rawDeviceType:Int=Int(data[0] & 7) >> 1
|
let rawDeviceType = Int(data[0] & 7) >> 1
|
||||||
self.name=deviceName
|
name = deviceName
|
||||||
self.deviceType=RemoteDeviceInfo.DeviceType.fromRawValue(value: rawDeviceType)
|
deviceType = RemoteDeviceInfo.DeviceType.fromRawValue(value: rawDeviceType)
|
||||||
}
|
}
|
||||||
|
|
||||||
func serialize() -> Data {
|
func serialize() -> Data {
|
||||||
@@ -149,7 +148,6 @@ public protocol ShareExtensionDelegate:AnyObject{
|
|||||||
}
|
}
|
||||||
|
|
||||||
public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearbyConnectionDelegate, OutboundNearbyConnectionDelegate {
|
public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearbyConnectionDelegate, OutboundNearbyConnectionDelegate {
|
||||||
|
|
||||||
public var checkSignature = true {
|
public var checkSignature = true {
|
||||||
didSet {
|
didSet {
|
||||||
if !checkSignature {
|
if !checkSignature {
|
||||||
@@ -158,7 +156,7 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var tcpListener:NWListener;
|
private var tcpListener: NWListener
|
||||||
public let endpointID: [UInt8] = generateEndpointID()
|
public let endpointID: [UInt8] = generateEndpointID()
|
||||||
private var mdnsServices: [NetService] = []
|
private var mdnsServices: [NetService] = []
|
||||||
private var activeConnections: [String: InboundNearbyConnection] = [:]
|
private var activeConnections: [String: InboundNearbyConnection] = [:]
|
||||||
@@ -204,7 +202,8 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
|
|
||||||
// Try to retrieve from UserDefaults
|
// Try to retrieve from UserDefaults
|
||||||
if let savedString = UserDefaults.standard.string(forKey: userDefaultsKey),
|
if let savedString = UserDefaults.standard.string(forKey: userDefaultsKey),
|
||||||
let savedData = savedString.data(using: .utf8) {
|
let savedData = savedString.data(using: .utf8)
|
||||||
|
{
|
||||||
return [UInt8](savedData)
|
return [UInt8](savedData)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,25 +226,25 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
0x23, // PCP
|
0x23, // PCP
|
||||||
endpointID[0], endpointID[1], endpointID[2], endpointID[3],
|
endpointID[0], endpointID[1], endpointID[2], endpointID[3],
|
||||||
0xFC, 0x9F, 0x5E, // Service ID hash
|
0xFC, 0x9F, 0x5E, // Service ID hash
|
||||||
0, 0
|
0, 0,
|
||||||
]
|
]
|
||||||
let name = Data(nameBytes).urlSafeBase64EncodedString()
|
let name = Data(nameBytes).urlSafeBase64EncodedString()
|
||||||
let endpointInfo = EndpointInfo(name: Host.current().localizedName!, deviceType: .computer)
|
let endpointInfo = EndpointInfo(name: Host.current().localizedName!, deviceType: .computer)
|
||||||
|
|
||||||
let port: Int32 = Int32(tcpListener.port!.rawValue)
|
let port = Int32(tcpListener.port!.rawValue)
|
||||||
|
|
||||||
mdnsServices = serviceTypes.map { serviceType in
|
mdnsServices = serviceTypes.map { serviceType in
|
||||||
let service = NetService(domain: "", type: serviceType, name: name, port: port)
|
let service = NetService(domain: "", type: serviceType, name: name, port: port)
|
||||||
service.delegate = self
|
service.delegate = self
|
||||||
service.setTXTRecord(NetService.data(fromTXTRecord: [
|
service.setTXTRecord(NetService.data(fromTXTRecord: [
|
||||||
"n": endpointInfo.serialize().urlSafeBase64EncodedString().data(using: .utf8)!
|
"n": endpointInfo.serialize().urlSafeBase64EncodedString().data(using: .utf8)!,
|
||||||
]))
|
]))
|
||||||
service.publish()
|
service.publish()
|
||||||
return service
|
return service
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func obtainUserConsent(for transfer: TransferMetadata, from device: RemoteDeviceInfo, connection: InboundNearbyConnection) {
|
func obtainUserConsent(for transfer: TransferMetadata, from device: RemoteDeviceInfo, connection _: InboundNearbyConnection) {
|
||||||
guard let delegate = mainAppDelegate else { return }
|
guard let delegate = mainAppDelegate else { return }
|
||||||
delegate.obtainUserConsent(for: transfer, from: device)
|
delegate.obtainUserConsent(for: transfer, from: device)
|
||||||
}
|
}
|
||||||
@@ -261,9 +260,7 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
conn.submitUserConsent(accepted: accept, storeInTemp: storeInTemp)
|
conn.submitUserConsent(accepted: accept, storeInTemp: storeInTemp)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public func startDeviceDiscovery() {
|
public func startDeviceDiscovery() {
|
||||||
|
|
||||||
log("Device discovery requested.")
|
log("Device discovery requested.")
|
||||||
|
|
||||||
if discoveryRefCount == 0 {
|
if discoveryRefCount == 0 {
|
||||||
@@ -273,11 +270,10 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
|
|
||||||
if browsers.isEmpty {
|
if browsers.isEmpty {
|
||||||
for type in serviceTypes {
|
for type in serviceTypes {
|
||||||
|
|
||||||
log("Starting browser for type \(type)")
|
log("Starting browser for type \(type)")
|
||||||
|
|
||||||
let browser = NWBrowser(for: .bonjourWithTXTRecord(type: type, domain: nil), using: .tcp)
|
let browser = NWBrowser(for: .bonjourWithTXTRecord(type: type, domain: nil), using: .tcp)
|
||||||
browser.browseResultsChangedHandler = { newResults, changes in
|
browser.browseResultsChangedHandler = { _, changes in
|
||||||
for change in changes {
|
for change in changes {
|
||||||
switch change {
|
switch change {
|
||||||
case let .added(res):
|
case let .added(res):
|
||||||
@@ -286,7 +282,6 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
self.removeFoundDevice(service: res)
|
self.removeFoundDevice(service: res)
|
||||||
default:
|
default:
|
||||||
log("Ignoring change \(change)")
|
log("Ignoring change \(change)")
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -299,7 +294,6 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
discoveryRefCount += 1
|
discoveryRefCount += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public func stopDeviceDiscovery() {
|
public func stopDeviceDiscovery() {
|
||||||
discoveryRefCount -= 1
|
discoveryRefCount -= 1
|
||||||
assert(discoveryRefCount >= 0)
|
assert(discoveryRefCount >= 0)
|
||||||
@@ -381,7 +375,7 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
|
|
||||||
public func startOutgoingTransfer(deviceID: String, delegate: ShareExtensionDelegate, urls: [URL]) {
|
public func startOutgoingTransfer(deviceID: String, delegate: ShareExtensionDelegate, urls: [URL]) {
|
||||||
guard let info = foundServices[deviceID] else { return }
|
guard let info = foundServices[deviceID] else { return }
|
||||||
let tcp=NWProtocolTCP.Options.init()
|
let tcp = NWProtocolTCP.Options()
|
||||||
tcp.noDelay = true
|
tcp.noDelay = true
|
||||||
let nwconn = NWConnection(to: info.service.endpoint, using: NWParameters(tls: .none, tcp: tcp))
|
let nwconn = NWConnection(to: info.service.endpoint, using: NWParameters(tls: .none, tcp: tcp))
|
||||||
let conn = OutboundNearbyConnection(connection: nwconn, id: deviceID, urlsToSend: urls)
|
let conn = OutboundNearbyConnection(connection: nwconn, id: deviceID, urlsToSend: urls)
|
||||||
@@ -432,4 +426,3 @@ public class NearbyConnectionManager : NSObject, NetServiceDelegate, InboundNear
|
|||||||
return activeConnections.count
|
return activeConnections.count
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5,15 +5,15 @@
|
|||||||
// Created by Grishka on 23.09.2023.
|
// Created by Grishka on 23.09.2023.
|
||||||
//
|
//
|
||||||
|
|
||||||
|
import CommonCrypto
|
||||||
|
import CryptoKit
|
||||||
import Foundation
|
import Foundation
|
||||||
import Network
|
import Network
|
||||||
import CryptoKit
|
|
||||||
import CommonCrypto
|
|
||||||
import System
|
import System
|
||||||
import UniformTypeIdentifiers
|
import UniformTypeIdentifiers
|
||||||
|
|
||||||
import SwiftECC
|
|
||||||
import BigInt
|
import BigInt
|
||||||
|
import SwiftECC
|
||||||
|
|
||||||
class OutboundNearbyConnection: NearbyConnection {
|
class OutboundNearbyConnection: NearbyConnection {
|
||||||
private var currentState: State = .initial
|
private var currentState: State = .initial
|
||||||
@@ -84,9 +84,9 @@ class OutboundNearbyConnection:NearbyConnection{
|
|||||||
case .initial:
|
case .initial:
|
||||||
protocolError()
|
protocolError()
|
||||||
case .sentUkeyClientInit:
|
case .sentUkeyClientInit:
|
||||||
try processUkey2ServerInit(frame: try Securegcm_Ukey2Message(serializedBytes: frameData), raw: frameData)
|
try processUkey2ServerInit(frame: Securegcm_Ukey2Message(serializedBytes: frameData), raw: frameData)
|
||||||
case .sentUkeyClientFinish:
|
case .sentUkeyClientFinish:
|
||||||
try processConnectionResponse(frame: try Location_Nearby_Connections_OfflineFrame(serializedBytes: frameData))
|
try processConnectionResponse(frame: Location_Nearby_Connections_OfflineFrame(serializedBytes: frameData))
|
||||||
default:
|
default:
|
||||||
let smsg = try Securemessage_SecureMessage(serializedBytes: frameData)
|
let smsg = try Securemessage_SecureMessage(serializedBytes: frameData)
|
||||||
try decryptAndProcessReceivedSecureMessage(smsg)
|
try decryptAndProcessReceivedSecureMessage(smsg)
|
||||||
@@ -139,7 +139,7 @@ class OutboundNearbyConnection:NearbyConnection{
|
|||||||
let endpointInfo = EndpointInfo(name: Host.current().localizedName!, deviceType: .computer)
|
let endpointInfo = EndpointInfo(name: Host.current().localizedName!, deviceType: .computer)
|
||||||
frame.v1.connectionRequest.endpointInfo = endpointInfo.serialize()
|
frame.v1.connectionRequest.endpointInfo = endpointInfo.serialize()
|
||||||
frame.v1.connectionRequest.mediums = [.wifiLan]
|
frame.v1.connectionRequest.mediums = [.wifiLan]
|
||||||
sendFrameAsync(try frame.serializedData())
|
try sendFrameAsync(frame.serializedData())
|
||||||
}
|
}
|
||||||
|
|
||||||
private func sendUkey2ClientInit() throws {
|
private func sendUkey2ClientInit() throws {
|
||||||
@@ -214,7 +214,7 @@ class OutboundNearbyConnection:NearbyConnection{
|
|||||||
resp.v1.connectionResponse.status = 0
|
resp.v1.connectionResponse.status = 0
|
||||||
resp.v1.connectionResponse.osInfo = Location_Nearby_Connections_OsInfo()
|
resp.v1.connectionResponse.osInfo = Location_Nearby_Connections_OsInfo()
|
||||||
resp.v1.connectionResponse.osInfo.type = .apple
|
resp.v1.connectionResponse.osInfo.type = .apple
|
||||||
sendFrameAsync(try resp.serializedData())
|
try sendFrameAsync(resp.serializedData())
|
||||||
|
|
||||||
encryptionDone = true
|
encryptionDone = true
|
||||||
delegate?.outboundConnectionWasEstablished(connection: self)
|
delegate?.outboundConnectionWasEstablished(connection: self)
|
||||||
@@ -288,15 +288,15 @@ class OutboundNearbyConnection:NearbyConnection{
|
|||||||
meta.type = .image
|
meta.type = .image
|
||||||
} else if meta.mimeType.starts(with: "video/") {
|
} else if meta.mimeType.starts(with: "video/") {
|
||||||
meta.type = .video
|
meta.type = .video
|
||||||
}else if(meta.mimeType.starts(with: "audio/")){
|
} else if meta.mimeType.starts(with: "audio/") {
|
||||||
meta.type = .audio
|
meta.type = .audio
|
||||||
}else if(url.pathExtension.lowercased()=="apk"){
|
} else if url.pathExtension.lowercased() == "apk" {
|
||||||
meta.type = .app
|
meta.type = .app
|
||||||
} else {
|
} else {
|
||||||
meta.type = .unknown
|
meta.type = .unknown
|
||||||
}
|
}
|
||||||
meta.payloadID = Int64.random(in: Int64.min ... Int64.max)
|
meta.payloadID = Int64.random(in: Int64.min ... Int64.max)
|
||||||
queue.append(OutgoingFileTransfer(url: url, payloadID: meta.payloadID, handle: try FileHandle(forReadingFrom: url), totalBytes: meta.size, currentOffset: 0))
|
try queue.append(OutgoingFileTransfer(url: url, payloadID: meta.payloadID, handle: FileHandle(forReadingFrom: url), totalBytes: meta.size, currentOffset: 0))
|
||||||
introduction.v1.introduction.fileMetadata.append(meta)
|
introduction.v1.introduction.fileMetadata.append(meta)
|
||||||
totalBytesToSend += meta.size
|
totalBytesToSend += meta.size
|
||||||
}
|
}
|
||||||
@@ -420,7 +420,7 @@ class OutboundNearbyConnection:NearbyConnection{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate struct OutgoingFileTransfer{
|
private struct OutgoingFileTransfer {
|
||||||
let url: URL
|
let url: URL
|
||||||
let payloadID: Int64
|
let payloadID: Int64
|
||||||
let handle: FileHandle?
|
let handle: FileHandle?
|
||||||
|
|||||||
Reference in new issue
Block a user