Skip to content

PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.

10.0 KB
Raw Blame
import 'dart:io';

import 'background_service_linux.dart';
import 'background_service_windows.dart';
import 'i18n.dart';

/// 构建时注入的版本号(build.sh 传 --dart-define=APP_VERSION)。
/// 用来判断后台服务是不是跟界面同一个版本。
const appVersion = String.fromEnvironment('APP_VERSION', defaultValue: 'dev');
const appBuild = String.fromEnvironment('APP_BUILD');

/// 后台服务的安装状态。
enum ServiceState {
  /// 开发构建:App 包里没有内置后台服务,只能用源码目录的脚本安装
  unavailable,

  /// 从一个随时会消失的位置运行,这时登记的自启项会指向不存在的路径:
  /// Mac 上是直接从 DMG 里打开、或被系统随机化路径(App Translocation);
  /// Windows 上是直接在压缩包里双击打开(实际运行在临时目录)。Linux 上没有这种情况
  mustMove,

  /// 尚未注册为登录项
  notInstalled,

  /// 已注册,但指向的不是当前这个 App(被移动过,或旧版脚本装的)
  stale,

  /// 已注册,launchd 中没有在运行
  stopped,

  running,
}

/// 管理随 App 一起分发的后台服务(剪贴板监听与同步进程):开机自启、崩溃自动拉起,
/// 关掉窗口也照常同步。各平台的做法不同,见 [MacBackgroundService]、
/// [WindowsBackgroundService] 与 [LinuxBackgroundService]。
abstract class BackgroundService {
  factory BackgroundService() => Platform.isWindows
      ? WindowsBackgroundService()
      : Platform.isLinux
      ? LinuxBackgroundService()
      : MacBackgroundService();

  /// App 里是否带着后台服务(开发构建没有)
  bool get available;

  /// 运行日志的位置,显示给用户看的写法
  String get displayLogPath;

  Future<ServiceState> state();

  Future<bool> launchAtLogin();

  /// Changes the next-login entry without stopping the current session.
  Future<void> setLaunchAtLogin(bool enabled);

  /// Stops this session, preserving the next-login preference.
  Future<void> stop();

  /// 注册并启动。重复调用即为修复。
  Future<void> install();

  /// 结束旧进程并按当前的 App 重新拉起。用于 App 更新后。
  Future<void> restart();

  /// 停用并取消开机自启。数据目录保留,重新启用后历史记录与配对关系都还在。
  Future<void> uninstall();

  /// 2.0.0 之前产品叫 CopySync:停掉并移除那时登记的后台服务,否则它会和新的同时监听剪贴板。
  /// 返回旧服务原先是否启用,启用过的就该接着启用新的。数据目录由新的后台服务第一次启动时挪过来
  Future<bool> removeLegacy();
}

/// Mac:后台服务内置在 `PasteFerry.app/Contents/Helpers/` 下,由界面在首次启动时
/// 注册成 launchd 的 LaunchAgent。
/// 用 LaunchAgent 而非 LaunchDaemon:剪贴板属于登录用户的会话,系统级进程访问不到。
class MacBackgroundService implements BackgroundService {
  MacBackgroundService({
    String? executable,
    String? home,
    this.serviceLabel = label,
  }) : _executable = executable ?? Platform.resolvedExecutable,
       _home = home ?? Platform.environment['HOME'] ?? '';

  static const label = 'com.pasteferry.daemon';
  final String serviceLabel;

  /// 界面 App 的 bundle ID。写进登录项,系统才知道后台服务属于哪个 App:
  /// macOS 15 的「本地网络」权限按它记账,登录项列表里也显示成 PasteFerry。
  static const _appBundleId = 'com.pasteferry.app';

  final String _executable;
  final String _home;

  /// `…/PasteFerry.app`,由可执行文件 `…/PasteFerry.app/Contents/MacOS/PasteFerry` 上溯三级。
  String get _bundle => File(_executable).parent.parent.parent.path;

  String get helperApp => '$_bundle/Contents/Helpers/PasteFerryDaemon.app';
  String get helperBinary => '$helperApp/Contents/MacOS/pasteferryd';
  String get plistPath => '$_home/Library/LaunchAgents/$serviceLabel.plist';
  String get logPath => '$_home/Library/Logs/PasteFerry/daemon.log';
  String get runtimePath =>
      '$_home/Library/Application Support/PasteFerry/daemon.plist';

  @override
  String get displayLogPath =>
      logPath.replaceFirst(RegExp(r'^/Users/[^/]+'), '~');

  /// 旧版 install.sh 装在这里,迁移时清理掉
  String get _legacyApp => '$_home/Applications/CopySyncDaemon.app';

  @override
  bool get available => Platform.isMacOS && File(helperBinary).existsSync();

  bool get _runningFromTemporaryLocation =>
      _bundle.startsWith('/Volumes/') || _bundle.contains('/AppTranslocation/');

  @override
  Future<ServiceState> state() async {
    if (!available) return ServiceState.unavailable;
    if (_runningFromTemporaryLocation) return ServiceState.mustMove;
    final r = await Process.run('launchctl', ['print', await _target()]);
    final file = File(runtimePath).existsSync()
        ? File(runtimePath)
        : File(plistPath);
    if (!file.existsSync()) return ServiceState.notInstalled;
    if (!(await file.readAsString()).contains(_xml(helperBinary))) {
      return ServiceState.stale;
    }
    return r.exitCode == 0 && '${r.stdout}'.contains('state = running')
        ? ServiceState.running
        : ServiceState.stopped;
  }

  @override
  Future<bool> launchAtLogin() async => File(plistPath).existsSync();

  @override
  Future<void> setLaunchAtLogin(bool enabled) async {
    final file = File(plistPath);
    if (enabled) {
      await file.parent.create(recursive: true);
      await file.writeAsString(_plist());
    } else if (await file.exists()) {
      await file.delete();
    }
  }

  @override
  Future<void> stop() async {
    final before = await Process.run('launchctl', ['print', await _target()]);
    final pid = RegExp(
      r'^\s*pid = (\d+)',
      multiLine: true,
    ).firstMatch('${before.stdout}')?.group(1);
    await _bootout();
    if (pid != null) {
      for (var i = 0; i < 40; i++) {
        if ((await Process.run('kill', ['-0', pid])).exitCode != 0) break;
        await Future<void>.delayed(const Duration(milliseconds: 250));
      }
      if ((await Process.run('kill', ['-0', pid])).exitCode == 0) {
        throw ServiceException('The background process did not stop.');
      }
    }
    if ((await Process.run('launchctl', ['print', await _target()])).exitCode ==
        0) {
      throw ServiceException('The background service did not stop.');
    }
  }

  @override
  Future<void> install() async {
    await _bootout();

    final legacy = Directory(_legacyApp);
    if (await legacy.exists()) await legacy.delete(recursive: true);

    // 用户打开 App 时已经放行过整个包,内置的后台服务不该再被隔离属性拦下:
    // launchd 拉起它时没有任何弹窗可以让用户确认
    await Process.run('xattr', ['-dr', 'com.apple.quarantine', helperApp]);

    await Directory(File(plistPath).parent.path).create(recursive: true);
    await Directory(File(logPath).parent.path).create(recursive: true);
    await File(runtimePath).parent.create(recursive: true);
    await File(runtimePath).writeAsString(_plist());
    if (await launchAtLogin()) await setLaunchAtLogin(true);

    final r = await Process.run('launchctl', [
      'bootstrap',
      await _domain(),
      runtimePath,
    ]);
    if (r.exitCode != 0) {
      throw ServiceException(appL10n.errServiceStart('${r.stderr}'.trim()));
    }
  }

  /// 让 launchd 结束旧进程并按当前的 App 重新拉起。用于 App 更新后。
  @override
  Future<void> restart() async {
    final r = await Process.run('launchctl', [
      'kickstart',
      '-k',
      await _target(),
    ]);
    if (r.exitCode != 0) {
      throw ServiceException(appL10n.errServiceRestart('${r.stderr}'.trim()));
    }
  }

  /// 停用并移除登录项。数据目录保留,重新启用后历史记录与配对关系都还在。
  @override
  Future<void> uninstall() async {
    await stop();
    await setLaunchAtLogin(false);
    final runtime = File(runtimePath);
    if (await runtime.exists()) await runtime.delete();
    final plist = File(plistPath);
    if (await plist.exists()) await plist.delete();
  }

  @override
  Future<bool> removeLegacy() async {
    final plist = File('$_home/Library/LaunchAgents/com.copysync.daemon.plist');
    if (!await plist.exists()) return false;
    await _bootout('${await _domain()}/com.copysync.daemon');
    await plist.delete();
    return true;
  }

  Future<void> _bootout([String? target]) async {
    target ??= await _target();
    await Process.run('launchctl', ['bootout', target]);
    // bootout 是异步的:旧服务没注销干净就 bootstrap 会报 "Bootstrap failed: 5"
    for (var i = 0; i < 20; i++) {
      final r = await Process.run('launchctl', ['print', target]);
      if (r.exitCode != 0) return;
      await Future<void>.delayed(const Duration(milliseconds: 250));
    }
  }

  String? _uid;
  Future<String> _domain() async {
    _uid ??= '${(await Process.run('id', ['-u'])).stdout}'.trim();
    return 'gui/$_uid';
  }

  Future<String> _target() async => '${await _domain()}/$serviceLabel';

  String _plist() =>
      '''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>              <string>$serviceLabel</string>
    <key>ProgramArguments</key>
    <array>
        <string>${_xml(helperBinary)}</string>
    </array>
    <key>RunAtLoad</key>          <true/>
    <key>KeepAlive</key>          <true/>
    <key>ThrottleInterval</key>   <integer>10</integer>
    <key>StandardOutPath</key>    <string>${_xml(logPath)}</string>
    <key>StandardErrorPath</key>  <string>${_xml(logPath)}</string>
    <key>ProcessType</key>        <string>Interactive</string>
    <key>AssociatedBundleIdentifiers</key>
    <array>
        <string>$_appBundleId</string>
    </array>
</dict>
</plist>
''';

  static String _xml(String s) => s
      .replaceAll('&', '&amp;')
      .replaceAll('<', '&lt;')
      .replaceAll('>', '&gt;');
}

class ServiceException implements Exception {
  ServiceException(this.message);
  final String message;
  @override
  String toString() => message;
}