Improve logging

This commit is contained in:
Leon Böttger committed 2025-07-27 15:13:29 +02:00
1 parent e3562ab03a
commit 77657ece73
4 files changed
+40 -47

No files matched your search

+14 -14
View File
@@ -52,7 +52,7 @@ class InboundNearbyConnection: NearbyConnection {
override func processReceivedFrame(frameData: Data) { override func processReceivedFrame(frameData: Data) {
if currentState != .receivingFiles { if currentState != .receivingFiles {
log("Received frame in state \(currentState)...") log("[InboundNearbyConnection] Received frame in state \(currentState)...")
} }
do { do {
@@ -77,7 +77,7 @@ class InboundNearbyConnection: NearbyConnection {
do { do {
smsg = try Securemessage_SecureMessage(serializedBytes: frameData) smsg = try Securemessage_SecureMessage(serializedBytes: frameData)
} catch { } catch {
log("Error deserializing secure message (probably due to packet filter)") log("[InboundNearbyConnection] Error deserializing secure message (probably due to packet filter)")
lastError = NearbyError.packetFilterError lastError = NearbyError.packetFilterError
protocolError() protocolError()
} }
@@ -88,7 +88,7 @@ class InboundNearbyConnection: NearbyConnection {
} }
} catch { } catch {
lastError = error lastError = error
log("Error receiving frame: \(error) in state \(currentState).") log("[InboundNearbyConnection] Error receiving frame: \(error) in state \(currentState).")
protocolError() protocolError()
} }
} }
@@ -96,7 +96,7 @@ class InboundNearbyConnection: NearbyConnection {
override 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("[InboundNearbyConnection] Transfer canceled")
try sendDisconnectionAndDisconnect() try sendDisconnectionAndDisconnect()
return return
} }
@@ -108,7 +108,7 @@ class InboundNearbyConnection: NearbyConnection {
case .receivedPairedKeyResult: case .receivedPairedKeyResult:
try processIntroductionFrame(frame) try processIntroductionFrame(frame)
default: default:
log("Unexpected connection state in processTransferSetupFrame: \(currentState)") log("[InboundNearbyConnection] Unexpected connection state in processTransferSetupFrame: \(currentState)")
log(frame.debugDescription) log(frame.debugDescription)
} }
} }
@@ -137,7 +137,7 @@ class InboundNearbyConnection: NearbyConnection {
filesToBeReceived[id]!.bytesTransferred += Int64(frame.payloadChunk.body.count) filesToBeReceived[id]!.bytesTransferred += Int64(frame.payloadChunk.body.count)
fileInfo.progress?.completedUnitCount = filesToBeReceived[id]!.bytesTransferred fileInfo.progress?.completedUnitCount = filesToBeReceived[id]!.bytesTransferred
} catch { } catch {
log("Error occurred during writing file: \(error.localizedDescription)") log("[InboundNearbyConnection] Error occurred during writing file: \(error.localizedDescription)")
throw NearbyError.protocolError(error.localizedDescription) throw NearbyError.protocolError(error.localizedDescription)
} }
@@ -151,7 +151,7 @@ class InboundNearbyConnection: NearbyConnection {
filesToBeReceived.removeValue(forKey: id) filesToBeReceived.removeValue(forKey: id)
if filesToBeReceived.isEmpty { if filesToBeReceived.isEmpty {
log("All files received, sending disconnection frame and disconnecting.") log("[InboundNearbyConnection] All files received, sending disconnection frame and disconnecting.")
try sendDisconnectionAndDisconnect() try sendDisconnectionAndDisconnect()
} }
} }
@@ -175,7 +175,7 @@ class InboundNearbyConnection: NearbyConnection {
} }
} }
log("Received text payload. Disconnecting...") log("[InboundNearbyConnection] Received text payload. Disconnecting...")
try sendDisconnectionAndDisconnect() try sendDisconnectionAndDisconnect()
return true return true
} }
@@ -189,7 +189,7 @@ class InboundNearbyConnection: NearbyConnection {
filesToBeReceived.removeValue(forKey: id) filesToBeReceived.removeValue(forKey: id)
SaveFilesManager.shared.registerFileFinishedDownloading(fileInfo.destinationURL) SaveFilesManager.shared.registerFileFinishedDownloading(fileInfo.destinationURL)
log("Received file payload. Disconnecting...") log("[InboundNearbyConnection] Received file payload. Disconnecting...")
try sendDisconnectionAndDisconnect() try sendDisconnectionAndDisconnect()
return true return true
} }
@@ -330,7 +330,7 @@ class InboundNearbyConnection: NearbyConnection {
try sendTransferSetupFrame(pairedEncryption) try sendTransferSetupFrame(pairedEncryption)
currentState = .sentConnectionResponse currentState = .sentConnectionResponse
} else { } else {
log("Unhandled offline frame plaintext: \(frame)") log("[InboundNearbyConnection] Unhandled offline frame plaintext: \(frame)")
} }
} }
@@ -421,7 +421,7 @@ class InboundNearbyConnection: NearbyConnection {
func rejectDueToUnsupportedFileType(_ frame: Sharing_Nearby_Frame) { func rejectDueToUnsupportedFileType(_ frame: Sharing_Nearby_Frame) {
log("Rejecting transfer due to unsupported file type. Frame is \(frame.debugDescription)") log("[InboundNearbyConnection] Rejecting transfer due to unsupported file type. Frame is \(frame.debugDescription)")
NearbyConnectionManager.shared.mainAppDelegate?.showUnsupportedFileAlert(for: remoteDeviceInfo) NearbyConnectionManager.shared.mainAppDelegate?.showUnsupportedFileAlert(for: remoteDeviceInfo)
rejectTransfer(with: .unsupportedAttachmentType) rejectTransfer(with: .unsupportedAttachmentType)
@@ -441,7 +441,7 @@ 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("[InboundNearbyConnection] Detected timeout, not accepting transfer")
return return
} }
@@ -484,7 +484,7 @@ class InboundNearbyConnection: NearbyConnection {
self.wasRejected = true self.wasRejected = true
log("Rejecting transfer because of \( reason)") log("[InboundNearbyConnection] Rejecting transfer because of \( reason)")
var frame = Sharing_Nearby_Frame() var frame = Sharing_Nearby_Frame()
frame.version = .v1 frame.version = .v1
@@ -494,7 +494,7 @@ class InboundNearbyConnection: NearbyConnection {
try sendTransferSetupFrame(frame) try sendTransferSetupFrame(frame)
try sendDisconnectionAndDisconnect() try sendDisconnectionAndDisconnect()
} catch { } catch {
log("Error \(error)") log("[InboundNearbyConnection] Error \(error)")
protocolError() protocolError()
} }
} }
+14 -16
View File
@@ -82,7 +82,7 @@ class NearbyConnection {
} }
} }
else { else {
log("Connection already closed, ignoring state update: \(state)") log("[NearbyConnection] Connection already closed, ignoring state update: \(state)")
} }
} }
@@ -90,7 +90,7 @@ class NearbyConnection {
func recordErrorAndDisconnect(err: NWError) { func recordErrorAndDisconnect(err: NWError) {
self.lastError = err self.lastError = err
log("Connection Error: \(err)") log("[NearbyConnection] Connection Error: \(err)")
// If the error is a connection reset, it could be due to firewall issues. // If the error is a connection reset, it could be due to firewall issues.
if err == .posix(.ENOTCONN) { if err == .posix(.ENOTCONN) {
@@ -112,7 +112,7 @@ class NearbyConnection {
func protocolError() { func protocolError() {
log("Protocol error: \(String(describing: lastError))") log("[NearbyConnection] Protocol error: \(String(describing: lastError))")
disconnect() disconnect()
} }
@@ -148,7 +148,7 @@ class NearbyConnection {
return return
} }
if isComplete { if isComplete {
log("Connection closed by peer during receiveFrameAsync") log("[NearbyConnection] Connection closed by peer during receiveFrameAsync")
self.lastError = NearbyError.protocolError("Error.ClosedByPeer".localized()) self.lastError = NearbyError.protocolError("Error.ClosedByPeer".localized())
self.disconnect() self.disconnect()
return return
@@ -181,7 +181,7 @@ class NearbyConnection {
return return
} }
if isComplete { if isComplete {
log("Connection closed by peer during receiveFrameAsync") log("[NearbyConnection] Connection closed by peer during receiveFrameAsync")
self.lastError = NearbyError.protocolError("Error.ClosedByPeer".localized()) self.lastError = NearbyError.protocolError("Error.ClosedByPeer".localized())
self.disconnect() self.disconnect()
return return
@@ -262,15 +262,13 @@ class NearbyConnection {
func sendTransferSetupFrame(_ frame: Sharing_Nearby_Frame) throws { func sendTransferSetupFrame(_ frame: Sharing_Nearby_Frame) throws {
log("Sending transfer setup frame.") log("[NearbyConnection] Sending transfer setup frame.")
try sendBytesPayload(data: frame.serializedData(), id: Int64.random(in: Int64.min ... Int64.max)) try sendBytesPayload(data: frame.serializedData(), id: Int64.random(in: Int64.min ... Int64.max))
} }
func sendBytesPayload(data: Data, id: Int64) throws { func sendBytesPayload(data: Data, id: Int64) throws {
log("Sending bytes payload with ID \(id) of length \(data.count)")
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
@@ -339,7 +337,7 @@ class NearbyConnection {
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 { guard payloadTransfer.hasPayloadChunk, chunk.hasOffset, chunk.hasFlags else {
log("Payload transfer chunk is missing offset or flags, likely canceled.") log("[NearbyConnection] Payload transfer chunk is missing offset or flags, likely canceled.")
throw NearbyError.canceled(reason: .userCanceled) throw NearbyError.canceled(reason: .userCanceled)
} }
@@ -384,11 +382,11 @@ class NearbyConnection {
} }
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("[NearbyConnection] Sent keep-alive")
sendKeepAlive(ack: true) sendKeepAlive(ack: true)
} else { } else {
log("Unhandled offline frame encrypted: \(offlineFrame)") log("[NearbyConnection] Unhandled offline frame encrypted: \(offlineFrame)")
} }
} }
@@ -492,7 +490,7 @@ class NearbyConnection {
func disconnect() { func disconnect() {
log("Disconnecting from connection.") log("[NearbyConnection] Disconnecting from connection.")
connection.stateUpdateHandler = nil connection.stateUpdateHandler = nil
inactivityTimer?.cancel() inactivityTimer?.cancel()
@@ -514,7 +512,7 @@ class NearbyConnection {
try sendFrameAsync(offlineFrame.serializedData()) try sendFrameAsync(offlineFrame.serializedData())
} }
log("Sent disconnection frame during sendDisconnectionAndDisconnect") log("[NearbyConnection] Sent disconnection frame during sendDisconnectionAndDisconnect")
disconnect() disconnect()
} }
@@ -527,7 +525,7 @@ class NearbyConnection {
msg.messageData = try! alert.serializedData() msg.messageData = try! alert.serializedData()
sendFrameAsync(try! msg.serializedData()) sendFrameAsync(try! msg.serializedData())
log("Sent UKEY2 alert: \(type)") log("[NearbyConnection] Sent UKEY2 alert: \(type)")
disconnect() disconnect()
} }
@@ -545,7 +543,7 @@ class NearbyConnection {
try sendFrameAsync(offlineFrame.serializedData()) try sendFrameAsync(offlineFrame.serializedData())
} }
} catch { } catch {
log("Error sending KEEP_ALIVE: \(error)") log("[NearbyConnection] Error sending KEEP_ALIVE: \(error)")
} }
} }
@@ -562,7 +560,7 @@ class NearbyConnection {
guard let self = self else { return } guard let self = self else { return }
if !self.connectionClosed { if !self.connectionClosed {
log("Connection timeout: No message received in \(self.timeoutInterval) seconds") log("[NearbyConnection] Connection timeout: No message received in \(self.timeoutInterval) seconds")
self.lastError = NearbyError.canceled(reason: .timedOut) self.lastError = NearbyError.canceled(reason: .timedOut)
self.disconnect() self.disconnect()
} }
+5 -7
View File
@@ -123,7 +123,7 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
public func submitUserConsent(transferID: String, accept: Bool, storeInTemp: Bool = false) { public func submitUserConsent(transferID: String, accept: Bool, storeInTemp: Bool = false) {
guard let conn = incomingConnections[transferID] else { return } guard let conn = incomingConnections[transferID] else { return }
log("Submitting user consent for transfer, accepted: \(accept), store in temp: \(storeInTemp)") log("[NearbyConnectionManager] Submitting user consent for transfer, accepted: \(accept), store in temp: \(storeInTemp)")
conn.submitUserConsent(accepted: accept, storeInTemp: storeInTemp) conn.submitUserConsent(accepted: accept, storeInTemp: storeInTemp)
} }
@@ -134,11 +134,11 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
startedDeviceDiscovery = true startedDeviceDiscovery = true
foundServices.removeAll() foundServices.removeAll()
log("Starting device discovery") log("[NearbyConnectionManager] Starting device discovery")
if browsers.isEmpty { if browsers.isEmpty {
for type in serviceTypes { for type in serviceTypes {
log("Starting browser for type \(type)") log("[NearbyConnectionManager] 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 = { _, changes in browser.browseResultsChangedHandler = { _, changes in
@@ -149,7 +149,7 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
case let .removed(res): case let .removed(res):
self.removeFoundDevice(service: res) self.removeFoundDevice(service: res)
default: default:
log("Ignoring change \(change)") log("[NearbyConnectionManager] Ignoring change \(change)")
} }
} }
} }
@@ -206,15 +206,13 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
private func addFoundDevice(service: NWBrowser.Result) { private func addFoundDevice(service: NWBrowser.Result) {
log("found service \(service)") log("[NearbyConnectionManager] Found Service \(service)")
for interface in service.interfaces { for interface in service.interfaces {
if case .loopback = interface.type { if case .loopback = interface.type {
log("ignoring localhost service")
return return
} }
} }
guard let endpointID = endpointID(for: service) else { return } guard let endpointID = endpointID(for: service) else { return }
log("service name is valid, endpoint ID \(endpointID)")
var foundService = FoundServiceInfo(service: service) var foundService = FoundServiceInfo(service: service)
guard case let NWBrowser.Result.Metadata.bonjour(txtRecord) = service.metadata else { return } guard case let NWBrowser.Result.Metadata.bonjour(txtRecord) = service.metadata else { return }
+7 -10
View File
@@ -102,7 +102,7 @@ class OutboundNearbyConnection: NearbyConnection {
override func processReceivedFrame(frameData: Data) { override func processReceivedFrame(frameData: Data) {
if currentState != .sendingFiles { if currentState != .sendingFiles {
log("Received frame in state \(currentState)...") log("[OutboundNearbyConnection] Received frame in state \(currentState)...")
} }
do { do {
@@ -119,7 +119,7 @@ class OutboundNearbyConnection: NearbyConnection {
} }
} catch { } catch {
log("Error occured while processing frame with data \(frameData.hex): \(error)") log("[OutboundNearbyConnection] Error occured while processing frame with data \(frameData.hex): \(error)")
if case NearbyError.ukey2 = error { if case NearbyError.ukey2 = error {
// do nothing // do nothing
@@ -137,14 +137,12 @@ class OutboundNearbyConnection: NearbyConnection {
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("[OutboundNearbyConnection] Transfer canceled")
try sendDisconnectionAndDisconnect() try sendDisconnectionAndDisconnect()
delegate?.outboundConnection(connection: self, failedWithError: NearbyError.canceled(reason: .userCanceled)) delegate?.outboundConnection(connection: self, failedWithError: NearbyError.canceled(reason: .userCanceled))
return return
} }
log(frame.debugDescription)
switch currentState { switch currentState {
case .sentPairedKeyEncryption: case .sentPairedKeyEncryption:
try processPairedKeyEncryption(frame: frame) try processPairedKeyEncryption(frame: frame)
@@ -155,7 +153,7 @@ class OutboundNearbyConnection: NearbyConnection {
case .sendingFiles: case .sendingFiles:
break break
default: default:
assertionFailure("Unexpected state \(currentState)") assertionFailure("[OutboundNearbyConnection] Unexpected state \(currentState)")
} }
} }
@@ -262,7 +260,6 @@ class OutboundNearbyConnection: NearbyConnection {
private func processConnectionResponse(frame: Location_Nearby_Connections_OfflineFrame) throws { private func processConnectionResponse(frame: Location_Nearby_Connections_OfflineFrame) throws {
log("connection response: \(frame)")
guard frame.version == .v1 else { throw NearbyError.protocolError("Unexpected offline frame version \(frame.version)") } guard frame.version == .v1 else { throw NearbyError.protocolError("Unexpected offline frame version \(frame.version)") }
guard frame.v1.type == .connectionResponse else { throw NearbyError.protocolError("Unexpected frame type \(frame.v1.type)") } guard frame.v1.type == .connectionResponse else { throw NearbyError.protocolError("Unexpected frame type \(frame.v1.type)") }
guard frame.v1.connectionResponse.response == .accept else { throw NearbyError.protocolError("Connection was rejected by recipient") } guard frame.v1.connectionResponse.response == .accept else { throw NearbyError.protocolError("Connection was rejected by recipient") }
@@ -347,7 +344,7 @@ class OutboundNearbyConnection: NearbyConnection {
totalBytesToSend += meta.size totalBytesToSend += meta.size
} }
} }
log("sent introduction: \(introduction)") log("[OutboundNearbyConnection] Sent introduction: \(introduction)")
try sendTransferSetupFrame(introduction) try sendTransferSetupFrame(introduction)
currentState = .sentIntroduction currentState = .sentIntroduction
@@ -411,7 +408,7 @@ class OutboundNearbyConnection: NearbyConnection {
try currentTransfer?.handle?.close() try currentTransfer?.handle?.close()
} }
if queue.isEmpty { if queue.isEmpty {
log("Disconnecting because all files have been transferred") log("[OutboundNearbyConnection] Disconnecting because all files have been transferred")
try sendDisconnectionAndDisconnect() try sendDisconnectionAndDisconnect()
delegate?.outboundConnectionTransferFinished(connection: self) delegate?.outboundConnectionTransferFinished(connection: self)
return return
@@ -470,7 +467,7 @@ class OutboundNearbyConnection: NearbyConnection {
wrapper.v1.type = .payloadTransfer wrapper.v1.type = .payloadTransfer
wrapper.v1.payloadTransfer = transfer wrapper.v1.payloadTransfer = transfer
try encryptAndSendOfflineFrame(wrapper) try encryptAndSendOfflineFrame(wrapper)
log("sent EOF, current transfer: \(String(describing: currentTransfer))") log("[OutboundNearbyConnection] Sent EOF, current transfer: \(String(describing: currentTransfer))")
} }
} }