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) {
if currentState != .receivingFiles {
log("Received frame in state \(currentState)...")
log("[InboundNearbyConnection] Received frame in state \(currentState)...")
}
do {
@@ -77,7 +77,7 @@ class InboundNearbyConnection: NearbyConnection {
do {
smsg = try Securemessage_SecureMessage(serializedBytes: frameData)
} 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
protocolError()
}
@@ -88,7 +88,7 @@ class InboundNearbyConnection: NearbyConnection {
}
} catch {
lastError = error
log("Error receiving frame: \(error) in state \(currentState).")
log("[InboundNearbyConnection] Error receiving frame: \(error) in state \(currentState).")
protocolError()
}
}
@@ -96,7 +96,7 @@ class InboundNearbyConnection: NearbyConnection {
override func processTransferSetupFrame(_ frame: Sharing_Nearby_Frame) throws {
if frame.hasV1 && frame.v1.hasType, case .cancel = frame.v1.type {
log("Transfer canceled")
log("[InboundNearbyConnection] Transfer canceled")
try sendDisconnectionAndDisconnect()
return
}
@@ -108,7 +108,7 @@ class InboundNearbyConnection: NearbyConnection {
case .receivedPairedKeyResult:
try processIntroductionFrame(frame)
default:
log("Unexpected connection state in processTransferSetupFrame: \(currentState)")
log("[InboundNearbyConnection] Unexpected connection state in processTransferSetupFrame: \(currentState)")
log(frame.debugDescription)
}
}
@@ -137,7 +137,7 @@ class InboundNearbyConnection: NearbyConnection {
filesToBeReceived[id]!.bytesTransferred += Int64(frame.payloadChunk.body.count)
fileInfo.progress?.completedUnitCount = filesToBeReceived[id]!.bytesTransferred
} catch {
log("Error occurred during writing file: \(error.localizedDescription)")
log("[InboundNearbyConnection] Error occurred during writing file: \(error.localizedDescription)")
throw NearbyError.protocolError(error.localizedDescription)
}
@@ -151,7 +151,7 @@ class InboundNearbyConnection: NearbyConnection {
filesToBeReceived.removeValue(forKey: id)
if filesToBeReceived.isEmpty {
log("All files received, sending disconnection frame and disconnecting.")
log("[InboundNearbyConnection] All files received, sending disconnection frame and disconnecting.")
try sendDisconnectionAndDisconnect()
}
}
@@ -175,7 +175,7 @@ class InboundNearbyConnection: NearbyConnection {
}
}
log("Received text payload. Disconnecting...")
log("[InboundNearbyConnection] Received text payload. Disconnecting...")
try sendDisconnectionAndDisconnect()
return true
}
@@ -189,7 +189,7 @@ class InboundNearbyConnection: NearbyConnection {
filesToBeReceived.removeValue(forKey: id)
SaveFilesManager.shared.registerFileFinishedDownloading(fileInfo.destinationURL)
log("Received file payload. Disconnecting...")
log("[InboundNearbyConnection] Received file payload. Disconnecting...")
try sendDisconnectionAndDisconnect()
return true
}
@@ -330,7 +330,7 @@ class InboundNearbyConnection: NearbyConnection {
try sendTransferSetupFrame(pairedEncryption)
currentState = .sentConnectionResponse
} 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) {
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)
rejectTransfer(with: .unsupportedAttachmentType)
@@ -441,7 +441,7 @@ class InboundNearbyConnection: NearbyConnection {
private func acceptTransfer(storeInTemp: Bool) {
if currentState == .disconnected {
log("Detected timeout, not accepting transfer")
log("[InboundNearbyConnection] Detected timeout, not accepting transfer")
return
}
@@ -484,7 +484,7 @@ class InboundNearbyConnection: NearbyConnection {
self.wasRejected = true
log("Rejecting transfer because of \( reason)")
log("[InboundNearbyConnection] Rejecting transfer because of \( reason)")
var frame = Sharing_Nearby_Frame()
frame.version = .v1
@@ -494,7 +494,7 @@ class InboundNearbyConnection: NearbyConnection {
try sendTransferSetupFrame(frame)
try sendDisconnectionAndDisconnect()
} catch {
log("Error \(error)")
log("[InboundNearbyConnection] Error \(error)")
protocolError()
}
}
+14 -16
View File
@@ -82,7 +82,7 @@ class NearbyConnection {
}
}
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) {
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 err == .posix(.ENOTCONN) {
@@ -112,7 +112,7 @@ class NearbyConnection {
func protocolError() {
log("Protocol error: \(String(describing: lastError))")
log("[NearbyConnection] Protocol error: \(String(describing: lastError))")
disconnect()
}
@@ -148,7 +148,7 @@ class NearbyConnection {
return
}
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.disconnect()
return
@@ -181,7 +181,7 @@ class NearbyConnection {
return
}
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.disconnect()
return
@@ -262,15 +262,13 @@ class NearbyConnection {
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))
}
func sendBytesPayload(data: Data, id: Int64) throws {
log("Sending bytes payload with ID \(id) of length \(data.count)")
var transfer = Location_Nearby_Connections_PayloadTransferFrame()
transfer.packetType = .data
transfer.payloadChunk.offset = 0
@@ -339,7 +337,7 @@ class NearbyConnection {
guard header.hasType, header.hasID else { throw NearbyError.requiredFieldMissing("payloadHeader.type|id") }
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)
}
@@ -384,11 +382,11 @@ class NearbyConnection {
}
else if offlineFrame.hasV1, offlineFrame.v1.hasType, case .keepAlive = offlineFrame.v1.type {
log("Sent keep-alive")
log("[NearbyConnection] Sent keep-alive")
sendKeepAlive(ack: true)
} else {
log("Unhandled offline frame encrypted: \(offlineFrame)")
log("[NearbyConnection] Unhandled offline frame encrypted: \(offlineFrame)")
}
}
@@ -492,7 +490,7 @@ class NearbyConnection {
func disconnect() {
log("Disconnecting from connection.")
log("[NearbyConnection] Disconnecting from connection.")
connection.stateUpdateHandler = nil
inactivityTimer?.cancel()
@@ -514,7 +512,7 @@ class NearbyConnection {
try sendFrameAsync(offlineFrame.serializedData())
}
log("Sent disconnection frame during sendDisconnectionAndDisconnect")
log("[NearbyConnection] Sent disconnection frame during sendDisconnectionAndDisconnect")
disconnect()
}
@@ -527,7 +525,7 @@ class NearbyConnection {
msg.messageData = try! alert.serializedData()
sendFrameAsync(try! msg.serializedData())
log("Sent UKEY2 alert: \(type)")
log("[NearbyConnection] Sent UKEY2 alert: \(type)")
disconnect()
}
@@ -545,7 +543,7 @@ class NearbyConnection {
try sendFrameAsync(offlineFrame.serializedData())
}
} 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 }
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.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) {
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)
}
@@ -134,11 +134,11 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
startedDeviceDiscovery = true
foundServices.removeAll()
log("Starting device discovery")
log("[NearbyConnectionManager] Starting device discovery")
if browsers.isEmpty {
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)
browser.browseResultsChangedHandler = { _, changes in
@@ -149,7 +149,7 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
case let .removed(res):
self.removeFoundDevice(service: res)
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) {
log("found service \(service)")
log("[NearbyConnectionManager] Found Service \(service)")
for interface in service.interfaces {
if case .loopback = interface.type {
log("ignoring localhost service")
return
}
}
guard let endpointID = endpointID(for: service) else { return }
log("service name is valid, endpoint ID \(endpointID)")
var foundService = FoundServiceInfo(service: service)
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) {
if currentState != .sendingFiles {
log("Received frame in state \(currentState)...")
log("[OutboundNearbyConnection] Received frame in state \(currentState)...")
}
do {
@@ -119,7 +119,7 @@ class OutboundNearbyConnection: NearbyConnection {
}
} 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 {
// do nothing
@@ -137,14 +137,12 @@ class OutboundNearbyConnection: NearbyConnection {
if frame.hasV1 && frame.v1.hasType, case .cancel = frame.v1.type {
log("Transfer canceled")
log("[OutboundNearbyConnection] Transfer canceled")
try sendDisconnectionAndDisconnect()
delegate?.outboundConnection(connection: self, failedWithError: NearbyError.canceled(reason: .userCanceled))
return
}
log(frame.debugDescription)
switch currentState {
case .sentPairedKeyEncryption:
try processPairedKeyEncryption(frame: frame)
@@ -155,7 +153,7 @@ class OutboundNearbyConnection: NearbyConnection {
case .sendingFiles:
break
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 {
log("connection response: \(frame)")
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.connectionResponse.response == .accept else { throw NearbyError.protocolError("Connection was rejected by recipient") }
@@ -347,7 +344,7 @@ class OutboundNearbyConnection: NearbyConnection {
totalBytesToSend += meta.size
}
}
log("sent introduction: \(introduction)")
log("[OutboundNearbyConnection] Sent introduction: \(introduction)")
try sendTransferSetupFrame(introduction)
currentState = .sentIntroduction
@@ -411,7 +408,7 @@ class OutboundNearbyConnection: NearbyConnection {
try currentTransfer?.handle?.close()
}
if queue.isEmpty {
log("Disconnecting because all files have been transferred")
log("[OutboundNearbyConnection] Disconnecting because all files have been transferred")
try sendDisconnectionAndDisconnect()
delegate?.outboundConnectionTransferFinished(connection: self)
return
@@ -470,7 +467,7 @@ class OutboundNearbyConnection: NearbyConnection {
wrapper.v1.type = .payloadTransfer
wrapper.v1.payloadTransfer = transfer
try encryptAndSendOfflineFrame(wrapper)
log("sent EOF, current transfer: \(String(describing: currentTransfer))")
log("[OutboundNearbyConnection] Sent EOF, current transfer: \(String(describing: currentTransfer))")
}
}