Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions OpenParsec.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
A27110000000000000000001 /* ConnectionAttemptPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = A27110000000000000000002 /* ConnectionAttemptPolicy.swift */; };
170E0A772BEF5AFF00B0EA32 /* ParsecViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 170E0A762BEF5AFF00B0EA32 /* ParsecViewController.swift */; };
17374D412CB8E35D00EDCEE7 /* KeyCodeTranslators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17374D402CB8E35500EDCEE7 /* KeyCodeTranslators.swift */; };
17840D1D2CB639530097374B /* ParsecUserData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17840D1C2CB6394D0097374B /* ParsecUserData.swift */; };
Expand Down Expand Up @@ -59,6 +60,7 @@
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
A27110000000000000000002 /* ConnectionAttemptPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionAttemptPolicy.swift; sourceTree = "<group>"; };
170E0A762BEF5AFF00B0EA32 /* ParsecViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParsecViewController.swift; sourceTree = "<group>"; };
17374D402CB8E35500EDCEE7 /* KeyCodeTranslators.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyCodeTranslators.swift; sourceTree = "<group>"; };
17840D1C2CB6394D0097374B /* ParsecUserData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParsecUserData.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -140,6 +142,7 @@
27E61A90292965FC00FF6563 /* OpenParsec */ = {
isa = PBXGroup;
children = (
A27110000000000000000002 /* ConnectionAttemptPolicy.swift */,
E76224A02F8C017700A2F86F /* ParsecBackgroundManager.swift */,
E762250A2F8D0A0000A2F86F /* PictureInPictureManager.swift */,
17374D402CB8E35500EDCEE7 /* KeyCodeTranslators.swift */,
Expand Down Expand Up @@ -285,6 +288,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A27110000000000000000001 /* ConnectionAttemptPolicy.swift in Sources */,
FC16A7AD29A97BDA00BB70A7 /* Shared.swift in Sources */,
84480EBE2ADC4FDA007DE5F1 /* GameController.swift in Sources */,
27AC751829EA339B00E8CAF7 /* URLImage.swift in Sources */,
Expand Down
16 changes: 16 additions & 0 deletions OpenParsec/ConnectionAttemptPolicy.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
struct ConnectionAttemptPolicy {
private(set) var activePolls = 0
static let timeoutPolls = 30

mutating func tick(isActive: Bool) -> Bool {
guard isActive else { return false }
activePolls += 1
return true
}

var timedOut: Bool { activePolls >= Self.timeoutPolls }

static func shouldRetry(isPeerFailure: Bool, alreadyRetried: Bool) -> Bool {
isPeerFailure && !alreadyRetried
}
}
2 changes: 1 addition & 1 deletion OpenParsec/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ struct ContentView: View {
if let data = loadFromKeychain(key: GLBDataModel.shared.SessionKeyChainKey) {
let decoder = JSONDecoder()

print("Retrieved data from keychain: \(data).\nTrying to restore session.")
appNote("[session] restoring saved session")
NetworkHandler.clinfo = try? decoder.decode(ClientInfo.self, from: data)
if NetworkHandler.clinfo != nil {
curView = .main
Expand Down
2 changes: 2 additions & 0 deletions OpenParsec/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
<string></string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSLocalNetworkUsageDescription</key>
<string>OpenParsec connects directly to your computers on Wi-Fi to stream their desktop, audio, and controls.</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
Expand Down
2 changes: 0 additions & 2 deletions OpenParsec/LoginView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,6 @@ struct LoginView: View {

let json = try? JSONSerialization.jsonObject(with: data, options: [])
if let dict = json as? [String: Any], let isTFARequired = dict["tfa_required"] as? Bool {
print("Code output:")
print(dict)
if isTFARequired {
presentTFAAlert = true
} else {
Expand Down
46 changes: 37 additions & 9 deletions OpenParsec/MainView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ struct MainView: View {
@State var pollTimer: Timer?
@State var approvalStartedAt: Date?
@State var connectStartedAt = Date()
@State private var attemptPolicy = ConnectionAttemptPolicy()
@State private var approvalPolls = 0
@State private var showConnectionHelp = false

@State var isRefreshing: Bool = false
@State var refreshError: String?
Expand Down Expand Up @@ -365,7 +368,13 @@ struct MainView: View {
.padding(.top, -8)
.frame(maxWidth: .infinity)
.alert(isPresented: $showBaseAlert) {
Alert(title: Text(baseAlertText))
if showConnectionHelp {
return Alert(title: Text("Connection failed"), message: Text(baseAlertText),
primaryButton: .default(Text("Open App Settings"), action: {
if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
}), secondaryButton: .cancel(Text("OK")))
}
return Alert(title: Text(baseAlertText))
}

// Page controls
Expand Down Expand Up @@ -401,7 +410,10 @@ struct MainView: View {
.zIndex(1)
}
.onAppear(perform: initView)
.onDisappear { ParsecBackgroundManager.shared.onShortcutReconnect = nil }
.onDisappear {
pollTimer?.invalidate()
ParsecBackgroundManager.shared.onShortcutReconnect = nil
}
.disabled(busy) // disable view if busy

// Settings screen
Expand Down Expand Up @@ -659,6 +671,7 @@ struct MainView: View {
}

func connectTo(_ who: IdentifiableHostInfo, retried: Bool = false) {
showConnectionHelp = false
if NetworkWatcher.shared.noNetwork {
appNote("[connect] no network, not trying")
withAnimation {
Expand Down Expand Up @@ -687,8 +700,10 @@ struct MainView: View {

connectStartedAt = Date()
let status = CParsec.connect(who.id)
appNote("[connect] started, status \(status.rawValue)")
appNote("[connect] started, status \(status.rawValue), network \(NetworkWatcher.shared.interfaceDescription)")
connectPolls = 0
attemptPolicy = ConnectionAttemptPolicy()
approvalPolls = 0
approvalStartedAt = nil

// Polling status
Expand All @@ -700,6 +715,7 @@ struct MainView: View {
}

func pollConnect(_ who: IdentifiableHostInfo) {
guard isConnecting, attemptPolicy.tick(isActive: UIApplication.shared.applicationState == .active) else { return }
let status = CParsec.getStatus()
connectPolls += 1

Expand All @@ -710,7 +726,16 @@ struct MainView: View {
return
}

if status == PARSEC_CONNECTING { return } // wait
if status == PARSEC_CONNECTING {
if attemptPolicy.timedOut { retryOrGiveUp(who) }
return
}

if ConnectionAttemptPolicy.shouldRetry(isPeerFailure: status.isPeerConnectionFailure, alreadyRetried: retryingConnect) {
appNote("[connect] retrying peer setup, code \(status.rawValue)")
retryOrGiveUp(who)
return
}

if status == CONNECT_WRN_APPROVAL {
if approvalStartedAt == nil {
Expand All @@ -720,10 +745,10 @@ struct MainView: View {
return
}
}
let started = approvalStartedAt ?? Date()
approvalStartedAt = started
approvalStartedAt = approvalStartedAt ?? Date()
approvalPolls += 1
if !waitingForApproval { withAnimation { waitingForApproval = true } }
if Date().timeIntervalSince(started) < 60 { return }
if approvalPolls < 60 { return }
}

withAnimation {
Expand All @@ -740,7 +765,8 @@ struct MainView: View {
}
} else {
CParsec.disconnect()
baseAlertText = status.readable(connecting: true)
baseAlertText = status.connectionMessage(connecting: true)
showConnectionHelp = status.isPeerConnectionFailure
showBaseAlert = true
}

Expand All @@ -757,8 +783,10 @@ struct MainView: View {
withAnimation {
isConnecting = false
retryingConnect = false
waitingForApproval = false
}
baseAlertText = "\(who.hostname) didn't answer the connection request"
baseAlertText = "The host didn't answer the connection request within the retry limit. Check that it is online and that OpenParsec has Local Network access for same-Wi-Fi connections."
showConnectionHelp = true
showBaseAlert = true
}

Expand Down
4 changes: 4 additions & 0 deletions OpenParsec/NetworkHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class NetworkWatcher {
private var running = false
private var offline = false
private(set) var noNetwork = false
private(set) var interfaceDescription = "unknown"
private var known = false
private var waiting: [() -> Void] = []

Expand All @@ -24,9 +25,12 @@ class NetworkWatcher {

monitor.pathUpdateHandler = { [weak self] path in
let status = path.status
let interface = path.usesInterfaceType(.wifi) ? "Wi-Fi" : path.usesInterfaceType(.cellular) ? "cellular" : path.usesInterfaceType(.wiredEthernet) ? "Ethernet" : "other"
DispatchQueue.main.async {
guard let self = self else { return }
self.noNetwork = status == .unsatisfied
self.interfaceDescription = interface
appNote("[network] \(interface), \(status == .satisfied ? "available" : "unavailable"); LAN permission unknown")
if !self.known {
self.known = true
let runs = self.waiting
Expand Down
7 changes: 4 additions & 3 deletions OpenParsec/ParsecSDKBridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,12 @@ class ParsecSDKBridge: ParsecService {

ParsecSetLogCallback(
{ (level, msg, _) in
let line = String(cString: msg!)
os_log("%{public}@", log: sdkLog, type: .debug, "[\(level == LOG_DEBUG ? "D" : "I")] \(line)")
guard let msg = msg else { return }
let line = String(cString: msg)
// SDK payloads can contain session credentials. Never log them verbatim.
if line.contains("signal_") && line.contains("] = -") {
let at = Date()
DispatchQueue.main.async { CParsec.setupError = (line, at) }
DispatchQueue.main.async { CParsec.setupError = ("SDK signaling failed", at) }
}
}, nil)

Expand Down
4 changes: 3 additions & 1 deletion OpenParsec/ParsecView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import SwiftUI
import ParsecSDK
import Foundation
import AVFoundation
import Combine

struct ParsecStatusBar: View {
@Binding var showMenu: Bool
Expand Down Expand Up @@ -51,6 +52,7 @@ struct ParsecStatusBar: View {
}

func poll() {
guard UIApplication.shared.applicationState != .inactive else { return }
if showDCAlert || ParsecBackgroundManager.shared.isPaused {
return
}
Expand Down Expand Up @@ -135,7 +137,7 @@ struct ParsecStatusBar: View {
// silent: auto-reconnect spent its retries, dont nag with an alert
onSilentDisconnect()
} else {
DCAlertText = status.readable()
DCAlertText = status.connectionMessage()
showDCAlert = true
}
return
Expand Down
9 changes: 9 additions & 0 deletions OpenParsec/Shared.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ class DataManager {
}

extension ParsecStatus {
var isPeerConnectionFailure: Bool {
self == NAT_ERR_PEER_PHASE || self == NAT_ERR_NO_CANDIDATES || self == NAT_ERR_STUN_PHASE
}

func connectionMessage(connecting: Bool = false) -> String {
let message = "\(readable(connecting: connecting)) (code \(rawValue))."
guard isPeerConnectionFailure else { return message }
return message + "\n\nFor a host on the same Wi-Fi, allow OpenParsec in Settings → Privacy & Security → Local Network, then retry. If access is already allowed, check guest Wi-Fi/client isolation, VPN routing, and the host firewall. A working cellular connection does not confirm LAN access."
}
func readable(connecting: Bool = false) -> String {
switch self {
case WS_ERR_AUTH: return "Authentication failed"
Expand Down
25 changes: 25 additions & 0 deletions Tests/ConnectionRegressionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Foundation

@main
enum ConnectionRegressionTests {
static func main() {
var checks = 0
func check(_ condition: @autoclosure () -> Bool, _ name: String) {
precondition(condition(), "FAILED: \(name)")
checks += 1
}
var policy = ConnectionAttemptPolicy()
var paused = true
for _ in 0..<100 { paused = !policy.tick(isActive: false) && paused }
check(paused, "permission prompt pauses polling")
check(policy.activePolls == 0 && !policy.timedOut, "inactive time never consumes timeout")
for _ in 0..<29 { _ = policy.tick(isActive: true) }
check(!policy.timedOut, "attempt remains live before timeout")
_ = policy.tick(isActive: true)
check(policy.timedOut, "attempt is bounded")
check(ConnectionAttemptPolicy.shouldRetry(isPeerFailure: true, alreadyRetried: false), "first peer failure can retry")
check(!ConnectionAttemptPolicy.shouldRetry(isPeerFailure: true, alreadyRetried: true), "second failure never loops")
check(!ConnectionAttemptPolicy.shouldRetry(isPeerFailure: false, alreadyRetried: false), "permission/auth errors not peer retries")
print("Passed \(checks) connection-policy assertions.")
}
}
11 changes: 11 additions & 0 deletions Tests/run-connection-regressions.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/sh
# Connection-policy checks run on the Mac without loading the device-only Parsec SDK.
set -eu
ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
WORK="$(mktemp -d "${TMPDIR:-/tmp}/openparsec-tests.XXXXXX")"
trap 'rm -rf "$WORK"' EXIT
xcrun swiftc -sdk "$(xcrun --sdk macosx --show-sdk-path)" \
"$ROOT/OpenParsec/ConnectionAttemptPolicy.swift" \
"$ROOT/Tests/ConnectionRegressionTests.swift" -o "$WORK/regressions"
"$WORK/regressions"
/usr/bin/plutil -lint "$ROOT/OpenParsec/Info.plist" "$ROOT/OpenParsec.xcodeproj/project.pbxproj"