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.

feat(server): 支持在 Windows 与 Mac 上一键部署服务器

baiyuze4e0f0b923f7f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e611339..451c572 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -73,6 +73,9 @@ jobs:
# 单独列出剪贴板测试的每一条:没有交互式桌面时它们会跳过,要看得出来
- run: go test -v -count=1 -run Windows ./internal/clipboard/
working-directory: client-core
+ # 服务器也能装在 Windows 上,作为系统服务运行
+ - run: go vet ./... ; if ($LASTEXITCODE) { exit 1 } ; go test ./...
+ working-directory: server
- uses: subosito/flutter-action@v2
with:
channel: stable
diff --git a/scripts/package.sh b/scripts/package.sh
index 2478fe0..1d787b8 100755
--- a/scripts/package.sh
+++ b/scripts/package.sh
@@ -4,7 +4,8 @@
# CopySync.dmg macOS 客户端,Intel 与 Apple 芯片通用
# copysync-server-linux-amd64.tar.gz 信令服务器 + systemd / Docker 部署文件
# copysync-server-linux-arm64.tar.gz
-# copysync-server-macos.tar.gz 把服务器放在其中一台 Mac 上时用
+# copysync-server-macos.tar.gz 把服务器放在其中一台 Mac 上时用(LaunchAgent 安装脚本)
+# copysync-server-windows-amd64.zip 把服务器放在 Windows 电脑上时用(注册为系统服务)
#
# Windows 的安装程序与便携版(CopySync-Setup.exe、CopySync-windows-x64.zip)只能在 Windows 上
# 构建:由 CI 的 Windows 任务运行 scripts/build-windows.ps1 产出,发布时从构建产物里取。
@@ -18,7 +19,7 @@
set -euo pipefail
cd "$(dirname "$0")/.."
-export VERSION=${VERSION:-1.3.2}
+export VERSION=${VERSION:-1.3.3}
OUT=release
./scripts/build.sh
@@ -111,9 +112,22 @@ done
name="copysync-server-macos"
mkdir -p "$STAGE/$name"
cp dist/copysync-server server/deploy/README.md "$STAGE/$name/"
+cp server/deploy/install-macos.sh "$STAGE/$name/install.sh"
tar -C "$STAGE" -czf "$OUT/$name.tar.gz" "$name"
echo " ✓ $name.tar.gz"
+# Windows 用 zip:系统自带解压。install.ps1 与 .cmd 必须保持带 BOM 的 UTF-8 与 CRLF,原样拷贝
+name="copysync-server-windows-amd64"
+d="$STAGE/$name"
+mkdir -p "$d"
+(cd server && CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -trimpath \
+ -ldflags "-s -w -X main.version=$VERSION" \
+ -o "$d/copysync-server.exe" ./cmd/copysync-server)
+cp server/deploy/{install.ps1,install.cmd,uninstall.cmd,README.md} "$d/"
+zip_out="$PWD/$OUT/$name.zip"
+(cd "$STAGE" && zip -qr -X "$zip_out" "$name")
+echo " ✓ $name.zip"
+
(cd "$OUT" && shasum -a 256 -- * > SHA256SUMS)
echo
diff --git a/server/cmd/copysync-server/logfile.go b/server/cmd/copysync-server/logfile.go
new file mode 100644
index 0000000..844e347
--- /dev/null
+++ b/server/cmd/copysync-server/logfile.go
@@ -0,0 +1,77 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "sync"
+)
+
+// 日志文件超过这个大小就换新,旧的改名为 .1:作为系统服务常年运行,不能把磁盘写满。
+const maxLogBytes = 10 << 20
+
+// logFile 是按大小轮换的日志文件,只保留上一份。
+type logFile struct {
+ mu sync.Mutex
+ path string
+ f *os.File
+ size int64
+}
+
+func openLog(path string) (*logFile, error) {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return nil, err
+ }
+ l := &logFile{path: path}
+ if err := l.open(); err != nil {
+ return nil, err
+ }
+ if l.size >= maxLogBytes {
+ if err := l.rotate(); err != nil {
+ l.f.Close()
+ return nil, err
+ }
+ }
+ return l, nil
+}
+
+func (l *logFile) open() error {
+ f, err := os.OpenFile(l.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+ if err != nil {
+ return err
+ }
+ fi, err := f.Stat()
+ if err != nil {
+ f.Close()
+ return err
+ }
+ l.f, l.size = f, fi.Size()
+ return nil
+}
+
+// rotate 把当前文件改名为 .1 并重新打开。Windows 上不能改名打开着的文件,所以先关。
+func (l *logFile) rotate() error {
+ l.f.Close()
+ if err := os.Rename(l.path, l.path+".1"); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ return l.open()
+}
+
+func (l *logFile) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if l.size+int64(len(p)) > maxLogBytes {
+ if err := l.rotate(); err != nil {
+ return 0, err
+ }
+ }
+ n, err := l.f.Write(p)
+ l.size += int64(n)
+ return n, err
+}
+
+func (l *logFile) Close() error {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.f.Close()
+}
diff --git a/server/cmd/copysync-server/logfile_test.go b/server/cmd/copysync-server/logfile_test.go
new file mode 100644
index 0000000..95c0e90
--- /dev/null
+++ b/server/cmd/copysync-server/logfile_test.go
@@ -0,0 +1,58 @@
+package main
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestLogFileRotates(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "sub", "server.log")
+ l, err := openLog(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+
+ line := bytes.Repeat([]byte("x"), 1<<20)
+ for range 10 {
+ if _, err := l.Write(line); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // 第 11 MB 写不下,先轮换
+ if _, err := l.Write([]byte("new\n")); err != nil {
+ t.Fatal(err)
+ }
+
+ old, err := os.Stat(path + ".1")
+ if err != nil {
+ t.Fatal("没有轮换出 .1:", err)
+ }
+ if old.Size() != 10<<20 {
+ t.Errorf(".1 的大小 = %d,应为 10 MB", old.Size())
+ }
+ cur, _ := os.ReadFile(path)
+ if string(cur) != "new\n" {
+ t.Errorf("新文件内容 = %q", cur)
+ }
+}
+
+func TestLogFileRotatesOversizedOnOpen(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "server.log")
+ if err := os.WriteFile(path, bytes.Repeat([]byte("x"), maxLogBytes), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ l, err := openLog(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+ if l.size != 0 {
+ t.Errorf("打开已满的日志后 size = %d,应先轮换", l.size)
+ }
+ if _, err := os.Stat(path + ".1"); err != nil {
+ t.Error("没有轮换出 .1:", err)
+ }
+}
diff --git a/server/cmd/copysync-server/main.go b/server/cmd/copysync-server/main.go
index 7a82540..26f6712 100644
--- a/server/cmd/copysync-server/main.go
+++ b/server/cmd/copysync-server/main.go
@@ -13,6 +13,7 @@ import (
"errors"
"flag"
"fmt"
+ "io"
"log/slog"
"net/http"
"os"
@@ -38,6 +39,9 @@ func main() {
turnPort = flag.Int("turn-port", 3478, "TURN 监听端口")
turnSecret = flag.String("turn-secret", "",
"TURN 凭证派生密钥。留空自动生成(重启后已签发的凭证失效)")
+ logPath = flag.String("log", "",
+ "日志写到这个文件,超过 10 MB 换新。默认输出到标准错误;作为 Windows 服务运行时默认写到 "+
+ `%ProgramData%\CopySync Server\server.log`)
verbose = flag.Bool("v", false, "输出调试日志")
showVersion = flag.Bool("version", false, "打印版本号后退出")
)
@@ -48,11 +52,27 @@ func main() {
return
}
+ // 由 Windows 服务管理器启动时没有控制台,日志只能写文件
+ service := isService()
+ if *logPath == "" && service {
+ *logPath = defaultServiceLog()
+ }
+ var out io.Writer = os.Stderr
+ if *logPath != "" {
+ f, err := openLog(*logPath)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "打开日志文件:", err)
+ os.Exit(1)
+ }
+ defer f.Close()
+ out = f
+ }
+
level := slog.LevelInfo
if *verbose {
level = slog.LevelDebug
}
- log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level}))
+ log := slog.New(slog.NewTextHandler(out, &slog.HandlerOptions{Level: level}))
slog.SetDefault(log)
cfg := serverConfig{
@@ -62,7 +82,15 @@ func main() {
turnPort: *turnPort,
turnSecret: *turnSecret,
}
- if err := run(cfg, log); err != nil {
+ var err error
+ if service {
+ err = runService(cfg, log)
+ } else {
+ ctx, stop := ossignal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ err = run(ctx, cfg, log)
+ stop()
+ }
+ if err != nil {
log.Error("服务器退出", "err", err)
os.Exit(1)
}
@@ -76,10 +104,8 @@ type serverConfig struct {
turnSecret string
}
-func run(cfg serverConfig, log *slog.Logger) error {
- ctx, stop := ossignal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
- defer stop()
-
+// run 运行服务器,直到 ctx 取消。
+func run(ctx context.Context, cfg serverConfig, log *slog.Logger) error {
stun := splitNonEmpty(cfg.stunURLs)
// TURN 中转:P2P 打洞失败时兜底。它只转发 UDP 包,看不到 DTLS 内层明文。
diff --git a/server/cmd/copysync-server/service_other.go b/server/cmd/copysync-server/service_other.go
new file mode 100644
index 0000000..965925b
--- /dev/null
+++ b/server/cmd/copysync-server/service_other.go
@@ -0,0 +1,13 @@
+//go:build !windows
+
+package main
+
+import "log/slog"
+
+// 只有 Windows 有服务管理器;其他系统用 systemd、launchd 直接运行可执行文件。
+
+func isService() bool { return false }
+
+func defaultServiceLog() string { return "" }
+
+func runService(serverConfig, *slog.Logger) error { return nil }
diff --git a/server/cmd/copysync-server/service_windows.go b/server/cmd/copysync-server/service_windows.go
new file mode 100644
index 0000000..0bd1100
--- /dev/null
+++ b/server/cmd/copysync-server/service_windows.go
@@ -0,0 +1,63 @@
+package main
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "path/filepath"
+
+ "golang.org/x/sys/windows/svc"
+)
+
+// 与 server/deploy/install.ps1 注册的服务名一致
+const serviceName = "CopySyncServer"
+
+// isService 判断是否由 Windows 服务管理器启动。
+func isService() bool {
+ ok, err := svc.IsWindowsService()
+ return err == nil && ok
+}
+
+func defaultServiceLog() string {
+ return filepath.Join(os.Getenv("ProgramData"), "CopySync Server", "server.log")
+}
+
+// runService 在服务管理器下运行,收到停止或关机通知时退出。
+func runService(cfg serverConfig, log *slog.Logger) error {
+ return svc.Run(serviceName, &service{cfg: cfg, log: log})
+}
+
+type service struct {
+ cfg serverConfig
+ log *slog.Logger
+}
+
+func (s *service) Execute(_ []string, req <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() { done <- run(ctx, s.cfg, s.log) }()
+ status <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown}
+
+ for {
+ select {
+ case err := <-done:
+ if err != nil {
+ // 端口被占用之类:以非零退出码结束,服务管理器按安装时设置的恢复策略重启
+ s.log.Error("服务器退出", "err", err)
+ return true, 1
+ }
+ return false, 0
+ case c := <-req:
+ switch c.Cmd {
+ case svc.Interrogate:
+ status <- c.CurrentStatus
+ case svc.Stop, svc.Shutdown:
+ status <- svc.Status{State: svc.StopPending}
+ cancel()
+ <-done
+ return false, 0
+ }
+ }
+ }
+}
diff --git a/server/deploy/.gitattributes b/server/deploy/.gitattributes
new file mode 100644
index 0000000..89948d6
--- /dev/null
+++ b/server/deploy/.gitattributes
@@ -0,0 +1,4 @@
+# Windows 脚本按原样提交,不做换行转换:install.ps1 要保持带 BOM 的 UTF-8 与 CRLF,
+# 否则 Windows PowerShell 5.1 会把中文读成乱码
+*.ps1 -text
+*.cmd -text
diff --git a/server/deploy/README.md b/server/deploy/README.md
index 7a9e6b6..72f0ab5 100644
--- a/server/deploy/README.md
+++ b/server/deploy/README.md
@@ -4,74 +4,121 @@ The server only does two things: it lets your devices find each other (signaling
CopySync 的服务器只做两件事:让你的设备找到彼此(信令),以及在设备之间打不通直连时转发加密后的数据(TURN 中转)。它不存账号,也看不到你复制的内容。
-## Requirements / 需要准备
+Step-by-step guide with screenshots / 带截图的图文教程:
+<https://baiyuze.github.io/copysync/server/>
-- A machine both devices can reach. On a LAN, one of your Macs will do.
-- Across the internet it needs a public IP, with these ports open:
+## Where to run it / 放在哪里
-一台两端设备都能访问到的机器,同一局域网内用其中一台 Mac 也行;跨公网使用时需要公网 IP,并放行以下端口:
+| | Requirement 要求 |
+|---|---|
+| **On your LAN** 局域网 | Any always-on Windows 10/11, macOS 13+ or Linux computer on the same network, one of your own computers included. Reserve its address in the router. 同一网络里任意一台常开的 Windows 10/11、macOS 13 以上或 Linux 电脑,自己的电脑也行;在路由器里给它固定地址。 |
+| **Across the internet** 跨公网 | A Linux machine with a public IP; the smallest VPS is enough. 一台有公网 IP 的 Linux 机器,最低配的云主机就够。 |
+
+It uses about 15 MB of RAM. 内存占用约 15 MB。
| Port 端口 | Protocol 协议 | Purpose 用途 |
|---|---|---|
| 8787 | TCP | Signaling (WebSocket) 信令 |
| 3478 | UDP | STUN / TURN |
-| 32768–60999 | UDP | TURN relay ports, assigned by the OS / 中转端口,系统随机分配 |
+| 32768–60999 (Linux), 49152–65535 (Windows, macOS) | UDP | TURN relay ports, assigned by the OS / 中转端口,系统随机分配 |
+
+The install scripts below find the computer's LAN address, enable the TURN relay on it, register the server to start automatically, and print the address to enter in the apps. Running a script again upgrades in place and keeps your settings.
+
+下面的安装脚本会找到本机的局域网地址并在它上面启用 TURN 中转、把服务器设为自动运行,最后打印出客户端要填的地址。重复运行即为升级,原来的设置保留。
+
+## Windows
+
+Download `copysync-server-windows-amd64.zip`, extract it, and double-click `install.cmd` (it asks for administrator rights).
+
+下载 `copysync-server-windows-amd64.zip`,解压后双击 `install.cmd`(会请求管理员权限)。
-Uses about 15 MB of RAM; the smallest VPS is enough. 内存占用约 15 MB,1 核 512 MB 的机器足够。
+- Runs as the Windows service `CopySyncServer` under the low-privilege LOCAL SERVICE account, starts with Windows and restarts after failures. 以低权限的 LOCAL SERVICE 账户注册为 Windows 服务 `CopySyncServer`,开机启动,出错后自动重启。
+- Adds a Windows Firewall rule for `copysync-server.exe` only. 在 Windows 防火墙里只为 `copysync-server.exe` 添加一条入站规则。
+- Wrong address picked? Run `install.cmd 192.168.1.20` with yours. 认错了地址就运行 `install.cmd 192.168.1.20`,换成你的地址。
-## Option 1: systemd (recommended) / 方式一:systemd(推荐)
+| | |
+|---|---|
+| Program 程序 | `C:\Program Files\CopySync Server` |
+| Settings 设置 | `C:\ProgramData\CopySync Server\server.conf` (administrators only 仅管理员可读) |
+| Logs 日志 | `C:\ProgramData\CopySync Server\server.log` |
+| Restart 重启 | `Restart-Service CopySyncServer` (administrator PowerShell 管理员 PowerShell) |
+| Uninstall 卸载 | double-click `uninstall.cmd` 双击 `uninstall.cmd` |
+
+## macOS
+
+```bash
+tar xzf copysync-server-macos.tar.gz
+cd copysync-server-macos
+./install.sh # or ./install.sh 192.168.1.20
+```
+
+No administrator rights needed: it registers a LaunchAgent that runs whenever you're logged in. Keep that Mac awake. If the macOS firewall is on, the script prints the command to allow the server through it.
+
+不需要管理员权限:注册为 LaunchAgent,登录后自动运行。这台 Mac 不能睡眠。开着系统防火墙时,脚本最后会给出放行命令。
+
+| | |
+|---|---|
+| Logs 日志 | `~/Library/Logs/CopySync/server.log` |
+| Restart 重启 | `launchctl kickstart -k gui/$(id -u)/com.copysync.server` |
+| Uninstall 卸载 | `./install.sh uninstall` |
+
+## Linux: systemd (recommended) / Linux:systemd(推荐)
```bash
tar xzf copysync-server-linux-amd64.tar.gz
cd copysync-server-linux-amd64
-sudo ./install.sh <public IP / 公网IP>
+sudo ./install.sh # on a LAN: uses this machine's LAN address / 局域网:用本机的局域网地址
+sudo ./install.sh <public IP> # on a cloud server / 云服务器:填公网 IP
```
-The script installs the binary to `/usr/local/bin`, writes `/etc/copysync/server.env` with a random TURN secret, and registers a systemd service that starts on boot. Running it again upgrades in place and keeps your config.
+The script installs the binary to `/usr/local/bin`, writes `/etc/copysync/server.env` with a random TURN secret, and registers a systemd service that starts on boot. If ufw or firewalld is active, it prints the commands to open the ports.
-脚本会把程序装到 `/usr/local/bin`,生成配置 `/etc/copysync/server.env`(含随机的 TURN 密钥),注册为开机自启的 systemd 服务。重复执行即为升级,已有配置不会被覆盖。
+脚本会把程序装到 `/usr/local/bin`,生成配置 `/etc/copysync/server.env`(含随机的 TURN 密钥),注册为开机自启的 systemd 服务。开着 ufw 或 firewalld 时,最后会给出放行端口的命令。
```bash
journalctl -u copysync-server -f # logs / 日志
-systemctl restart copysync-server # restart after editing config / 改完配置后重启
+systemctl restart copysync-server # restart after editing the config / 改完配置后重启
copysync-server -version # version / 版本
+sudo ./install.sh uninstall # uninstall / 卸载
```
-## Option 2: Docker / 方式二:Docker
+On a cloud server, also open the ports above in the provider's security group. 云服务器还要在安全组里放行上面的端口。
+
+## Linux: Docker / Linux:Docker
```bash
cp env.example .env # set TURN_IP and TURN_SECRET / 填入 TURN_IP 与 TURN_SECRET
docker compose up -d
```
-`network_mode: host` is required (already set in the compose file): TURN assigns a random UDP port per session, which port mapping can't expose.
+`network_mode: host` is required (already set in the compose file): TURN assigns a random UDP port per session, which port mapping can't expose. For the same reason Docker Desktop on Mac or Windows won't work; use the install scripts there.
-必须使用 `network_mode: host`(compose 文件里已经写好):TURN 为每个会话随机分配 UDP 端口,端口映射模式下这些端口不可达。
+必须使用 `network_mode: host`(compose 文件里已经写好):TURN 为每个会话随机分配 UDP 端口,端口映射模式下这些端口不可达。同样的原因,Mac 与 Windows 上的 Docker Desktop 不适用,请用安装脚本。
-## Option 3: run it directly / 方式三:直接运行
+## Run it directly / 直接运行
```bash
-./copysync-server -addr :8787 -turn-ip <public IP> -turn-secret <random string>
+./copysync-server -addr :8787 -turn-ip <address> -turn-secret <random string>
```
-On a LAN you can omit `-turn-ip`; relaying won't be available. 只在局域网内使用、不需要中转时,`-turn-ip` 可以省略。
+`-turn-ip` is the address clients use to reach the relay: the LAN address on a LAN, the public IP on a cloud server. Without it there is no relay. `-log <file>` writes the log to a file instead of standard error. Run `copysync-server -h` for all options.
+
+`-turn-ip` 是客户端访问中转用的地址:局域网里填局域网地址,云服务器填公网 IP;不填就没有中转。`-log <文件>` 把日志写到文件而不是标准错误。全部参数见 `copysync-server -h`。
## Client setup / 客户端设置
-On each computer (Mac or Windows), open CopySync → 设置 (Settings) → 信令服务器地址 (Signaling server) and enter:
+On each computer (Mac or Windows), open CopySync → Settings → Signaling server and enter the address the script printed:
-在每台电脑(Mac 或 Windows)上打开 CopySync →「设置」→「信令服务器地址」,填入:
+在每台电脑(Mac 或 Windows)上打开 CopySync →「设置」→「信令服务器地址」,填入脚本打印的地址:
```
ws://<server address>:8787/signal
```
-Behind an HTTPS reverse proxy, use `wss://` and make sure the proxy forwards WebSocket upgrades. 放在 HTTPS 反向代理后面时用 `wss://`,代理需要支持 WebSocket 升级。
+Then check `http://<server address>:8787/healthz` in a browser on another computer; it should show `{"status":"ok",...}`.
-## Uninstall / 卸载
+然后在另一台电脑的浏览器里打开 `http://<服务器地址>:8787/healthz`,应当显示 `{"status":"ok",...}`。
-```bash
-sudo systemctl disable --now copysync-server
-sudo rm /usr/local/bin/copysync-server /etc/systemd/system/copysync-server.service
-sudo rm -r /etc/copysync
-```
+Behind an HTTPS reverse proxy, use `wss://` and make sure the proxy forwards WebSocket upgrades. 放在 HTTPS 反向代理后面时用 `wss://`,代理需要支持 WebSocket 升级。
+
+On a cloud server in mainland China, enter the IP rather than a domain unless the domain has an ICP filing: providers intercept plain HTTP for unfiled domains on any port, and the WebSocket handshake is plain HTTP. 国内云服务器上,域名没有备案时请直接填 IP:云厂商会拦截未备案域名的明文 HTTP 请求,任何端口都一样,而 WebSocket 握手就是明文 HTTP。
diff --git a/server/deploy/install-macos.sh b/server/deploy/install-macos.sh
new file mode 100644
index 0000000..5c4c88a
--- /dev/null
+++ b/server/deploy/install-macos.sh
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# 在 Mac 上安装 copysync-server,登录后自动在后台运行(launchd LaunchAgent),不需要管理员权限。
+# 发布包 copysync-server-macos.tar.gz 里的 install.sh 就是这个文件。
+#
+# ./install.sh 用本机的局域网地址启用 TURN 中转
+# ./install.sh <IP> 指定 TURN 对外公布的地址
+# ./install.sh uninstall 卸载
+#
+# 重复执行即为升级:替换程序并重启,已有设置(含 TURN 密钥)保留;指定了地址时改用新地址。
+
+set -euo pipefail
+cd "$(dirname "$0")"
+
+# 中文系统显示中文,其他显示英文
+LANGS=$(defaults read -g AppleLanguages 2>/dev/null | tr -d ' \n' || true)
+[[ ${LANGS#(\"} == zh* || ${LC_ALL:-${LANG:-}} == zh* ]] && ZH=1 || ZH=
+say() { if [[ $ZH ]]; then echo "$1"; else echo "$2"; fi; }
+
+LABEL=com.copysync.server
+DIR="$HOME/Library/Application Support/CopySync Server"
+BIN="$DIR/copysync-server"
+CONF="$DIR/server.conf"
+PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
+LOG="$HOME/Library/Logs/CopySync/server.log"
+DOMAIN="gui/$(id -u)"
+
+stop() {
+ launchctl bootout "$DOMAIN/$LABEL" 2>/dev/null || true
+ # bootout 是异步的:旧服务没注销干净就 bootstrap 会报 "Bootstrap failed: 5"
+ for _ in {1..20}; do
+ launchctl print "$DOMAIN/$LABEL" &>/dev/null || break
+ sleep 0.25
+ done
+}
+
+if [[ ${1:-} == uninstall ]]; then
+ stop
+ rm -rf "$DIR" "$PLIST"
+ say "✓ 已卸载(日志留在 $LOG)" "✓ Uninstalled (the log is kept at $LOG)"
+ exit 0
+fi
+
+# 本机的局域网地址:默认路由所用网卡的地址。代理软件的 TUN 模式会把默认路由指到
+# utun(198.18.0.0/15),这时改看 Wi‑Fi 与有线网卡。
+lan_ip() {
+ local ifc ip
+ ifc=$(route -n get default 2>/dev/null | awk '/interface:/{print $2}')
+ [[ -n $ifc ]] && ip=$(ipconfig getifaddr "$ifc" 2>/dev/null || true)
+ if [[ -z ${ip:-} || $ip == 198.1[89].* ]]; then
+ ip=
+ for ifc in en0 en1 en2 en3 en4 en5; do
+ ip=$(ipconfig getifaddr "$ifc" 2>/dev/null || true)
+ [[ -n $ip ]] && break
+ done
+ fi
+ echo "$ip"
+}
+
+TURN_IP= TURN_SECRET=
+# shellcheck source=/dev/null
+[[ -f $CONF ]] && source "$CONF"
+if [[ -n ${1:-} ]]; then
+ TURN_IP=$1
+elif [[ -z $TURN_IP ]]; then
+ TURN_IP=$(lan_ip)
+fi
+[[ -n $TURN_IP ]] || {
+ say "找不到本机的局域网地址,请指定:$0 <IP>" "Couldn't find this Mac's LAN address. Specify it: $0 <IP>"
+ exit 1
+}
+# 固定 secret:每次重启都换的话,客户端手里已签发的 TURN 凭证会失效
+[[ -n $TURN_SECRET ]] || TURN_SECRET=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
+
+say "▶ 停止旧版本" "▶ Stopping the running version"
+stop
+
+say "▶ 安装到 $DIR" "▶ Installing to $DIR"
+mkdir -p "$DIR" "$(dirname "$LOG")" "$(dirname "$PLIST")"
+cp copysync-server "$BIN"
+chmod 755 "$BIN"
+# 用浏览器下载的包带隔离属性,Gatekeeper 会拦下没有公证的程序,而 launchd 拉起时没有弹窗可以放行
+xattr -d com.apple.quarantine "$BIN" 2>/dev/null || true
+printf 'TURN_IP=%s\nTURN_SECRET=%s\n' "$TURN_IP" "$TURN_SECRET" > "$CONF"
+chmod 600 "$CONF"
+
+say "▶ 写入 LaunchAgent(中转地址 $TURN_IP)" "▶ Writing the LaunchAgent (relay address $TURN_IP)"
+cat > "$PLIST" <<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>$LABEL</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>$BIN</string>
+ <string>-addr</string> <string>:8787</string>
+ <string>-turn-ip</string> <string>$TURN_IP</string>
+ <string>-turn-secret</string> <string>$TURN_SECRET</string>
+ <string>-stun</string> <string>stun:$TURN_IP:3478,stun:stun.l.google.com:19302</string>
+ <string>-log</string> <string>$LOG</string>
+ </array>
+ <key>RunAtLoad</key> <true/>
+ <key>KeepAlive</key> <true/>
+ <!-- 起不来时(比如端口被占用)不要疯狂重启 -->
+ <key>ThrottleInterval</key> <integer>10</integer>
+ <!-- 参数错误之类在打开日志文件之前的输出 -->
+ <key>StandardErrorPath</key> <string>$LOG</string>
+</dict>
+</plist>
+PLIST
+chmod 600 "$PLIST"
+
+say "▶ 启动" "▶ Starting"
+launchctl bootstrap "$DOMAIN" "$PLIST"
+ok=
+for _ in {1..20}; do
+ curl -fsS --noproxy '*' -m 1 http://127.0.0.1:8787/healthz &>/dev/null && { ok=1; break; }
+ sleep 0.25
+done
+if [[ $ok ]]; then
+ say " ✓ 已启动" " ✓ Running"
+else
+ say " ✗ 启动失败,查看日志:tail -n 50 \"$LOG\"" " ✗ Failed to start. See the log: tail -n 50 \"$LOG\""
+ exit 1
+fi
+
+VERSION=$("$BIN" -version)
+if [[ $ZH ]]; then
+ cat <<EOF
+
+安装完成:$VERSION,登录这台 Mac 后自动运行
+在每台电脑的 CopySync「设置 → 信令服务器地址」填:
+
+ ws://$TURN_IP:8787/signal
+
+ 日志 $LOG
+ 重启 launchctl kickstart -k $DOMAIN/$LABEL
+ 卸载 $0 uninstall
+EOF
+else
+ cat <<EOF
+
+Installed: $VERSION. It starts whenever you log in to this Mac.
+In CopySync on each computer, set Settings → Signaling server to:
+
+ ws://$TURN_IP:8787/signal
+
+ Logs $LOG
+ Restart launchctl kickstart -k $DOMAIN/$LABEL
+ Uninstall $0 uninstall
+EOF
+fi
+
+# 系统防火墙开着时,没有放行的程序收不到其他电脑的连接
+FW=/usr/libexec/ApplicationFirewall/socketfilterfw
+if [[ -x $FW ]] && "$FW" --getglobalstate 2>/dev/null | grep -q "enabled"; then
+ echo
+ say "系统防火墙已开启,放行 copysync-server(需要输入密码):" \
+ "The macOS firewall is on. Allow copysync-server through it (asks for your password):"
+ echo " sudo $FW --add \"$BIN\" && sudo $FW --unblockapp \"$BIN\""
+fi
diff --git a/server/deploy/install.cmd b/server/deploy/install.cmd
new file mode 100644
index 0000000..7cb91ee
--- /dev/null
+++ b/server/deploy/install.cmd
@@ -0,0 +1,5 @@
+@echo off
+rem Double-click to install copysync-server as a Windows service (asks for administrator rights).
+rem To set the relay address yourself: install.cmd 192.168.1.20
+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install.ps1" %*
+if errorlevel 1 pause
diff --git a/server/deploy/install.ps1 b/server/deploy/install.ps1
new file mode 100644
index 0000000..51d0946
--- /dev/null
+++ b/server/deploy/install.ps1
@@ -0,0 +1,182 @@
+<#
+在 Windows 上安装 copysync-server:注册为开机自启的系统服务,并在 Windows 防火墙里放行。
+
+ 双击 install.cmd 用本机的局域网地址启用 TURN 中转
+ install.cmd 192.168.1.20 指定 TURN 对外公布的地址
+ 双击 uninstall.cmd 卸载
+
+重复执行即为升级:替换程序并重启服务,已有设置(含 TURN 密钥)保留;指定了地址时改用新地址。
+需要管理员权限,不是管理员时会弹出 UAC 确认,在新窗口里继续。
+
+这个文件必须保存为带 BOM 的 UTF-8:Windows PowerShell 5.1 把不带 BOM 的脚本当作系统代码页读取,中文会乱码。
+控制台按系统代码页输出,所以只用 GBK 与 CP437 里都有的符号(√、!),其他对勾、箭头会变成问号。
+#>
+param(
+ [string]$Ip = "",
+ [switch]$Uninstall
+)
+
+$ErrorActionPreference = 'Stop'
+
+# 中文系统显示中文,其他显示英文
+$zh = (Get-UICulture).Name -like 'zh*'
+function Say([string]$zhText, [string]$enText) { if ($zh) { $zhText } else { $enText } }
+function Step([string]$zhText, [string]$enText) { Write-Host ('> ' + (Say $zhText $enText)) }
+
+$admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
+ [Security.Principal.WindowsBuiltInRole]::Administrator)
+if (-not $admin) {
+ # 以管理员身份在新窗口里重新运行;-NoExit 让窗口留着,看得到结果
+ $argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-NoExit', '-File', "`"$PSCommandPath`"")
+ if ($Ip) { $argList += @('-Ip', $Ip) }
+ if ($Uninstall) { $argList += '-Uninstall' }
+ try {
+ Start-Process powershell.exe -Verb RunAs -ArgumentList $argList
+ } catch {
+ Write-Host (Say '需要管理员权限才能注册服务、设置防火墙。' 'Administrator rights are needed to register the service and configure the firewall.')
+ exit 1
+ }
+ exit 0
+}
+
+$Name = 'CopySyncServer'
+$Display = 'CopySync Server'
+$InstallDir = Join-Path $env:ProgramFiles 'CopySync Server'
+$DataDir = Join-Path $env:ProgramData 'CopySync Server'
+$Exe = Join-Path $InstallDir 'copysync-server.exe'
+$Conf = Join-Path $DataDir 'server.conf'
+$Log = Join-Path $DataDir 'server.log'
+
+function Stop-Server {
+ if (Get-Service $Name -ErrorAction SilentlyContinue) {
+ Stop-Service $Name -Force -ErrorAction SilentlyContinue
+ }
+ # 服务停了进程不一定立刻退出,退出前替换不了程序文件
+ for ($i = 0; $i -lt 20 -and (Get-Process copysync-server -ErrorAction SilentlyContinue); $i++) {
+ Start-Sleep -Milliseconds 250
+ }
+}
+
+if ($Uninstall) {
+ Stop-Server
+ if (Get-Service $Name -ErrorAction SilentlyContinue) { sc.exe delete $Name | Out-Null }
+ Get-NetFirewallRule -DisplayName $Display -ErrorAction SilentlyContinue | Remove-NetFirewallRule
+ Remove-Item $InstallDir, $DataDir -Recurse -Force -ErrorAction SilentlyContinue
+ Write-Host (Say '√ 已卸载' '√ Uninstalled')
+ exit 0
+}
+
+# 本机的局域网地址:默认路由所用网卡的地址,按跃点数取最优先的一个。
+# 跳过代理软件 TUN 模式常用的 198.18.0.0/15 与链路本地地址。
+function Get-LanIp {
+ $routes = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue |
+ Sort-Object { $_.RouteMetric + (Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }
+ foreach ($r in $routes) {
+ foreach ($a in Get-NetIPAddress -InterfaceIndex $r.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue) {
+ if ($a.IPAddress -notmatch '^(169\.254\.|198\.1[89]\.|127\.)') { return $a.IPAddress }
+ }
+ }
+}
+
+$src = Join-Path $PSScriptRoot 'copysync-server.exe'
+if (-not (Test-Path $src)) {
+ throw (Say "找不到 $src,请把压缩包完整解压后再运行" "$src not found. Extract the whole zip first.")
+}
+
+# 读取已有设置
+$cfg = @{}
+if (Test-Path $Conf) {
+ foreach ($line in Get-Content $Conf) {
+ if ($line -match '^(\w+)=(.*)$') { $cfg[$Matches[1]] = $Matches[2] }
+ }
+}
+if ($Ip) { $cfg.TURN_IP = $Ip } elseif (-not $cfg.TURN_IP) { $cfg.TURN_IP = Get-LanIp }
+if (-not $cfg.TURN_IP) {
+ throw (Say '找不到本机的局域网地址,请指定:install.cmd <IP>' "Couldn't find this PC's LAN address. Specify it: install.cmd <IP>")
+}
+if (-not $cfg.TURN_SECRET) {
+ # 固定 secret:每次重启都换的话,客户端手里已签发的 TURN 凭证会失效
+ $bytes = New-Object byte[] 32
+ [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
+ $cfg.TURN_SECRET = -join ($bytes | ForEach-Object { $_.ToString('x2') })
+}
+$turnIp = $cfg.TURN_IP
+
+Step '停止旧版本' 'Stopping the running version'
+Stop-Server
+
+Step "安装到 $InstallDir" "Installing to $InstallDir"
+New-Item -ItemType Directory -Force $InstallDir, $DataDir | Out-Null
+Copy-Item $src $Exe -Force
+Unblock-File $Exe
+# 服务以低权限的 LOCAL SERVICE 账户运行,只给它写日志的权限
+icacls $DataDir /grant '*S-1-5-19:(OI)(CI)M' | Out-Null
+Set-Content $Conf -Encoding ASCII -Value @("TURN_IP=$turnIp", "TURN_SECRET=$($cfg.TURN_SECRET)")
+# 设置里有 TURN 密钥,只留给管理员与系统
+icacls $Conf /inheritance:r /grant:r '*S-1-5-32-544:F' '*S-1-5-18:F' | Out-Null
+
+Step "注册服务 $Name(中转地址 $turnIp)" "Registering the service $Name (relay address $turnIp)"
+$bin = "`"$Exe`" -addr :8787 -turn-ip $turnIp -turn-secret $($cfg.TURN_SECRET) " +
+ "-stun stun:${turnIp}:3478,stun:stun.l.google.com:19302 -log `"$Log`""
+$desc = Say 'CopySync 的信令与 TURN 中转服务器' 'Signaling and TURN relay server for CopySync'
+$existing = Get-CimInstance Win32_Service -Filter "Name='$Name'"
+if ($existing) {
+ $r = $existing | Invoke-CimMethod -MethodName Change -Arguments @{ PathName = $bin; StartMode = 'Automatic' }
+ if ($r.ReturnValue -ne 0) { throw "Win32_Service.Change: $($r.ReturnValue)" }
+} else {
+ $cred = New-Object Management.Automation.PSCredential('NT AUTHORITY\LocalService', (New-Object Security.SecureString))
+ New-Service -Name $Name -BinaryPathName $bin -DisplayName $Display -Description $desc `
+ -StartupType Automatic -Credential $cred | Out-Null
+}
+# 意外退出(包括端口被占用)后自动重启:5 秒、5 秒、30 秒,一天后重新计数
+sc.exe failure $Name reset= 86400 actions= restart/5000/restart/5000/restart/30000 | Out-Null
+sc.exe failureflag $Name 1 | Out-Null
+
+Step '在 Windows 防火墙里放行' 'Allowing it through Windows Firewall'
+Get-NetFirewallRule -DisplayName $Display -ErrorAction SilentlyContinue | Remove-NetFirewallRule
+# 按程序放行:信令、STUN/TURN 与系统随机分配的中转端口都覆盖到,不用逐个开端口
+New-NetFirewallRule -DisplayName $Display -Description $desc -Direction Inbound -Program $Exe `
+ -Action Allow -Profile Any | Out-Null
+
+Step '启动' 'Starting'
+Start-Service $Name
+$ok = $false
+$web = New-Object Net.WebClient
+$web.Proxy = $null
+for ($i = 0; $i -lt 20 -and -not $ok; $i++) {
+ try { $null = $web.DownloadString('http://127.0.0.1:8787/healthz'); $ok = $true } catch { Start-Sleep -Milliseconds 250 }
+}
+if (-not $ok) {
+ Write-Host (Say " ! 启动失败,查看日志:$Log" " ! Failed to start. See the log: $Log")
+ exit 1
+}
+Write-Host (Say ' √ 已启动' ' √ Running')
+
+$version = & $Exe -version
+if ($zh) {
+ Write-Host @"
+
+安装完成:$version,作为 Windows 服务开机自动运行
+在每台电脑的 CopySync「设置 → 信令服务器地址」填:
+
+ ws://${turnIp}:8787/signal
+
+ 程序 $InstallDir
+ 日志 $Log
+ 重启 Restart-Service $Name(管理员 PowerShell)
+ 卸载 双击 uninstall.cmd
+"@
+} else {
+ Write-Host @"
+
+Installed: $version. It runs as a Windows service and starts with Windows.
+In CopySync on each computer, set Settings > Signaling server to:
+
+ ws://${turnIp}:8787/signal
+
+ Program $InstallDir
+ Logs $Log
+ Restart Restart-Service $Name (in an administrator PowerShell)
+ Uninstall double-click uninstall.cmd
+"@
+}
diff --git a/server/deploy/install.sh b/server/deploy/install.sh
index b0ad927..db002ee 100755
--- a/server/deploy/install.sh
+++ b/server/deploy/install.sh
@@ -1,68 +1,127 @@
#!/usr/bin/env bash
-# 在 Linux 服务器上安装 copysync-server 并注册为 systemd 服务。
+# 在 Linux 上安装 copysync-server 并注册为开机自启的 systemd 服务。
#
-# sudo ./install.sh 仅信令 + STUN(同一局域网够用)
-# sudo ./install.sh <公网IP> 同时启用 TURN 中转(跨公网、对称 NAT 时需要)
+# sudo ./install.sh 用本机的局域网地址启用 TURN 中转(局域网部署)
+# sudo ./install.sh <公网IP> 用公网 IP 启用 TURN 中转(云服务器,跨公网使用)
+# sudo ./install.sh uninstall 卸载
#
# 重复执行即为升级:替换二进制并重启,已有的 /etc/copysync/server.env 不会被覆盖。
set -euo pipefail
cd "$(dirname "$0")"
-[[ $EUID -eq 0 ]] || { echo "请用 root 运行:sudo $0 $*"; exit 1; }
+# 中文系统显示中文,其他显示英文
+[[ ${LC_ALL:-${LC_MESSAGES:-${LANG:-}}} == zh* ]] && ZH=1 || ZH=
+say() { if [[ $ZH ]]; then echo "$1"; else echo "$2"; fi; }
+
+[[ $EUID -eq 0 ]] || { say "请用 root 运行:sudo $0 $*" "Run as root: sudo $0 $*"; exit 1; }
-TURN_IP=${1:-}
ENV_FILE=/etc/copysync/server.env
-echo "▶ 安装二进制到 /usr/local/bin"
+if [[ ${1:-} == uninstall ]]; then
+ systemctl disable --now copysync-server 2>/dev/null || true
+ rm -f /usr/local/bin/copysync-server /etc/systemd/system/copysync-server.service
+ rm -rf /etc/copysync
+ systemctl daemon-reload
+ say "✓ 已卸载" "✓ Uninstalled"
+ exit 0
+fi
+
+# 本机的局域网地址:默认路由所用网卡的地址。代理软件的 TUN 模式会把默认路由指到
+# 198.18.0.0/15,这时改用其他网卡上的地址;Docker 的网桥也跳过。
+lan_ip() {
+ local ip
+ ip=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -n1)
+ if [[ -z $ip || $ip == 198.1[89].* ]]; then
+ ip=$(ip -4 -o addr show scope global 2>/dev/null | awk '{print $4}' | cut -d/ -f1 |
+ grep -Ev '^(198\.1[89]\.|172\.17\.)' | head -n1)
+ fi
+ echo "$ip"
+}
+
+say "▶ 安装二进制到 /usr/local/bin" "▶ Installing the binary to /usr/local/bin"
install -m 755 copysync-server /usr/local/bin/copysync-server
-echo "▶ 写入 systemd 单元"
+say "▶ 写入 systemd 单元" "▶ Writing the systemd unit"
install -m 644 copysync-server.service /etc/systemd/system/copysync-server.service
if [[ -f $ENV_FILE ]]; then
- echo "▶ 保留已有配置 $ENV_FILE"
+ say "▶ 保留已有配置 $ENV_FILE" "▶ Keeping the existing config $ENV_FILE"
+ TURN_IP=$(sed -n 's/.*-turn-ip \([^ "]*\).*/\1/p' "$ENV_FILE")
+ if [[ -n ${1:-} && ${1:-} != "$TURN_IP" ]]; then
+ say " 要改用 $1,编辑 $ENV_FILE 里的 -turn-ip 后执行 systemctl restart copysync-server" \
+ " To switch to $1, edit -turn-ip in $ENV_FILE and run systemctl restart copysync-server"
+ fi
else
- echo "▶ 生成配置 $ENV_FILE"
+ TURN_IP=${1:-$(lan_ip)}
+ [[ -n $TURN_IP ]] || {
+ say "找不到本机的局域网地址,请指定:sudo $0 <IP>" "Couldn't find this machine's LAN address. Specify it: sudo $0 <IP>"
+ exit 1
+ }
+ say "▶ 生成配置 $ENV_FILE(中转地址 $TURN_IP)" "▶ Writing $ENV_FILE (relay address $TURN_IP)"
mkdir -p /etc/copysync
- if [[ -n $TURN_IP ]]; then
- # 固定 secret:自动生成的话每次重启都会让已签发的 TURN 凭证失效
- # STUN 优先用自己:国内网络访问公共 STUN(如 Google 的)时通时断
- OPTIONS="-addr :8787 -turn-ip $TURN_IP -turn-secret $(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
- OPTIONS="$OPTIONS -stun stun:$TURN_IP:3478,stun:stun.l.google.com:19302"
- else
- OPTIONS="-addr :8787"
- fi
+ # 固定 secret:自动生成的话每次重启都会让已签发的 TURN 凭证失效
+ # STUN 优先用自己:国内网络访问公共 STUN(如 Google 的)时通时断
+ OPTIONS="-addr :8787 -turn-ip $TURN_IP -turn-secret $(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
+ OPTIONS="$OPTIONS -stun stun:$TURN_IP:3478,stun:stun.l.google.com:19302"
printf 'OPTIONS="%s"\n' "$OPTIONS" > "$ENV_FILE"
chmod 600 "$ENV_FILE"
fi
-echo "▶ 启动"
+say "▶ 启动" "▶ Starting"
systemctl daemon-reload
-systemctl enable copysync-server >/dev/null
+systemctl enable copysync-server >/dev/null 2>&1
systemctl restart copysync-server
sleep 1
if systemctl is-active --quiet copysync-server; then
- echo " ✓ 已启动"
+ say " ✓ 已启动" " ✓ Running"
else
- echo " ✗ 启动失败,查看日志:journalctl -u copysync-server -n 50"
+ say " ✗ 启动失败,查看日志:journalctl -u copysync-server -n 50" \
+ " ✗ Failed to start. See the log: journalctl -u copysync-server -n 50"
exit 1
fi
-cat <<EOF
+ADDR=${TURN_IP:-$(lan_ip)}
+PORTS=$(tr '\t' '-' < /proc/sys/net/ipv4/ip_local_port_range 2>/dev/null || echo 32768-60999)
+VERSION=$(/usr/local/bin/copysync-server -version)
+if [[ $ZH ]]; then
+ cat <<EOF
-安装完成:$(/usr/local/bin/copysync-server -version)
-客户端「设置 → 信令服务器地址」填:ws://${TURN_IP:-<本机地址>}:8787/signal
+安装完成:$VERSION
+在每台电脑的 CopySync「设置 → 信令服务器地址」填:
+
+ ws://$ADDR:8787/signal
配置 $ENV_FILE
日志 journalctl -u copysync-server -f
重启 systemctl restart copysync-server
- 卸载 systemctl disable --now copysync-server && rm /usr/local/bin/copysync-server /etc/systemd/system/copysync-server.service
+ 卸载 sudo $0 uninstall
-防火墙 / 云安全组需放行:
- TCP 8787 信令(WebSocket)
- UDP 3478 TURN(仅启用中转时)
- UDP 32768-60999 TURN 中转分配的端口(仅启用中转时;由系统随机分配,
- 实际范围见 /proc/sys/net/ipv4/ip_local_port_range)
+防火墙需放行:TCP 8787(信令)、UDP 3478(STUN 与 TURN)、UDP $PORTS(中转端口,系统随机分配)
EOF
+else
+ cat <<EOF
+
+Installed: $VERSION
+In CopySync on each computer, set Settings → Signaling server to:
+
+ ws://$ADDR:8787/signal
+
+ Config $ENV_FILE
+ Logs journalctl -u copysync-server -f
+ Restart systemctl restart copysync-server
+ Uninstall sudo $0 uninstall
+
+Open in your firewall: TCP 8787 (signaling), UDP 3478 (STUN and TURN), UDP $PORTS (relay ports, assigned by the OS)
+EOF
+fi
+
+# 开着的防火墙直接给出放行命令
+if command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q "Status: active"; then
+ say "ufw 已启用,放行命令:" "ufw is active. To open the ports:"
+ echo " sudo ufw allow 8787/tcp && sudo ufw allow 3478/udp && sudo ufw allow ${PORTS/-/:}/udp"
+elif command -v firewall-cmd >/dev/null && firewall-cmd --state &>/dev/null; then
+ say "firewalld 已启用,放行命令:" "firewalld is running. To open the ports:"
+ echo " sudo firewall-cmd --permanent --add-port=8787/tcp --add-port=3478/udp --add-port=$PORTS/udp && sudo firewall-cmd --reload"
+fi
diff --git a/server/deploy/uninstall.cmd b/server/deploy/uninstall.cmd
new file mode 100644
index 0000000..d33c999
--- /dev/null
+++ b/server/deploy/uninstall.cmd
@@ -0,0 +1,4 @@
+@echo off
+rem Double-click to remove the copysync-server service, its firewall rule and its files.
+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install.ps1" -Uninstall
+if errorlevel 1 pause
diff --git a/server/go.mod b/server/go.mod
index 1260894..d74f3a2 100644
--- a/server/go.mod
+++ b/server/go.mod
@@ -8,6 +8,7 @@ require (
github.com/baiyuze/copysync/proto v0.0.0-00010101000000-000000000000
github.com/coder/websocket v1.8.15
github.com/pion/turn/v4 v4.1.4
+ golang.org/x/sys v0.47.0
google.golang.org/protobuf v1.36.12
)
@@ -21,7 +22,6 @@ require (
github.com/wlynxg/anet v0.0.5 // indirect
golang.org/x/crypto v0.54.0 // indirect
golang.org/x/net v0.57.0 // indirect
- golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.40.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect
google.golang.org/grpc v1.84.0 // indirect