diff --git a/apple/Omnitun/App.swift b/apple/Omnitun/App.swift index 0c5b8ee..946c266 100644 --- a/apple/Omnitun/App.swift +++ b/apple/Omnitun/App.swift @@ -34,8 +34,15 @@ func editMenu() -> NSMenu { edit.addItem(withTitle: String(localized: "Select All"), action: #selector(NSText.selectAll(_:)), keyEquivalent: "a") let close = NSMenu(title: String(localized: "Window")) close.addItem(withTitle: String(localized: "Close"), action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w") + // Shown while a window makes the app a regular one (⌘-Tab). + let app = NSMenu(title: brand.product) + app.addItem(withTitle: String(localized: "Hide \(brand.product)"), action: #selector(NSApplication.hide(_:)), + keyEquivalent: "h") + app.addItem(.separator()) + app.addItem(withTitle: String(localized: "Quit \(brand.product)"), action: #selector(NSApplication.terminate(_:)), + keyEquivalent: "q") let main = NSMenu() - for menu in [NSMenu(title: brand.product), edit, close] { + for menu in [app, edit, close] { let item = NSMenuItem() item.submenu = menu main.addItem(item) diff --git a/apple/Omnitun/ManageView.swift b/apple/Omnitun/ManageView.swift index 8925193..d4ab91c 100644 --- a/apple/Omnitun/ManageView.swift +++ b/apple/Omnitun/ManageView.swift @@ -717,6 +717,7 @@ struct ProfileEditor: View { NetworkTab(form: $form, others: model.profiles.filter { $0.id != original }.map { ($0.id, $0.name) }, announced: original.flatMap(Settings.announced(for:))) .tabItem { Text("Network") } + ScheduleTab(form: $form).tabItem { Text("Schedule") } } .padding(.horizontal) footer @@ -2147,3 +2148,111 @@ private struct NetworkTab: View { } } + +/// Automatic disconnection: a switch for the whole, then each limit, the +/// first one reached disconnecting. Limits switched off are kept. +private struct ScheduleTab: View { + @Binding var form: ProfileForm + + var body: some View { + Form { + Section { + Toggle("Disconnect automatically", isOn: $form.disconnectEnabled) + caption("Even with the app closed: the service disconnects. You are warned 5 minutes before and can postpone.") + } + Section("Limits") { + limit("After being connected for", text: $form.disconnectAfter, initial: "8:00") { + DurationField(text: $form.disconnectAfter) + } + caption("Reconnections after a drop do not start the time again. Postponing starts it again.") + limit("After no keyboard or mouse activity for", text: $form.disconnectIdle, initial: "1:00") { + DurationField(text: $form.disconnectIdle) + } + caption("Network traffic does not count: it never stops. Using the computer again keeps the VPN up.") + limit("At", text: $form.disconnectAt, initial: "19:00") { + DatePicker("At", selection: timeOfDay, displayedComponents: .hourAndMinute).labelsHidden() + } + caption("The first time after connecting. Postponing moves it an hour later.") + if form.disconnectEnabled && noLimit { + Label("Choose at least one limit.", systemImage: "exclamationmark.triangle") + .font(.caption).foregroundStyle(.orange) + } + } + .disabled(!form.disconnectEnabled) + } + .formStyle(.grouped) + } + + private var noLimit: Bool { + form.disconnectAfter.isEmpty && form.disconnectIdle.isEmpty && form.disconnectAt.isEmpty + } + + /// A limit's checkbox, and its value once checked; unchecked, the + /// limit is removed. + private func limit(_ title: LocalizedStringKey, text: Binding, initial: String, + @ViewBuilder value: () -> some View) -> some View { + let on = Binding(get: { !text.wrappedValue.trimmingCharacters(in: .whitespaces).isEmpty }, + set: { text.wrappedValue = $0 ? initial : "" }) + return HStack { + Toggle(title, isOn: on).toggleStyle(.checkbox) + Spacer() + if on.wrappedValue { value() } + } + } + + /// The time of day of `disconnectAt`, as today's date for the picker. + private var timeOfDay: Binding { + Binding(get: { + let (h, m) = HourMinute.parse(form.disconnectAt) ?? (19, 0) + return Calendar.current.date(bySettingHour: h, minute: m, second: 0, of: Date()) ?? Date() + }, set: { date in + let c = Calendar.current.dateComponents([.hour, .minute], from: date) + form.disconnectAt = HourMinute.text(c.hour ?? 0, c.minute ?? 0) + }) + } + + private func caption(_ text: LocalizedStringKey) -> some View { + Text(text).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } +} + +/// `H:MM` text, as the profile writes it. +private enum HourMinute { + static func parse(_ text: String) -> (Int, Int)? { + let parts = text.trimmingCharacters(in: .whitespaces).split(separator: ":") + guard parts.count == 2, let h = Int(parts[0]), let m = Int(parts[1]) else { return nil } + return (h, m) + } + + static func text(_ hours: Int, _ minutes: Int) -> String { + String(format: "%d:%02d", hours, minutes) + } +} + +/// A duration in hours and minutes, never empty. +private struct DurationField: View { + @Binding var text: String + + private var parts: (Int, Int) { HourMinute.parse(text) ?? (0, 0) } + + private var hours: Binding { + Binding(get: { parts.0 }, set: { text = HourMinute.text(min(max($0, 0), 999), parts.1) }) + } + + private var minutes: Binding { + Binding(get: { parts.1 }, set: { text = HourMinute.text(parts.0, min(max($0, 0), 59)) }) + } + + var body: some View { + HStack(spacing: 4) { + TextField("Hours", value: hours, format: .number).labelsHidden().frame(width: 44) + .multilineTextAlignment(.trailing) + Stepper("Hours", value: hours, in: 0...999).labelsHidden() + Text("h") + TextField("Minutes", value: minutes, format: .number).labelsHidden().frame(width: 36) + .multilineTextAlignment(.trailing) + Stepper("Minutes", value: minutes, in: 0...59, step: 5).labelsHidden() + Text("min") + } + } +} diff --git a/apple/Omnitun/Model.swift b/apple/Omnitun/Model.swift index 3bf4f09..44060fa 100644 --- a/apple/Omnitun/Model.swift +++ b/apple/Omnitun/Model.swift @@ -59,6 +59,7 @@ final class AppModel: ObservableObject { func profile(_ id: String) -> ProfileSummary? { profiles.first { $0.id == id } } func start() { + Notifier.shared.onPostpone = { [weak self] id in self?.postpone(id) } Notifier.shared.setUp() reloadProfiles() resuming = Self.toResume(Settings.upSessions, version: Self.version, now: Date()) @@ -171,6 +172,14 @@ final class AppModel: ObservableObject { fileprivate func changed(_ change: StateChange) { retries[change.id] = change.retry + if [.disconnected, .failed].contains(change.state) { Notifier.shared.removeExpiring(id: change.id) } + // Ended by the service, not by the user: its profile's limit. + if change.state == .disconnected, change.detail != nil { + let planned = sessions[change.id]?.autoDisconnect + Notifier.shared.post(title: String(localized: "\(displayName(change.id)) disconnected automatically"), + body: planned.map(Self.reason) ?? change.detail ?? "") + return + } if change.state == .connecting || change.state == .connected { failures[change.id] = nil } // An interactive connection reports its own outcome. guard flows[change.id] == nil else { return } @@ -191,6 +200,42 @@ final class AppModel: ObservableObject { } } + /// Warns that `id` disconnects soon, as its profile says. + fileprivate func expiring(_ id: String, _ planned: PlannedDisconnect) { + let time = Date(timeIntervalSince1970: TimeInterval(planned.at)).formatted(date: .omitted, time: .shortened) + let body = switch planned.criterion { + case .after: String(localized: "Connected for \(planned.limit): it disconnects at \(time).") + case .at: String(localized: "It disconnects at \(time), as planned.") + case .idle: String(localized: "No activity for a while: it disconnects at \(time) unless you use the computer.") + } + Notifier.shared.postExpiring(id: id, title: String(localized: "\(displayName(id)) disconnects soon"), + body: body, canPostpone: planned.criterion != .idle) + objectWillChange.send() + } + + /// Why a session was disconnected automatically, for people. + nonisolated static func reason(_ planned: PlannedDisconnect) -> String { + switch planned.criterion { + case .after: String(localized: "Connected for \(planned.limit), as its settings say.") + case .idle: String(localized: "No activity for \(planned.limit), as its settings say.") + case .at: String(localized: "It is \(planned.limit), as its settings say.") + } + } + + /// Puts off `id`'s automatic disconnection. + func postpone(_ id: String) { + Notifier.shared.removeExpiring(id: id) + Task { + do { + try await client.postpone(id: id) + } catch { + Notifier.shared.post(title: String(localized: "\(displayName(id)) disconnects as planned"), + body: describe(error)) + } + pollSessions() + } + } + fileprivate func stopped(_ error: ClientError?) { subscription = nil sessions = [:] @@ -209,7 +254,13 @@ final class AppModel: ObservableObject { // MARK: Reconnecting after an update - private static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String + /// Version and build: a package of the same version built again (a + /// test build) is an update too. + private static let version: String? = { + let info = Bundle.main.infoDictionary + guard let short = info?["CFBundleShortVersionString"] as? String else { return nil } + return (info?["CFBundleVersion"] as? String).map { "\(short) (\($0))" } ?? short + }() /// What to connect again at launch: the VPNs a previous version saw up /// shortly before it stopped. A crash or a quit without an update @@ -519,6 +570,10 @@ private final class Observer: SessionObserver, @unchecked Sendable { DispatchQueue.main.async { MainActor.assumeIsolated { self.model?.holdRecord() } } } + func expiring(id: String, planned: PlannedDisconnect) { + DispatchQueue.main.async { MainActor.assumeIsolated { self.model?.expiring(id, planned) } } + } + func stopped(error: ClientError?) { DispatchQueue.main.async { MainActor.assumeIsolated { self.model?.stopped(error) } } } diff --git a/apple/Omnitun/Notifier.swift b/apple/Omnitun/Notifier.swift index 200f336..ef784fb 100644 --- a/apple/Omnitun/Notifier.swift +++ b/apple/Omnitun/Notifier.swift @@ -4,13 +4,29 @@ import UserNotifications /// User notifications; silently off when the app runs outside its bundle /// (`swift run`), where the notification center is not available. @MainActor -final class Notifier { +final class Notifier: NSObject, UNUserNotificationCenterDelegate { static let shared = Notifier() private var center: UNUserNotificationCenter? { Bundle.main.bundleIdentifier == nil ? nil : UNUserNotificationCenter.current() } + /// A disconnection to come, with a button to put it off. + private nonisolated static let expiringCategory = "expiring" + private nonisolated static let postponeAction = "postpone" + + /// Called with the profile id when the user asks to put off its + /// automatic disconnection from a notification. + var onPostpone: (String) -> Void = { _ in } + func setUp() { + if let center { + center.delegate = self + let postpone = UNNotificationAction(identifier: Self.postponeAction, + title: String(localized: "Postpone"), options: []) + center.setNotificationCategories([ + UNNotificationCategory(identifier: Self.expiringCategory, actions: [postpone], intentIdentifiers: []), + ]) + } Task { if await status() == .notDetermined { await requestAuthorization() } } @@ -39,4 +55,39 @@ final class Notifier { content.body = body center.add(UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)) } + + /// `id`'s disconnection to come; one at a time per VPN, replaced by + /// the next. `canPostpone`: with the Postpone button. + func postExpiring(id: String, title: String, body: String, canPostpone: Bool) { + guard let center else { return } + let content = UNMutableNotificationContent() + content.title = title + content.body = body + content.sound = .default + content.userInfo = ["id": id] + if canPostpone { content.categoryIdentifier = Self.expiringCategory } + center.add(UNNotificationRequest(identifier: Self.expiringIdentifier(id), content: content, trigger: nil)) + } + + /// Takes back `id`'s warning: postponed, or already disconnected. + func removeExpiring(id: String) { + center?.removeDeliveredNotifications(withIdentifiers: [Self.expiringIdentifier(id)]) + } + + private static func expiringIdentifier(_ id: String) -> String { "expiring-\(id)" } + + // MARK: UNUserNotificationCenterDelegate + + /// Shown as banners even though the menu bar app is always active. + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) + async -> UNNotificationPresentationOptions { + [.banner, .list, .sound] + } + + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse) async { + guard response.actionIdentifier == Self.postponeAction, + let id = response.notification.request.content.userInfo["id"] as? String else { return } + await MainActor.run { onPostpone(id) } + } } diff --git a/apple/Omnitun/StatusMenu.swift b/apple/Omnitun/StatusMenu.swift index efd89c6..0c1843c 100644 --- a/apple/Omnitun/StatusMenu.swift +++ b/apple/Omnitun/StatusMenu.swift @@ -16,6 +16,8 @@ final class StatusMenu: NSObject, NSMenuDelegate { /// The other ways to connect a VPN ("Connect Directly"…), and "Disconnect /// All": enabled by the sessions, which change while the menu is open. private var alternatives: [(item: NSMenuItem, id: String)] = [] + /// "Postpone Automatic Disconnection", enabled while one is planned. + private var postpones: [(item: NSMenuItem, id: String)] = [] private var disconnectAllItem: NSMenuItem? private var unavailableItem: NSMenuItem? private var header: NSMenuItem? @@ -50,6 +52,7 @@ final class StatusMenu: NSObject, NSMenuDelegate { row.setEnabled(serviceAvailable) } for (item, id) in alternatives { item.isEnabled = serviceAvailable && !model.isOn(id) } + for (item, id) in postpones { item.isEnabled = serviceAvailable && canPostpone(id) } disconnectAllItem?.isEnabled = canDisconnectAll showServiceState() for folder in folders { label(folder.item, name: folder.name, ids: folder.ids) } @@ -157,6 +160,7 @@ final class StatusMenu: NSObject, NSMenuDelegate { rows = [:] folders = [] alternatives = [] + postpones = [] let header = NSMenuItem() header.attributedTitle = headerTitle() @@ -238,7 +242,10 @@ final class StatusMenu: NSObject, NSMenuDelegate { } private func addRow(_ id: String, to target: NSMenu) { - let row = VPNRow { [weak self] on in self?.model.toggle(id, on: on) } + let row = VPNRow(onToggle: { [weak self] on in self?.model.toggle(id, on: on) }, onSettings: { [weak self] in + self?.menu.cancelTracking() + self?.afterMenu { Windows.shared.showManage(model: $0, profile: id) } + }) row.update(from: model, id: id) row.setEnabled(serviceAvailable) let item = NSMenuItem() @@ -268,6 +275,24 @@ final class StatusMenu: NSObject, NSMenuDelegate { target.addItem(split) alternatives.append((split, id)) } + // Listed for every VPN that disconnects by itself, enabled once + // the disconnection is planned. + if let profile = model.profile(id), profile.postponableDisconnect { + let postpone = action(String(localized: "Postpone Automatic Disconnection"), #selector(postpone(_:)), + symbol: "clock.arrow.circlepath") + postpone.representedObject = id + postpone.indentationLevel = 2 + postpone.isEnabled = serviceAvailable && canPostpone(id) + target.addItem(postpone) + postpones.append((postpone, id)) + } + } + + /// Up, with a disconnection planned that a request can put off. + private func canPostpone(_ id: String) -> Bool { + guard let session = model.sessions[id], session.state == .connected, + let planned = session.autoDisconnect else { return false } + return planned.criterion != .idle } /// `symbol`: every action has an icon, so that the menu reads as one @@ -287,6 +312,10 @@ final class StatusMenu: NSObject, NSMenuDelegate { if let id = sender.representedObject as? String { model.connect(id, split: true) } } + @objc private func postpone(_ sender: NSMenuItem) { + if let id = sender.representedObject as? String { model.postpone(id) } + } + @objc private func disconnectAll() { Task { await model.disconnectAll() } } @objc private func openWelcome() { afterMenu { Windows.shared.showWelcome(model: $0) } } @objc private func openSetup() { afterMenu { Windows.shared.showSetup(model: $0) } } @@ -306,27 +335,35 @@ final class StatusMenu: NSObject, NSMenuDelegate { @objc private func quit() { NSApp.terminate(nil) } } -/// A VPN in the menu: state dot, name, one line of detail, and a switch. +/// A VPN in the menu: state dot, name, one line of detail, a switch, and +/// a gear that opens its settings. final class VPNRow: NSView { private let dot = NSImageView() private let title = NSTextField(labelWithString: "") private let detail = NSTextField(labelWithString: "") private let toggle = MenuSwitch() + private let gear = PressableImage() private let onToggle: (Bool) -> Void + private let onSettings: () -> Void - init(onToggle: @escaping (Bool) -> Void) { + init(onToggle: @escaping (Bool) -> Void, onSettings: @escaping () -> Void) { self.onToggle = onToggle + self.onSettings = onSettings super.init(frame: NSRect(x: 0, y: 0, width: 320, height: 44)) title.font = .menuFont(ofSize: NSFont.systemFontSize) detail.font = .menuFont(ofSize: NSFont.smallSystemFontSize) detail.textColor = .secondaryLabelColor detail.lineBreakMode = .byTruncatingTail toggle.onPress = { [weak self] in self?.flip() } + gear.image = NSImage(systemSymbolName: "gearshape", accessibilityDescription: String(localized: "Settings")) + gear.contentTintColor = .secondaryLabelColor + gear.toolTip = String(localized: "Settings") + gear.onPress = onSettings let text = NSStackView(views: [title, detail]) text.orientation = .vertical text.alignment = .leading text.spacing = 1 - for view in [dot, text, toggle] as [NSView] { + for view in [dot, text, gear, toggle] as [NSView] { view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) } @@ -338,7 +375,10 @@ final class VPNRow: NSView { text.leadingAnchor.constraint(equalTo: dot.trailingAnchor, constant: 8), text.centerYAnchor.constraint(equalTo: centerYAnchor), text.trailingAnchor.constraint(lessThanOrEqualTo: toggle.leadingAnchor, constant: -10), - toggle.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -14), + toggle.trailingAnchor.constraint(equalTo: gear.leadingAnchor, constant: -10), + gear.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -14), + gear.centerYAnchor.constraint(equalTo: centerYAnchor), + gear.widthAnchor.constraint(equalToConstant: 16), toggle.centerYAnchor.constraint(equalTo: centerYAnchor), ]) } @@ -354,12 +394,21 @@ final class VPNRow: NSView { /// Clicking anywhere on the row, the switch included, flips the switch; /// so does releasing on it after a drag from the menu bar icon, as for /// any menu entry. - override func mouseUp(with event: NSEvent) { flip() } + /// The gear (with some margin around it) opens the VPN's settings. + override func mouseUp(with event: NSEvent) { + let point = convert(event.locationInWindow, from: nil) + if gear.frame.insetBy(dx: -5, dy: -8).contains(point) { + onSettings() + } else { + flip() + } + } /// Clicks go to the row, but VoiceOver's pointer finds the switch. override func accessibilityHitTest(_ point: NSPoint) -> Any? { guard let window else { return super.accessibilityHitTest(point) } let local = convert(window.convertPoint(fromScreen: point), from: nil) + if gear.frame.contains(local) { return gear } return toggle.frame.contains(local) ? toggle : super.accessibilityHitTest(point) } @@ -391,6 +440,12 @@ final class VPNRow: NSView { if let address = session.address { parts.append(address) } parts.append("↓ \(bytes(session.rxBytes)) ↑ \(bytes(session.txBytes))") if let since = session.connectedSince { parts.append(duration(since: since)) } + // An idle deadline moves with every input: not worth showing. + if let planned = session.autoDisconnect, planned.criterion != .idle { + let time = Date(timeIntervalSince1970: TimeInterval(planned.at)) + .formatted(date: .omitted, time: .shortened) + parts.append(String(localized: "ends at \(time)")) + } return (parts.joined(separator: " · "), .systemGreen) case .connecting: return (String(localized: "Connecting…"), .systemOrange) @@ -419,6 +474,17 @@ final class VPNRow: NSView { } } +/// The gear of a VPN row: the row takes its clicks, VoiceOver presses it. +final class PressableImage: NSImageView { + var onPress: (() -> Void)? + + override func accessibilityRole() -> NSAccessibility.Role? { .button } + override func accessibilityPerformPress() -> Bool { + onPress?() + return true + } +} + /// The switch of a VPN row. An NSSwitch in the menu of an app that is not /// frontmost (always the case for a menu bar app) is drawn grey when on, /// in a shade that depends on how its state was last set, and blue only diff --git a/apple/Omnitun/Windows.swift b/apple/Omnitun/Windows.swift index 77325bc..ee143c7 100644 --- a/apple/Omnitun/Windows.swift +++ b/apple/Omnitun/Windows.swift @@ -65,6 +65,8 @@ final class Windows { /// The settings window's tab, so that an open window can be switched. private let settingsTab = SettingsView.Selection() private var guards: [String: CloseGuard] = [:] + /// The editor of the open "Manage VPNs" window, to show another VPN in. + private weak var manageEditing: ProfileEditing? /// One window per kind (settings, welcome, import), brought forward if open. func show(_ key: String, title: String, resizable: Bool = false, @@ -82,9 +84,24 @@ final class Windows { guards[key] = shouldClose.map(CloseGuard.init) window.delegate = guards[key] named[key] = window + NotificationCenter.default.addObserver( + forName: NSWindow.willCloseNotification, object: window, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.updateActivationPolicy(closing: window) } + } + updateActivationPolicy() bringForward(window) } + /// While one of these windows is open, the app is a regular one, in the + /// Dock and in ⌘-Tab: a window gone behind another app can be found + /// again. With none, it is back to the menu bar only. + private func updateActivationPolicy(closing: NSWindow? = nil) { + let open = named.values.contains { $0 !== closing && ($0.isVisible || $0.isMiniaturized) } + let policy: NSApplication.ActivationPolicy = open || closing == nil ? .regular : .accessory + if NSApp.activationPolicy() != policy { NSApp.setActivationPolicy(policy) } + } + func close(_ key: String) { named[key]?.close() } @@ -107,7 +124,13 @@ final class Windows { /// `profile`: shown in the editor, when the window opens. func showManage(model: AppModel, profile: String? = nil) { + if let window = named["manage"], window.isVisible || window.isMiniaturized, let editing = manageEditing { + bringForward(window) + if let profile, profile != editing.selection { editing.leave { editing.select(profile) } } + return + } let editing = ProfileEditing(model: model) + manageEditing = editing if let profile { editing.select(profile) } show("manage", title: String(localized: "Manage VPNs"), resizable: true, shouldClose: editing.shouldClose) { ManageView(model: model, editing: editing) diff --git a/apple/Resources/fr.lproj/Localizable.strings b/apple/Resources/fr.lproj/Localizable.strings index 3d9d742..8ebb795 100644 --- a/apple/Resources/fr.lproj/Localizable.strings +++ b/apple/Resources/fr.lproj/Localizable.strings @@ -11,6 +11,7 @@ "Manage VPNs…" = "Gérer les VPN…"; "Settings…" = "Réglages…"; "Quit %@" = "Quitter %@"; +"Hide %@" = "Masquer %@"; "About %@" = "À propos de %@"; "Connecting…" = "Connexion…"; "Reconnecting (attempt %u/%u)…" = "Reconnexion (essai %u/%u)…"; @@ -476,3 +477,30 @@ "Added to the gateway's networks" = "Ajoutés aux réseaux de la passerelle"; "Unused while everything goes through the VPN." = "Inutilisés tant que tout passe par le VPN."; "Added when the gateway announces networks, like the route lines of an OpenVPN file." = "Ajoutés quand la passerelle annonce des réseaux, comme les lignes route d'un fichier OpenVPN."; + +/* Automatic disconnection */ +"After being connected for" = "Après une connexion de"; +"After no keyboard or mouse activity for" = "Après une inactivité clavier et souris de"; +"At" = "À"; +"Schedule" = "Horaires"; +"Disconnect automatically" = "Déconnecter automatiquement"; +"Even with the app closed: the service disconnects. You are warned 5 minutes before and can postpone." = "Même quand l'app est fermée : c'est le service qui déconnecte. Vous êtes prévenu 5 minutes avant et pouvez prolonger."; +"Limits" = "Limites"; +"Reconnections after a drop do not start the time again. Postponing starts it again." = "Les reconnexions après une coupure ne relancent pas le décompte. Prolonger le relance."; +"Network traffic does not count: it never stops. Using the computer again keeps the VPN up." = "Le trafic réseau ne compte pas : il ne s'arrête jamais. Utiliser à nouveau l'ordinateur garde le VPN."; +"The first time after connecting. Postponing moves it an hour later." = "La première fois après la connexion. Prolonger la recule d'une heure."; +"Choose at least one limit." = "Choisissez au moins une limite."; +"Hours" = "Heures"; +"Minutes" = "Minutes"; +"Postpone" = "Prolonger"; +"Postpone Automatic Disconnection" = "Reporter la déconnexion automatique"; +"ends at %@" = "fin à %@"; +"%@ disconnects soon" = "%@ va se déconnecter"; +"Connected for %@: it disconnects at %@." = "Connecté depuis %@ : déconnexion à %@."; +"It disconnects at %@, as planned." = "Déconnexion à %@, comme prévu."; +"No activity for a while: it disconnects at %@ unless you use the computer." = "Aucune activité depuis un moment : déconnexion à %@, sauf si vous utilisez l'ordinateur."; +"%@ disconnected automatically" = "%@ déconnecté automatiquement"; +"Connected for %@, as its settings say." = "Connecté depuis %@, comme le prévoient ses réglages."; +"No activity for %@, as its settings say." = "Aucune activité depuis %@, comme le prévoient ses réglages."; +"It is %@, as its settings say." = "Il est %@, comme le prévoient ses réglages."; +"%@ disconnects as planned" = "%@ se déconnectera comme prévu"; diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 319374d..30f3b41 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -52,6 +52,12 @@ enum Command { #[arg(long)] all: bool, }, + /// Put off the automatic disconnection of sessions: the time connected + /// starts again, a time of day moves an hour later. + Postpone { + #[arg(value_name = "PROFILE", required = true)] + names: Vec, + }, /// Show active sessions. Status { #[arg(long)] @@ -297,6 +303,13 @@ async fn main() -> anyhow::Result<()> { println!("{name}: disconnected"); } } + Command::Postpone { names } => { + for key in names { + let profile = store.find(&key)?; + daemon().await?.postpone(&profile.id).await?; + println!("{}: automatic disconnection postponed", profile.name); + } + } Command::Status { json } => { let sessions = daemon().await?.status().await?; if json { @@ -646,6 +659,15 @@ fn print_status(sessions: &[SessionInfo]) { .map_or(String::new(), |(at, why)| format!("; last drop {} ago: {}", ago(*at), printable(why))); row("drops", format!("{} reconnection attempt(s){last}", s.reconnects)); } + if let Some(planned) = &s.auto_disconnect { + use vpn_core::auto_disconnect::Criterion; + let why = match planned.criterion { + Criterion::After => format!("{} connected", planned.limit), + Criterion::Idle => format!("{} without activity", planned.limit), + Criterion::At => format!("at {}", planned.limit), + }; + row("disconnects", format!("in {} ({why})", elapsed(planned.at.saturating_sub(now)))); + } if let Some(detail) = &s.detail && s.state != SessionState::Connected { diff --git a/crates/daemon/src/autodisconnect.rs b/crates/daemon/src/autodisconnect.rs new file mode 100644 index 0000000..22087a8 --- /dev/null +++ b/crates/daemon/src/autodisconnect.rs @@ -0,0 +1,199 @@ +//! Sessions that end by themselves, as their profile's `auto_disconnect` +//! says: the deadlines, the time of day and the user's idle time. + +use std::time::Duration; + +use vpn_core::auto_disconnect::{AutoDisconnect, Clock, Criterion, HourMinute, POSTPONE_AT_SECS, Planned}; + +/// How often deadlines are checked, against the wall clock: a monotonic +/// timer would stop while the computer sleeps, and fire late after. +pub const TICK: Duration = Duration::from_secs(15); + +/// A session's deadlines, which `Postpone` moves. +#[derive(Debug, Default)] +pub struct Schedule { + /// `after` counts from here: the first connection, or the last + /// postponement. `None` until the tunnel has been up. + after_from: Option, + /// The time of day to disconnect at, as Unix time. + at: Option, +} + +impl Schedule { + /// The deadlines of a session first up at `connected`; later calls + /// keep them (a reconnection does not start them again). + pub fn start(&mut self, rule: &AutoDisconnect, connected: u64) { + if self.after_from.is_none() { + self.after_from = Some(connected); + self.at = rule.at.map(|time| next_time_of_day(connected, time)); + } + } + + pub fn clock(&self, now: u64, idle_secs: Option) -> Option { + Some(Clock { now, after_from: self.after_from?, at: self.at, idle_secs }) + } + + /// Puts off the deadline `planned` was for: the time connected starts + /// again, a time of day moves an hour later. Idleness ends with the + /// user's next input, not with a request: false. + pub fn postpone(&mut self, planned: &Planned, now: u64) -> bool { + match planned.criterion { + Criterion::After if self.after_from.is_some() => { + self.after_from = Some(now); + true + } + Criterion::At => match &mut self.at { + Some(at) => { + *at = (*at).max(now) + POSTPONE_AT_SECS; + true + } + None => false, + }, + _ => false, + } + } +} + +/// Why the session ended, for its last state. +pub fn reason(planned: &Planned) -> String { + match planned.criterion { + Criterion::After => format!("disconnected automatically after {} connected", planned.limit), + Criterion::Idle => format!("disconnected automatically after {} without activity", planned.limit), + Criterion::At => format!("disconnected automatically at {}", planned.limit), + } +} + +/// The first `time` of day, local time, strictly after `from` (Unix time). +pub fn next_time_of_day(from: u64, time: HourMinute) -> u64 { + let local = |day_offset: i32| -> Option { + let t = libc::time_t::try_from(from).ok()?; + // SAFETY: localtime_r and mktime only read and write `tm`, which + // lives on this stack frame; both are thread-safe. + unsafe { + let mut tm: libc::tm = std::mem::zeroed(); + if libc::localtime_r(&t, &mut tm).is_null() { + return None; + } + tm.tm_mday += day_offset; + tm.tm_hour = time.hours() as libc::c_int; + tm.tm_min = time.minutes() as libc::c_int; + tm.tm_sec = 0; + // Whether summer time applies on that day: for mktime to say. + tm.tm_isdst = -1; + u64::try_from(libc::mktime(&mut tm)).ok() + } + }; + match local(0) { + Some(today) if today > from => today, + _ => local(1).filter(|&tomorrow| tomorrow > from).unwrap_or_else(|| { + // No local time to read: UTC. + let day = from - from % 86_400; + let at = day + time.secs(); + if at > from { at } else { at + 86_400 } + }), + } +} + +/// Seconds since the last keyboard or mouse input on this computer, +/// whoever is logged in; `None` where it cannot be read. +#[cfg(target_os = "macos")] +pub async fn user_idle_secs() -> Option { + let output = tokio::process::Command::new("/usr/sbin/ioreg") + .args(["-r", "-c", "IOHIDSystem", "-d", "1", "-k", "HIDIdleTime"]) + .env_clear() + .env("LC_ALL", "C") + .kill_on_drop(true) + .output(); + let output = tokio::time::timeout(Duration::from_secs(5), output).await.ok()?.ok()?; + if !output.status.success() { + return None; + } + parse_idle(&String::from_utf8_lossy(&output.stdout)) +} + +#[cfg(not(target_os = "macos"))] +pub async fn user_idle_secs() -> Option { + None +} + +/// `"HIDIdleTime" = ` in ioreg's output. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +fn parse_idle(text: &str) -> Option { + text.lines().find_map(|line| { + let value = line.trim().strip_prefix("\"HIDIdleTime\"")?.trim().strip_prefix('=')?; + value.trim().parse::().ok().map(|ns| ns / 1_000_000_000) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use vpn_core::auto_disconnect::Criterion; + + fn hm(s: &str) -> HourMinute { + s.parse().unwrap() + } + + fn local_hour_minute(t: u64) -> (i32, i32) { + let t = t as libc::time_t; + // SAFETY: as in `next_time_of_day`. + unsafe { + let mut tm: libc::tm = std::mem::zeroed(); + libc::localtime_r(&t, &mut tm); + (tm.tm_hour, tm.tm_min) + } + } + + #[test] + fn the_next_time_of_day() { + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); + for time in ["0:00", "7:30", "12:00", "19:15", "23:59"] { + let at = next_time_of_day(now, hm(time)); + assert!(at > now && at - now <= 25 * 3600, "{time}: {at} from {now}"); + assert_eq!(local_hour_minute(at), (hm(time).hours() as i32, hm(time).minutes() as i32), "{time}"); + } + // Exactly that time: the next day's. + let at = next_time_of_day(now, hm("12:00")); + let next = next_time_of_day(at, hm("12:00")); + assert!(next > at + 22 * 3600 && next <= at + 26 * 3600); + } + + #[test] + fn deadlines_start_once_and_move_when_postponed() { + let rule = AutoDisconnect { + after: Some(hm("8:00")), + idle: Some(hm("0:30")), + at: Some(hm("19:00")), + ..Default::default() + }; + let mut schedule = Schedule::default(); + assert!(schedule.clock(100, None).is_none(), "not up yet"); + schedule.start(&rule, 1_000); + let at = schedule.at.unwrap(); + // A reconnection keeps the first connection's deadlines. + schedule.start(&rule, 5_000); + assert_eq!(schedule.clock(6_000, None).unwrap().after_from, 1_000); + + let after = Planned { at: 1_000 + 8 * 3600, criterion: Criterion::After, limit: hm("8:00") }; + assert!(schedule.postpone(&after, 20_000)); + assert_eq!(schedule.clock(20_000, None).unwrap().after_from, 20_000); + assert_eq!(schedule.at, Some(at), "only the deadline that was due moves"); + + let time = Planned { at, criterion: Criterion::At, limit: hm("19:00") }; + assert!(schedule.postpone(&time, 0)); + assert_eq!(schedule.at, Some(at + POSTPONE_AT_SECS)); + // Late (the computer slept): an hour from now. + assert!(schedule.postpone(&time, at + 7200)); + assert_eq!(schedule.at, Some(at + 7200 + POSTPONE_AT_SECS)); + + let idle = Planned { at: 0, criterion: Criterion::Idle, limit: hm("0:30") }; + assert!(!schedule.postpone(&idle, 0)); + } + + #[test] + fn idle_time_from_ioreg() { + let text = "+-o IOHIDSystem \n {\n \"HIDIdleTime\" = 7608266583\n }\n"; + assert_eq!(parse_idle(text), Some(7)); + assert_eq!(parse_idle("nothing"), None); + } +} diff --git a/crates/daemon/src/main.rs b/crates/daemon/src/main.rs index ee2a381..bf26766 100644 --- a/crates/daemon/src/main.rs +++ b/crates/daemon/src/main.rs @@ -2,6 +2,7 @@ //! create tun interfaces and change routes and DNS; users drive it with //! `omnitunctl` through a Unix socket restricted to one group. +mod autodisconnect; mod dnsproxy; mod engine; mod logfile; @@ -249,7 +250,15 @@ impl Drop for Slot { } /// Optional capabilities announced in `Hello`. -const FEATURES: &[&str] = &["watch", "shutdown", "trust_certificate", "failure_kinds", "prompt_socket", "stopping"]; +const FEATURES: &[&str] = &[ + "watch", + "shutdown", + "trust_certificate", + "failure_kinds", + "prompt_socket", + "stopping", + vpn_core::ipc::AUTO_DISCONNECT, +]; fn failed(e: anyhow::Error) -> Event { Event::Error { message: format!("{e:#}"), failure: Some(vpn_core::failure::kind_of(&e)) } @@ -279,6 +288,8 @@ async fn serve(stream: UnixStream, manager: Arc) -> anyhow::Result<()> let mut buf = zeroize::Zeroizing::new(String::new()); let mut greeted = false; let mut watching = false; + // What the client said it understands, in its hello. + let mut client_features = Vec::new(); loop { buf.zeroize(); let mut limited = (&mut lines).take(MAX_LINE as u64); @@ -309,7 +320,7 @@ async fn serve(stream: UnixStream, manager: Arc) -> anyhow::Result<()> // The version check comes first, so an outdated client or daemon // fails clearly instead of misreading messages. if !greeted { - let Request::Hello { protocol, client, version } = request else { + let Request::Hello { protocol, client, version, features } = request else { link.send(Event::error("the first request must be hello")); break; }; @@ -322,8 +333,9 @@ async fn serve(stream: UnixStream, manager: Arc) -> anyhow::Result<()> ))); break; } - tracing::debug!("client uid={uid}: {client} {version}"); + tracing::debug!("client uid={uid}: {client} {version} {features:?}"); greeted = true; + client_features = features; link.send(Event::Hello { protocol: PROTOCOL_VERSION, version: vpn_core::version(), @@ -338,12 +350,17 @@ async fn serve(stream: UnixStream, manager: Arc) -> anyhow::Result<()> Ok(()) => Event::Done, Err(e) => failed(e), }), + Request::Postpone { id } => Some(match manager.postpone(&id, uid) { + Ok(()) => Event::Done, + Err(e) => failed(e), + }), Request::Status => Some(Event::Status { sessions: manager.status(uid) }), Request::Answer { .. } => Some(Event::error("answers go to the session's prompt socket")), Request::Watch if watching => Some(Event::error("this connection is already watching")), Request::Watch => { watching = true; - manager.watch(uid, link.clone()); + let expiring = client_features.iter().any(|f| f == vpn_core::ipc::AUTO_DISCONNECT); + manager.watch(uid, link.clone(), expiring); None } Request::Shutdown => Some(if manager.may_shutdown(uid) { diff --git a/crates/daemon/src/manager.rs b/crates/daemon/src/manager.rs index c516c7a..7944373 100644 --- a/crates/daemon/src/manager.rs +++ b/crates/daemon/src/manager.rs @@ -17,6 +17,7 @@ use vpn_core::ipc::{Event, Retry, RoutedByDomain, SessionInfo, SessionState}; use vpn_core::{FailureKind, Profile, ProtocolConfig, TunnelSettings, TunnelStats, failure}; use vpn_platform::{Claims, Conflict, DynamicClaims, Registry}; +use crate::autodisconnect::{self, Schedule}; use crate::dnsproxy::{DnsProxy, Plan}; use crate::engine::{Launcher, RemoteEngine}; use crate::prompter::{ClientLink, SessionClient}; @@ -43,6 +44,9 @@ const MAX_MTU: u16 = 9000; /// A tunnel that stayed up this long resets the reconnect counter. const STABLE_UPTIME: Duration = Duration::from_secs(60); const WATCH_QUEUE: usize = 256; +/// An idle deadline drifts from one tick to the next by the time `ioreg` +/// took: within this, it is the same one. +const TICK_SLACK: u64 = 60; /// How long an engine's first question waits for the client to attach to /// the prompt socket. const ATTACH_WAIT: Duration = Duration::from_secs(10); @@ -128,6 +132,8 @@ struct Session { info: Arc>, stats: Arc, task: Option>, + /// Its automatic disconnection, if its profile has one. + schedule: Arc>, } impl Manager { @@ -206,6 +212,7 @@ impl Manager { dynamic_routes: 0, routed_by_domain: Vec::new(), announced: None, + auto_disconnect: None, })); // The engine asks the owner's client directly, on this socket. let prompt_socket = vpn_core::ipc::prompt_socket_path(&self.control_socket, &profile.id); @@ -223,6 +230,7 @@ impl Manager { let cancel = CancellationToken::new(); let stats = Arc::new(TunnelStats::default()); + let schedule = Arc::new(Mutex::new(Schedule::default())); let runner = Runner { manager: self.clone(), owner, @@ -235,9 +243,11 @@ impl Manager { prompt_socket, prompt_file, via, + schedule: schedule.clone(), + ended_by: Arc::default(), }; let task = tokio::spawn(runner.run(engine)); - sessions.insert(profile.id, Session { owner, cancel, info, stats, task: Some(task) }); + sessions.insert(profile.id, Session { owner, cancel, info, stats, task: Some(task), schedule }); Ok(()) } @@ -260,6 +270,23 @@ impl Manager { Ok(()) } + /// Puts off the automatic disconnection of a session; `uid` must own + /// it unless it is root. + pub fn postpone(&self, id: &str, uid: u32) -> anyhow::Result<()> { + let sessions = self.sessions.lock().unwrap(); + let session = + sessions.get(id).filter(|s| uid == 0 || s.owner == uid).with_context(|| format!("{id} is not active"))?; + let mut info = session.info.lock().unwrap(); + let planned = info.auto_disconnect.with_context(|| format!("{} has no disconnection planned", info.name))?; + if !session.schedule.lock().unwrap().postpone(&planned, now()) { + bail!("{} disconnects when idle: using the computer is enough to stay connected", info.name); + } + tracing::info!(session = info.name, "automatic disconnection postponed"); + // Planned again at the next tick. + info.auto_disconnect = None; + Ok(()) + } + /// Closes every session at once: the service manager kills the daemon /// if stopping takes too long, so teardowns must not queue up. /// Tells every watcher that the sessions are about to close because the @@ -289,7 +316,8 @@ impl Manager { /// Sends the current sessions, then every state change of `uid`'s /// sessions (all of them for root), until the client goes away. - pub fn watch(self: &Arc, uid: u32, link: ClientLink) { + /// `expiring`: the client understands `Expiring` events. + pub fn watch(self: &Arc, uid: u32, link: ClientLink, expiring: bool) { let mut rx = self.events.subscribe(); if !link.send(Event::Status { sessions: self.status(uid) }) { return; @@ -302,6 +330,7 @@ impl Manager { _ = link.closed() => return, }; match watched { + Ok(Watched { event: Event::Expiring { .. }, .. }) if !expiring => {} Ok(w) if uid == 0 || w.owner.is_none_or(|owner| owner == uid) => { if !link.send(w.event) { return; @@ -405,6 +434,10 @@ struct Runner { prompt_file: Option, /// The session this one is chained through. via: Option, + schedule: Arc>, + /// Why the session was ended without its user, if it was: its last + /// state says so. + ended_by: Arc>>, } /// Why a connection attempt ended. @@ -447,13 +480,20 @@ impl Runner { self.client.notify(event); } + /// Disconnected by its user, or by itself. + fn disconnected(&self) { + let reason = self.ended_by.lock().unwrap().take(); + self.set_state(SessionState::Disconnected, reason); + } + async fn run(self, mut engine: RemoteEngine) { + let deadlines = self.profile.auto_disconnect.is_active().then(|| tokio::spawn(self.deadlines())); let mut attempt = 0; loop { let first = attempt == 0 && self.info.lock().unwrap().connected_since.is_none(); match self.attempt(&mut engine, first).await { Outcome::Cancelled => { - self.set_state(SessionState::Disconnected, None); + self.disconnected(); break; } Outcome::Failed(e) => { @@ -492,7 +532,7 @@ impl Runner { ); tokio::select! { _ = self.cancel.cancelled() => { - self.set_state(SessionState::Disconnected, None); + self.disconnected(); break; } _ = tokio::time::sleep(delay) => {} @@ -500,6 +540,9 @@ impl Runner { } } } + if let Some(deadlines) = deadlines { + deadlines.abort(); + } self.client.detach(); engine.kill().await; remove_prompt_socket(&self.prompt_socket, self.prompt_file); @@ -519,6 +562,55 @@ impl Runner { } } + /// Watches the session's automatic disconnection: plans it once the + /// tunnel has been up, warns the user's clients before, and ends the + /// session when it is due. Runs until the session ends. + fn deadlines(&self) -> impl Future + Send + 'static { + let rule = self.profile.auto_disconnect.clone(); + let (manager, owner, id, name) = + (self.manager.clone(), self.owner, self.profile.id.clone(), self.profile.name.clone()); + let (info, schedule, cancel, ended_by) = + (self.info.clone(), self.schedule.clone(), self.cancel.clone(), self.ended_by.clone()); + async move { + if rule.idle.is_some() && autodisconnect::user_idle_secs().await.is_none() { + tracing::warn!(session = name, "idle time cannot be read here: no disconnection when idle"); + } + let mut tick = tokio::time::interval(autodisconnect::TICK); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + // The deadline the user was last warned of. + let mut warned: Option = None; + loop { + tick.tick().await; + let Some(connected) = info.lock().unwrap().connected_since else { continue }; + let idle = match rule.idle { + Some(_) => autodisconnect::user_idle_secs().await, + None => None, + }; + let now = now(); + let planned = { + let mut schedule = schedule.lock().unwrap(); + schedule.start(&rule, connected); + schedule.clock(now, idle).and_then(|clock| rule.next(&clock)) + }; + info.lock().unwrap().auto_disconnect = planned; + let Some(planned) = planned else { continue }; + if now >= planned.at { + let reason = autodisconnect::reason(&planned); + tracing::info!(session = name, "{reason}"); + *ended_by.lock().unwrap() = Some(reason); + cancel.cancel(); + return; + } + // Once per deadline; an idle one moves a little each tick. + if now >= planned.warning_at() && warned.is_none_or(|w| w.abs_diff(planned.at) > TICK_SLACK) { + warned = Some(planned.at); + let event = Event::Expiring { id: id.clone(), planned }; + let _ = manager.events.send(Watched { owner: Some(owner), event }); + } + } + } + } + async fn attempt(&self, engine: &mut RemoteEngine, first: bool) -> Outcome { if !engine.is_alive() { tracing::warn!(session = self.profile.name, "the engine died; starting a new one"); @@ -1168,13 +1260,21 @@ mod tests { dynamic_routes: 0, routed_by_domain: Vec::new(), announced: None, + auto_disconnect: None, }; let stats = Arc::new(TunnelStats::default()); stats.record_rx(100); stats.record_tx(40); m.sessions.lock().unwrap().insert( test_id(name), - Session { owner, cancel: cancel.clone(), info: Arc::new(Mutex::new(info)), stats, task: None }, + Session { + owner, + cancel: cancel.clone(), + info: Arc::new(Mutex::new(info)), + stats, + task: None, + schedule: Arc::default(), + }, ); cancel } @@ -1217,8 +1317,8 @@ mod tests { let m = Arc::new(Manager::default()); let (mine, mut mine_rx) = client(); let (theirs, mut theirs_rx) = client(); - m.watch(1000, mine); - m.watch(1001, theirs); + m.watch(1000, mine, true); + m.watch(1001, theirs, true); assert!(matches!(next_event(&mut mine_rx).await, Event::Status { sessions } if sessions.is_empty())); assert!(matches!(next_event(&mut theirs_rx).await, Event::Status { .. })); @@ -1236,8 +1336,8 @@ mod tests { let m = Arc::new(Manager::default()); let (mine, mut mine_rx) = client(); let (theirs, mut theirs_rx) = client(); - m.watch(1000, mine); - m.watch(1001, theirs); + m.watch(1000, mine, true); + m.watch(1001, theirs, true); assert!(matches!(next_event(&mut mine_rx).await, Event::Status { .. })); assert!(matches!(next_event(&mut theirs_rx).await, Event::Status { .. })); m.stopping(); @@ -1612,7 +1712,7 @@ mod tests { async fn a_lagging_watcher_gets_the_status_again() { let m = Arc::new(Manager::default()); let (tx, mut rx) = mpsc::channel(2 * WATCH_QUEUE); - m.watch(1000, ClientLink::new(tx)); + m.watch(1000, ClientLink::new(tx), true); assert!(matches!(rx.recv().await, Some(Event::Status { .. }))); fake_session(&m, "paris", 1000); for i in 0..WATCH_QUEUE + 10 { @@ -1823,4 +1923,54 @@ mod tests { .collect(); assert!(apply_profile(&profile, s).is_err()); } + + #[tokio::test] + async fn expiring_events_go_to_clients_that_understand_them() { + let m = Arc::new(Manager::default()); + let (new, mut new_rx) = client(); + let (old, mut old_rx) = client(); + m.watch(1000, new, true); + m.watch(1000, old, false); + assert!(matches!(next_event(&mut new_rx).await, Event::Status { .. })); + assert!(matches!(next_event(&mut old_rx).await, Event::Status { .. })); + let planned = vpn_core::auto_disconnect::Planned { + at: 1, + criterion: vpn_core::auto_disconnect::Criterion::After, + limit: "8:00".parse().unwrap(), + }; + let event = Event::Expiring { id: test_id("paris"), planned }; + let _ = m.events.send(Watched { owner: Some(1000), event }); + m.stopping(); + assert!(matches!(next_event(&mut new_rx).await, Event::Expiring { .. })); + assert!(matches!(next_event(&mut new_rx).await, Event::Stopping)); + assert!(matches!(next_event(&mut old_rx).await, Event::Stopping), "an older client would fail on it"); + } + + #[tokio::test] + async fn only_the_owner_postpones_and_idleness_is_not_postponed() { + use vpn_core::auto_disconnect::{AutoDisconnect, Criterion, Planned}; + let m = Manager::default(); + let _cancel = fake_session(&m, "paris", 1000); + assert!(m.postpone(&test_id("paris"), 1000).is_err(), "nothing planned"); + + let rule = AutoDisconnect { after: Some("8:00".parse().unwrap()), ..Default::default() }; + let plan = |criterion| Planned { at: 1_000 + 8 * 3600, criterion, limit: "8:00".parse().unwrap() }; + { + let sessions = m.sessions.lock().unwrap(); + let session = &sessions[&test_id("paris")]; + session.schedule.lock().unwrap().start(&rule, 1_000); + session.info.lock().unwrap().auto_disconnect = Some(plan(Criterion::After)); + } + assert!(m.postpone(&test_id("paris"), 1001).is_err(), "another user's session"); + m.postpone(&test_id("paris"), 1000).unwrap(); + let sessions = m.sessions.lock().unwrap(); + let session = &sessions[&test_id("paris")]; + assert_eq!(session.info.lock().unwrap().auto_disconnect, None, "planned again at the next tick"); + let after_from = session.schedule.lock().unwrap().clock(0, None).unwrap().after_from; + assert!(after_from > 1_000, "the time connected starts again"); + + session.info.lock().unwrap().auto_disconnect = Some(plan(Criterion::Idle)); + drop(sessions); + assert!(m.postpone(&test_id("paris"), 0).is_err()); + } } diff --git a/crates/vpn-client/src/daemon.rs b/crates/vpn-client/src/daemon.rs index f6bcfdf..68507c5 100644 --- a/crates/vpn-client/src/daemon.rs +++ b/crates/vpn-client/src/daemon.rs @@ -30,7 +30,12 @@ impl Daemon { let mut daemon = Self { lines: BufReader::new(read).lines(), write, version: String::new(), features: Vec::new() }; daemon - .send(&Request::Hello { protocol: PROTOCOL_VERSION, client: client.into(), version: vpn_core::version() }) + .send(&Request::Hello { + protocol: PROTOCOL_VERSION, + client: client.into(), + version: vpn_core::version(), + features: vec![vpn_core::ipc::AUTO_DISCONNECT.into()], + }) .await?; match daemon.next().await? { Event::Hello { version, features, .. } => { @@ -96,6 +101,14 @@ impl Daemon { self.until_done(Request::Disconnect { id: id.to_owned() }).await } + /// Puts off the automatic disconnection of session `id`. + pub async fn postpone(self, id: &str) -> anyhow::Result<()> { + if !self.supports(vpn_core::ipc::AUTO_DISCONNECT) { + bail!("{} {} cannot postpone a disconnection; restart it after the update", brand::DAEMON, self.version); + } + self.until_done(Request::Postpone { id: id.to_owned() }).await + } + /// Closes every session and stops the daemon (its service manager /// starts it again). pub async fn shutdown(self) -> anyhow::Result<()> { diff --git a/crates/vpn-client/src/import/ovpn.rs b/crates/vpn-client/src/import/ovpn.rs index 1ed5e30..12ea96e 100644 --- a/crates/vpn-client/src/import/ovpn.rs +++ b/crates/vpn-client/src/import/ovpn.rs @@ -592,6 +592,7 @@ fn convert(config: &Config, text: &str, notes: &mut Vec) -> anyhow::Resu allow_route_overlap: false, via: Vec::new(), exclusive: false, + auto_disconnect: Default::default(), }) } diff --git a/crates/vpn-client/src/import/wireguard.rs b/crates/vpn-client/src/import/wireguard.rs index 420faea..2f0fa60 100644 --- a/crates/vpn-client/src/import/wireguard.rs +++ b/crates/vpn-client/src/import/wireguard.rs @@ -202,6 +202,7 @@ fn convert(text: &str, base: &str, file: &str, existing: &[String]) -> anyhow::R allow_route_overlap: false, via: Vec::new(), exclusive: false, + auto_disconnect: Default::default(), }; if core.name != base { notes.push(format!("a VPN named {base} exists already: imported as {}", core.name)); diff --git a/crates/vpn-client/src/session.rs b/crates/vpn-client/src/session.rs index 13858bf..966ccef 100644 --- a/crates/vpn-client/src/session.rs +++ b/crates/vpn-client/src/session.rs @@ -266,6 +266,7 @@ async fn connect_one( | Event::OpenUrl { .. } | Event::Status { .. } | Event::Hello { .. } + | Event::Expiring { .. } | Event::Stopping => {} } } @@ -552,6 +553,7 @@ mod tests { dynamic_routes: 0, routed_by_domain: Vec::new(), announced: None, + auto_disconnect: None, }; let (company, lab, home) = (named("company", true), named("lab", false), named("home", false)); let profiles = [company.clone(), lab.clone(), home.clone()]; diff --git a/crates/vpn-core/src/auto_disconnect.rs b/crates/vpn-core/src/auto_disconnect.rs new file mode 100644 index 0000000..15477dc --- /dev/null +++ b/crates/vpn-core/src/auto_disconnect.rs @@ -0,0 +1,286 @@ +//! Automatic disconnection of a profile: after a time connected, after a +//! time without keyboard or mouse input, or at a time of day. Every limit +//! is written `H:MM`; the first one reached disconnects. + +use serde::{Deserialize, Serialize}; + +/// A duration or a time of day, written `H:MM` (`8:00`, `18:30`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct HourMinute { + minutes: u32, +} + +/// Durations above this are surely mistakes (about six weeks). +pub const MAX_HOURS: u32 = 999; + +impl HourMinute { + pub const fn new(hours: u32, minutes: u32) -> Self { + Self { minutes: hours * 60 + minutes } + } + + pub fn hours(self) -> u32 { + self.minutes / 60 + } + + pub fn minutes(self) -> u32 { + self.minutes % 60 + } + + pub fn secs(self) -> u64 { + u64::from(self.minutes) * 60 + } +} + +impl std::fmt::Display for HourMinute { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}:{:02}", self.hours(), self.minutes()) + } +} + +impl std::str::FromStr for HourMinute { + type Err = anyhow::Error; + + fn from_str(s: &str) -> anyhow::Result { + let bad = || anyhow::anyhow!("{s:?} is not a time written H:MM"); + let (hours, minutes) = s.trim().split_once(':').ok_or_else(bad)?; + let digits = |t: &str, lengths: std::ops::RangeInclusive| { + (lengths.contains(&t.len()) && t.bytes().all(|b| b.is_ascii_digit())).then(|| t.parse::().ok())? + }; + // Minutes always on two digits: `8:5` is ambiguous. + match (digits(hours, 1..=3), digits(minutes, 2..=2)) { + (Some(hours), Some(minutes)) if minutes < 60 => Ok(Self::new(hours, minutes)), + _ => Err(bad()), + } + } +} + +impl Serialize for HourMinute { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for HourMinute { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + text.parse().map_err(serde::de::Error::custom) + } +} + +/// When a profile's session ends by itself; nothing set, or off: never. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AutoDisconnect { + /// Off keeps the limits for later, without applying them. + #[serde(default = "yes", skip_serializing_if = "is_yes")] + pub enabled: bool, + /// This long after the connection; reconnections after a drop do not + /// start it again. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub after: Option, + /// This long without keyboard or mouse input on the computer (not + /// network traffic, which never stops). macOS only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub idle: Option, + /// At this time of day, local time: the first one after the connection. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub at: Option, +} + +fn yes() -> bool { + true +} + +fn is_yes(b: &bool) -> bool { + *b +} + +impl Default for AutoDisconnect { + fn default() -> Self { + Self { enabled: true, after: None, idle: None, at: None } + } +} + +impl AutoDisconnect { + /// No limit set: nothing to keep in the profile. + pub fn is_empty(&self) -> bool { + self.after.is_none() && self.idle.is_none() && self.at.is_none() + } + + /// Limits set and switched on: the session ends by itself. + pub fn is_active(&self) -> bool { + self.enabled && !self.is_empty() + } + + pub fn validate(&self) -> anyhow::Result<()> { + for (name, limit) in [("after", self.after), ("idle", self.idle)] { + match limit { + Some(l) if l.minutes == 0 => anyhow::bail!("auto_disconnect.{name} must be longer than 0:00"), + Some(l) if l.hours() > MAX_HOURS => { + anyhow::bail!("auto_disconnect.{name} must be at most {MAX_HOURS}:59") + } + _ => {} + } + } + if let Some(at) = self.at + && at.hours() >= 24 + { + anyhow::bail!("auto_disconnect.at must be a time of day, 0:00 to 23:59"); + } + Ok(()) + } +} + +/// Which limit is reached. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Criterion { + After, + Idle, + At, +} + +/// The disconnection to come: Unix time, the limit that causes it, and +/// that limit's value as set in the profile. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Planned { + pub at: u64, + pub criterion: Criterion, + pub limit: HourMinute, +} + +/// How long before a disconnection the user is told, at most: never more +/// than half the limit, so that a short idle limit does not warn at once. +pub const WARNING_LEAD_SECS: u64 = 300; + +impl Planned { + /// When to warn the user. + pub fn warning_at(&self) -> u64 { + self.at.saturating_sub(WARNING_LEAD_SECS.min(self.limit.secs() / 2)) + } +} + +/// What a session's deadlines count from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Clock { + /// Unix time. + pub now: u64, + /// `after` counts from here: the connection, or the last postponement. + pub after_from: u64, + /// The time of day `at` falls next, as Unix time, postponements added. + pub at: Option, + /// Seconds without input; `None` where it cannot be read. + pub idle_secs: Option, +} + +/// One hour more, for a postponed time of day. +pub const POSTPONE_AT_SECS: u64 = 3600; + +impl AutoDisconnect { + /// The earliest of the deadlines that apply. + pub fn next(&self, clock: &Clock) -> Option { + if !self.enabled { + return None; + } + let after = self.after.map(|limit| Planned { + at: clock.after_from.saturating_add(limit.secs()), + criterion: Criterion::After, + limit, + }); + let idle = self.idle.zip(clock.idle_secs).map(|(limit, idle)| Planned { + at: clock.now.saturating_add(limit.secs().saturating_sub(idle)), + criterion: Criterion::Idle, + limit, + }); + let at = self.at.zip(clock.at).map(|(limit, at)| Planned { at, criterion: Criterion::At, limit }); + [after, idle, at].into_iter().flatten().min_by_key(|p| p.at) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hm(s: &str) -> HourMinute { + s.parse().unwrap() + } + + #[test] + fn written_hours_and_minutes() { + assert_eq!(hm("8:00"), HourMinute::new(8, 0)); + assert_eq!(hm(" 18:30 "), HourMinute::new(18, 30)); + assert_eq!(hm("0:05").secs(), 300); + assert_eq!(hm("120:00").hours(), 120); + assert_eq!(HourMinute::new(8, 5).to_string(), "8:05"); + for bad in ["8", "8:5", "8:60", ":30", "8:", "-1:00", "8:30:00", "1000:00", "a:00", "8h30", ""] { + assert!(bad.parse::().is_err(), "{bad}"); + } + } + + #[test] + fn stored_as_text() { + #[derive(Serialize, Deserialize)] + struct T { + auto_disconnect: AutoDisconnect, + } + let t: T = toml::from_str("auto_disconnect = { after = \"8:00\", at = \"19:15\" }").unwrap(); + assert_eq!(t.auto_disconnect.after, Some(HourMinute::new(8, 0))); + assert_eq!(t.auto_disconnect.idle, None); + let text = toml::to_string(&t).unwrap(); + assert!(text.contains("after = \"8:00\"") && text.contains("at = \"19:15\""), "{text}"); + assert!(t.auto_disconnect.enabled && !text.contains("enabled"), "{text}"); + assert!(toml::from_str::("auto_disconnect = { after = \"8h\" }").is_err()); + // Switched off: the limits stay, with the switch. + let off: T = toml::from_str("auto_disconnect = { enabled = false, idle = \"1:00\" }").unwrap(); + assert!(!off.auto_disconnect.enabled && !off.auto_disconnect.is_active()); + assert!(toml::to_string(&off).unwrap().contains("enabled = false")); + } + + #[test] + fn limits_are_checked() { + let a = |after: &str, idle: &str, at: &str| AutoDisconnect { + enabled: true, + after: (!after.is_empty()).then(|| hm(after)), + idle: (!idle.is_empty()).then(|| hm(idle)), + at: (!at.is_empty()).then(|| hm(at)), + }; + assert!(a("8:00", "0:30", "23:59").validate().is_ok()); + assert!(a("0:00", "", "").validate().is_err()); + assert!(a("", "0:00", "").validate().is_err()); + assert!(a("", "", "24:00").validate().is_err()); + assert!(AutoDisconnect::default().is_empty()); + } + + #[test] + fn the_first_deadline_wins() { + let rule = AutoDisconnect { + after: Some(hm("8:00")), + idle: Some(hm("1:00")), + at: Some(hm("19:00")), + ..Default::default() + }; + let clock = Clock { now: 10_000, after_from: 1_000, at: Some(50_000), idle_secs: Some(0) }; + // Active user: the idle deadline is an hour away, before the others. + assert_eq!(rule.next(&clock), Some(Planned { at: 13_600, criterion: Criterion::Idle, limit: hm("1:00") })); + // Idle for 50 minutes: ten minutes left. + let idle = Clock { idle_secs: Some(3000), ..clock }; + assert_eq!(rule.next(&idle).unwrap().at, 10_600); + // No idle time to read: the time of day comes before 8 hours. + let unknown = Clock { idle_secs: None, ..clock }; + assert_eq!(rule.next(&unknown).unwrap().criterion, Criterion::After); + assert_eq!(rule.next(&unknown).unwrap().at, 1_000 + 8 * 3600); + let early = Clock { at: Some(20_000), ..unknown }; + assert_eq!(rule.next(&early).unwrap().criterion, Criterion::At); + assert_eq!(AutoDisconnect::default().next(&clock), None); + let off = AutoDisconnect { enabled: false, ..rule }; + assert_eq!(off.next(&clock), None); + assert!(!off.is_active() && !off.is_empty()); + } + + #[test] + fn warned_five_minutes_before_or_half_the_limit() { + let planned = Planned { at: 10_000, criterion: Criterion::After, limit: hm("8:00") }; + assert_eq!(planned.warning_at(), 9_700); + let short = Planned { at: 10_000, criterion: Criterion::Idle, limit: hm("0:04") }; + assert_eq!(short.warning_at(), 9_880); + } +} diff --git a/crates/vpn-core/src/ipc.rs b/crates/vpn-core/src/ipc.rs index 700f156..42ff9a9 100644 --- a/crates/vpn-core/src/ipc.rs +++ b/crates/vpn-core/src/ipc.rs @@ -11,11 +11,16 @@ use serde::{Deserialize, Serialize}; +use crate::auto_disconnect::Planned; use crate::{FailureKind, Profile, Prompt, brand}; /// Bumped on incompatible changes; both sides refuse a different version. pub const PROTOCOL_VERSION: u32 = 3; +/// The client feature and daemon capability of automatic disconnection: +/// `Expiring` events and `Postpone` requests. +pub const AUTO_DISCONNECT: &str = "auto_disconnect"; + pub fn socket_path() -> String { std::env::var(brand::SOCKET_ENV).unwrap_or_else(|_| brand::default_socket()) } @@ -44,6 +49,11 @@ pub enum Request { /// e.g. "omnitunctl", "Omnitun.app". client: String, version: String, + /// Events the client understands beyond those of the protocol + /// version (`auto_disconnect`): an older client, which would fail + /// on them, is not sent them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + features: Vec, }, Connect { profile: Box, @@ -66,6 +76,12 @@ pub enum Request { /// Keep the connection open and receive `State` events for every /// session of the caller, after an initial `Status`. Watch, + /// Puts off the automatic disconnection of a session: the time + /// connected starts again, a time of day moves an hour later. + /// `id`: the session's profile id. + Postpone { + id: String, + }, /// Disconnect everything and exit, so the service manager restarts the /// daemon (after an update). Root, or the owner of every session. Shutdown, @@ -75,11 +91,12 @@ pub enum Request { impl std::fmt::Debug for Request { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Request::Hello { protocol, client, version } => f + Request::Hello { protocol, client, version, features } => f .debug_struct("Hello") .field("protocol", protocol) .field("client", client) .field("version", version) + .field("features", features) .finish(), Request::Connect { profile, via } => { f.debug_struct("Connect").field("profile", profile).field("via", via).finish() @@ -87,6 +104,7 @@ impl std::fmt::Debug for Request { Request::Watch => f.write_str("Watch"), Request::Shutdown => f.write_str("Shutdown"), Request::Disconnect { id } => f.debug_struct("Disconnect").field("id", id).finish(), + Request::Postpone { id } => f.debug_struct("Postpone").field("id", id).finish(), Request::Status => f.write_str("Status"), Request::Answer { id, value } => { f.debug_struct("Answer").field("id", id).field("value", &value.as_ref().map(|_| "")).finish() @@ -133,6 +151,13 @@ pub enum Event { Status { sessions: Vec, }, + /// To watchers: session `id` disconnects by itself soon, unless + /// postponed (`Postpone`) or, for idleness, the user comes back. + /// Sent to clients that announced the `auto_disconnect` feature only. + Expiring { + id: String, + planned: Planned, + }, Done, /// To watchers: the daemon is stopping (an update, a restart). The /// sessions it closes next were not ended by their users. @@ -224,6 +249,9 @@ pub struct SessionInfo { /// What the gateway announced, before the profile's own choices. #[serde(default, skip_serializing_if = "Option::is_none")] pub announced: Option, + /// When the session disconnects by itself, if its profile says so. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto_disconnect: Option, } /// The routing a gateway announced. diff --git a/crates/vpn-core/src/l2tp.rs b/crates/vpn-core/src/l2tp.rs index 88a1456..a4c1ddd 100644 --- a/crates/vpn-core/src/l2tp.rs +++ b/crates/vpn-core/src/l2tp.rs @@ -83,6 +83,7 @@ impl L2tpProfile { allow_route_overlap: false, via: Vec::new(), exclusive: false, + auto_disconnect: Default::default(), }; ipsec.validate() } diff --git a/crates/vpn-core/src/lib.rs b/crates/vpn-core/src/lib.rs index 58169bb..0349038 100644 --- a/crates/vpn-core/src/lib.rs +++ b/crates/vpn-core/src/lib.rs @@ -2,6 +2,7 @@ //! settings handed to the platform layer, connection profiles and the //! prompt interface used for interactive authentication. +pub mod auto_disconnect; pub mod brand; /// The commit built, given by apple/package.sh (`OMNITUN_COMMIT`); absent @@ -31,6 +32,7 @@ pub mod prompt; pub mod settings; pub mod wireguard; +pub use auto_disconnect::{AutoDisconnect, HourMinute}; pub use destination::{Destination, DomainPattern}; pub use engine::{Engine, PacketIo, SessionContext, TunnelStats}; pub use failure::{CertificateInfo, Failure, FailureExt, FailureKind, failure}; diff --git a/crates/vpn-core/src/profile.rs b/crates/vpn-core/src/profile.rs index 5dc0218..e0580f2 100644 --- a/crates/vpn-core/src/profile.rs +++ b/crates/vpn-core/src/profile.rs @@ -62,6 +62,10 @@ pub struct Profile { /// it goes through excepted. The app offers to disconnect the others. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub exclusive: bool, + /// When the session ends by itself: after a time connected or idle, + /// or at a time of day. + #[serde(default, skip_serializing_if = "crate::AutoDisconnect::is_empty")] + pub auto_disconnect: crate::AutoDisconnect, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -460,6 +464,7 @@ impl Profile { if port == 0 { anyhow::bail!("invalid server port 0"); } + self.auto_disconnect.validate()?; if let ProtocolConfig::FortiSsl(FortiSslProfile { auth: FortiSslAuth::Saml { port }, .. }) = &self.protocol && *port < MIN_SAML_PORT { diff --git a/crates/vpn-ffi/src/forms.rs b/crates/vpn-ffi/src/forms.rs index f6574a6..842c89f 100644 --- a/crates/vpn-ffi/src/forms.rs +++ b/crates/vpn-ffi/src/forms.rs @@ -201,6 +201,18 @@ pub struct ProfileForm { pub folder: Option, /// A company VPN: never up at the same time as another VPN. pub exclusive: bool, + /// Automatic disconnection, each `H:MM` or empty for none: after this + /// long connected, after this long without keyboard or mouse input, + /// at this time of day. Switched off: kept, not applied. + pub disconnect_enabled: bool, + pub disconnect_after: String, + pub disconnect_idle: String, + pub disconnect_at: String, +} + +/// An `H:MM` limit as the form shows it; empty for none. +fn text_of(limit: Option) -> String { + limit.map(|l| l.to_string()).unwrap_or_default() } impl ProfileForm { @@ -337,6 +349,18 @@ impl ProfileForm { profile.allow_route_overlap = self.allow_route_overlap; profile.via = dedup(clean_list(&self.via)); profile.exclusive = self.exclusive; + let limit = |text: &str, what: &str| -> anyhow::Result> { + let text = text.trim(); + (!text.is_empty()) + .then(|| text.parse().with_context(|| format!("automatic disconnection {what}"))) + .transpose() + }; + profile.auto_disconnect = vpn_core::AutoDisconnect { + enabled: self.disconnect_enabled, + after: limit(&self.disconnect_after, "after a time connected")?, + idle: limit(&self.disconnect_idle, "when idle")?, + at: limit(&self.disconnect_at, "at a time of day")?, + }; // "Clients / Acme" means Clients/Acme. profile.folder = text(&self.folder) .map(|f| f.split('/').map(str::trim).filter(|n| !n.is_empty()).collect::>().join("/")); @@ -903,6 +927,10 @@ impl From<&Profile> for ProfileForm { via: profile.via.clone(), folder: profile.folder.clone(), exclusive: profile.exclusive, + disconnect_enabled: profile.auto_disconnect.enabled, + disconnect_after: text_of(profile.auto_disconnect.after), + disconnect_idle: text_of(profile.auto_disconnect.idle), + disconnect_at: text_of(profile.auto_disconnect.at), }; match &profile.protocol { ProtocolConfig::WireGuard(p) => { @@ -1083,6 +1111,35 @@ mod tests { assert_eq!(ProfileForm::from(&saved).client_certificate, Some("cd".repeat(32))); } + #[test] + fn automatic_disconnection_in_the_form() { + let base: Profile = toml::from_str( + "name = \"paris\"\nprotocol = \"forti-ssl\"\nhost = \"vpn.example.com\"\n\ + auto_disconnect = { after = \"8:00\", at = \"19:30\" }", + ) + .unwrap(); + let mut form = ProfileForm::from(&base); + assert!(form.disconnect_enabled); + assert_eq!((&*form.disconnect_after, &*form.disconnect_idle, &*form.disconnect_at), ("8:00", "", "19:30")); + form.disconnect_after = String::new(); + form.disconnect_idle = " 0:45 ".into(); + let profile = form.to_profile(Some(&base)).unwrap(); + assert_eq!(profile.auto_disconnect.after, None); + assert_eq!(profile.auto_disconnect.idle, Some(vpn_core::HourMinute::new(0, 45))); + assert_eq!(profile.auto_disconnect.at, Some(vpn_core::HourMinute::new(19, 30))); + // Switched off: the limits are kept, not applied. + form.disconnect_enabled = false; + let off = form.to_profile(Some(&base)).unwrap(); + assert!(!off.auto_disconnect.is_active() && off.auto_disconnect.idle.is_some()); + assert!(!ProfileForm::from(&off).disconnect_enabled); + form.disconnect_enabled = true; + form.disconnect_at = "25:00".into(); + assert!(form.to_profile(Some(&base)).is_err(), "not a time of day"); + form.disconnect_at = "7h".into(); + let error = form.to_profile(Some(&base)).unwrap_err(); + assert!(format!("{error:#}").contains("at a time of day"), "{error:#}"); + } + #[test] fn another_type_keeps_the_profile() { let base: Profile = toml::from_str( diff --git a/crates/vpn-ffi/src/lib.rs b/crates/vpn-ffi/src/lib.rs index 9c058cd..4ed1468 100644 --- a/crates/vpn-ffi/src/lib.rs +++ b/crates/vpn-ffi/src/lib.rs @@ -405,6 +405,12 @@ impl Client { Ok(on_runtime(async move { Daemon::open(CLIENT).await?.disconnect(&id).await }).await?) } + /// Puts off the automatic disconnection of session `id`: the time + /// connected starts again, a time of day moves an hour later. + pub async fn postpone(&self, id: String) -> Result<(), ClientError> { + Ok(on_runtime(async move { Daemon::open(CLIENT).await?.postpone(&id).await }).await?) + } + /// Closes every session and restarts the service. pub async fn shutdown(&self) -> Result<(), ClientError> { Ok(on_runtime(async { Daemon::open(CLIENT).await?.shutdown().await }).await?) @@ -472,6 +478,12 @@ impl Client { observer.stopping(); continue; } + Event::Expiring { id, planned } => { + observer.expiring(id.clone(), planned.into()); + if let Some(session) = sessions.iter_mut().find(|s| s.id == id) { + session.auto_disconnect = Some(planned); + } + } Event::Error { message, failure } => { return Err(vpn_core::failure(failure.unwrap_or(FailureKind::Other), message)); } @@ -516,6 +528,9 @@ pub trait SessionObserver: Send + Sync { /// The daemon is stopping (an update, a restart): the sessions that end /// next were not ended by their users. fn stopping(&self); + /// Session `id` disconnects by itself soon, unless postponed + /// (`Client::postpone`) or, when idle, the user comes back. + fn expiring(&self, id: String, planned: PlannedDisconnect); /// The daemon went away or refused; subscribe again later. fn stopped(&self, error: Option); } @@ -657,6 +672,8 @@ impl From<&vpn_core::Profile> for ProfileSummary { .iter() .map(|e| forms::ListEntry { value: e.value.to_string(), note: e.note.clone().unwrap_or_default() }) .collect(), + postponable_disconnect: p.auto_disconnect.enabled + && (p.auto_disconnect.after.is_some() || p.auto_disconnect.at.is_some()), } } } diff --git a/crates/vpn-ffi/src/types.rs b/crates/vpn-ffi/src/types.rs index 4a3fddb..576393d 100644 --- a/crates/vpn-ffi/src/types.rs +++ b/crates/vpn-ffi/src/types.rs @@ -283,6 +283,41 @@ pub struct Session { pub dynamic_routes: u32, /// What the gateway announced, before the profile's own choices. pub announced: Option, + /// When it disconnects by itself, if its profile says so. + pub auto_disconnect: Option, +} + +/// Which limit of the profile disconnects a session. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum AutoDisconnectCriterion { + /// The time connected. + After, + /// The time without keyboard or mouse input. + Idle, + /// A time of day. + At, +} + +/// An automatic disconnection to come. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct PlannedDisconnect { + /// Unix time. + pub at: u64, + pub criterion: AutoDisconnectCriterion, + /// The profile's limit, `H:MM`. + pub limit: String, +} + +impl From for PlannedDisconnect { + fn from(p: vpn_core::auto_disconnect::Planned) -> Self { + use vpn_core::auto_disconnect::Criterion; + let criterion = match p.criterion { + Criterion::After => AutoDisconnectCriterion::After, + Criterion::Idle => AutoDisconnectCriterion::Idle, + Criterion::At => AutoDisconnectCriterion::At, + }; + Self { at: p.at, criterion, limit: p.limit.to_string() } + } } /// The routing a gateway announced. @@ -321,6 +356,7 @@ impl From for Session { via: s.via, dynamic_routes: s.dynamic_routes.try_into().unwrap_or(u32::MAX), announced: s.announced.map(Into::into), + auto_disconnect: s.auto_disconnect.map(Into::into), } } } @@ -359,6 +395,9 @@ pub struct ProfileSummary { pub exclusive: bool, /// The networks of a connection in split mode; empty: no split mode. pub split_routes: Vec, + /// It disconnects by itself after a time connected or at a time of + /// day: the menu offers to postpone it. + pub postponable_disconnect: bool, } #[derive(Debug, Clone, uniffi::Record)] diff --git a/examples/profiles.toml b/examples/profiles.toml index be9ea1e..ba9d467 100644 --- a/examples/profiles.toml +++ b/examples/profiles.toml @@ -46,3 +46,8 @@ full_tunnel = true split_routes = ["10.20.0.0/16", { net = "192.168.30.12/32", note = "Printers" }, { domain = "*.office-saas.example", note = "CRM" }] dns_domains = [{ domain = "office.example", note = "Intranet" }] excluded_domains = [{ domain = "*.zoom.us", note = "Video calls" }] +# Disconnect by itself, whichever comes first (H:MM each, all optional): +# after 9 hours connected, after an hour without keyboard or mouse input +# (macOS), or at 19:30. Warned 5 minutes before; `omnitunctl postpone +# office` or the notification's button puts it off. +auto_disconnect = { after = "9:00", idle = "1:00", at = "19:30" }