Skip to content
English下载

控制接口 ​

不是 REST 接口

虽然本页地址里有 restful,Core 并没有 HTTP 或 REST 接口:没有 /api/v1 路由,没有密钥,也没有 OpenAPI 文件。 控制接口是 MessagePack-RPC。

桌面应用做的每件事都经过 Core 的控制接口:切换 Profile、选择代理组成员、查看连接和日志、编辑节点和规则。 脚本和其他客户端使用和应用相同的协议。

接口定义就是源码树里的 api/*.toml,每个服务一个文件,按线上顺序列出了每个方法和每个字段。本页说明如何连接、 如何读懂这些文件。

传输方式 ​

传输地址何时打开谁能连接
命名管道(Windows)\\.\pipe\specola始终见 CLI
Unix socket(macOS、Linux)/tmp/specola.sock始终启动 Core 的用户(权限 0600)
TCP[general].api-listenProfile 设置了它时回环和私有网络的客户端
TCP,路由器模式LAN 地址的 9090 端口带 --gateway 时,在加载 Profile 之前回环和私有网络的客户端
  • --ipc-endpoint 可以改变本地端点。
  • TCP 监听使用同一套协议,不是 HTTP。它可以绑定任意地址,但只服务回环、10.0.0.0/8、172.16.0.0/12、 192.168.0.0/16、100.64.0.0/10、169.254.0.0/16、fc00::/7 和 fe80::/10;其他客户端一连上就被断开。
  • 所有传输方式都没有认证,也没有加密。
  • license.* 和 core.shutdown 只能走本地端点,通过 TCP 调用返回 -32003。
  • 每个监听同一时间最多接受 8 个连接。
  • 修改 api-listen 后重新激活 Profile,TCP 监听就会迁移,Core 不需要重启。

线上格式 ​

标准的 MessagePack-RPC,外加服务端流。 每条消息是一个 MessagePack 数组,消息之间直接相连,没有长度前缀:MessagePack 的值本身就能界定边界。

request       [0, msgid, method, [req]]        可选的第 5 个元素:{0: timeout_us, 1: window}
response      [1, msgid, error, result]        error = nil | [code, message]
notification  [2, method, [req]]
stream item   [3, msgid, item]                 服务端 -> 客户端,在最终响应之前
cancel        [4, msgid]                       客户端 -> 服务端
credit        [5, msgid, n]                    客户端 -> 服务端:还能再收 n 条
goaway        [6, last_msgid, reason]          服务端 -> 客户端:Core 正在退出
  • msgid 是客户端自选的 32 位无符号整数,在它尚未结束的请求中必须唯一。
  • 每个方法只接受一个结构体、只返回一个结构体,所以参数数组永远只有一个元素:[req]。
  • method 是线上名称,例如 proxy.selectGroupMember。api/*.toml 里的 aliases 是应用内部桥接用的名字, 不是线上名称。

结构体是按位置排列的数组 ​

结构体在线上是按声明顺序排列的字段数组,不是 map,不传字段名。

定义里的类型线上表示
结构体按 api/*.toml 中的顺序排列全部字段的数组;空结构体 Empty 是 []
T?(可选)值本身,或 nil
T[]数组
map<K, V>map
枚举值的下标:RouteMode = ["direct", "rule", "global"],所以 rule 是 1
variant[case id, value]
string、bool、整数、f64对应的 MessagePack 类型

请求必须带齐每个字段。定义里的 default 只是生成的客户端代码的初始值,线上不会替你补齐。增加、删除或调整字段顺序 都会破坏契约,所以握手时要比对整个定义的哈希。

例如 api/proxy.toml 声明了

toml
[[struct]]
name = "ProxyDelayReq"
fields = [
  { id = 0, name = "proxy_id",       type = "string" },
  { id = 1, name = "protocol",       type = "string", default = "tcp" },
  { id = 2, name = "url",            type = "string" },
  { id = 3, name = "timeout_ms",     type = "u32", default = 5000 },
  { id = 4, name = "expected_status", type = "string", default = "200-399" },
]

所以一次延迟测试的请求是 [0, 7, "proxy.testDelay", [["office", "tcp", "", 5000, "200-399"]]]。

限制 ​

  • 超过 4 MiB 的消息会导致连接被关闭。
  • 每个连接最多同时有 32 个未完成的请求,再多返回 -32012。
  • TCP 连接启用了 keepalive,对端消失约 90 秒后连接被丢弃。

握手 ​

每个连接上第一个调用 sys.hello:

HelloReq  [contract_version, client_name, contract_hash, min_supported_version]
HelloResp [contract_version, server_name, contract_hash, min_supported_version]
  • contract_version 和 min_supported_version 取自 api/rpcgen.toml(目前都是 3)。

  • contract_hash 是整个定义的 64 位哈希,和 Core 自己的不一致时返回 -32600。用与你的 Core 同一份源码树里的 api 目录计算:

    bash
    python3 -c "import sys; sys.path.insert(0, 'tool/rpcgen'); from pathlib import Path; \
    from schema import load; print(hex(load([Path('api')]).hash))"

    api/api.lock 记录的是上一个正式版的契约,其中的 hash 只和那个版本构建的 Core 一致。

  • 不调用 sys.hello 时 Core 也不会拒绝后续调用,但按另一份定义构建的客户端会读错每个结构体。请务必先握手。

应用随后会调用 profile.setDirectory,传入用户的 Profiles 目录。不调用它的客户端使用 Core 自己的 Profiles 目录 (Windows 服务没有这个目录)。

流 ​

流是这样一种请求:先返回任意条 [3, msgid, item],最后用一条普通响应结束(nil 或错误)。 同一个连接上,流和普通调用可以交错进行。

  • 快照。 watch* 方法立即发送一份完整快照,之后发送更新的快照;每条都不是增量。
  • 流量控制。 请求可以带窗口(元数据键 1):Core 最多发送这么多条,直到客户端用 [5, msgid, n] 追加额度。不带窗口时流不受限制,socket 写满时 Core 会等待。
  • 取消。 [4, msgid] 结束一个流,或放弃一个调用。
  • 截止时间。 timeout_us(元数据键 0)到期后,Core 自己返回 -32010。
  • 退出。 Core 退出时发送 GOAWAY:进行中的调用会完成,流以 -32013 结束,新请求被拒绝,连接最迟 3 秒后关闭。

可用时机 ​

何时可用方法
监听一打开sys.*、core.*、profile.*、license.*、overview.*、ssh.*、gateway.*
Profile 解析完成后general.getConfig
Core 运行起一个 Profile 后其余全部

过早调用返回 -32002。core.watchStartup 会报告启动进度,直到 Core 就绪。激活 Profile 期间,除 sys.hello 外的所有请求都返回 -32006,业务流也会结束;请在激活的最后一条消息之后重新打开。

错误码 ​

错误码含义
-32600协议错误:消息格式不对,或 sys.hello 里的契约不同
-32601未知方法
-32602参数无效:结构体形状不对,或 Core 拒绝该值
-32603内部错误
-32002Core 还没准备好执行这个方法
-32003禁止:通过 TCP 调用 license.* 或 core.shutdown、客户端不在私有网络,或缺少许可证
-32004未找到
-32005冲突,例如 expected_revision 已过期
-32006忙:正在激活 Profile
-32007不可用,例如 DNS 解析器没有运行
-32010超过截止时间
-32011已取消
-32012过载:未完成的请求太多,或流的消费者跟不上
-32013Core 正在退出

最小客户端 ​

任何 MessagePack 库都可以。下面这段 Python 示意代码(pip install msgpack)连接、握手、读取健康状态、 做一次延迟测试,并跟踪一次 Profile 激活:

python
import socket, msgpack

CONTRACT_HASH = 0x0           # 填入“握手”一节命令打印的值

sock = socket.socket(socket.AF_UNIX)          # Linux、macOS
sock.connect("/tmp/specola.sock")
# TCP:sock = socket.create_connection(("192.168.1.2", 9090))
# Windows:sock = open(r"\\.\pipe\specola", "r+b", buffering=0),下面改用 write()/read()
unpacker = msgpack.Unpacker()
last_id = 0

def messages():
    while True:
        for message in unpacker:
            yield message
        data = sock.recv(65536)
        if not data:
            raise ConnectionError("Core closed the connection")
        unpacker.feed(data)

def call(method, req):
    """普通调用,返回结果结构体(列表)。"""
    global last_id
    last_id += 1
    sock.sendall(msgpack.packb([0, last_id, method, [req]]))
    for kind, msgid, *rest in messages():
        if kind == 1 and msgid == last_id:
            error, result = rest
            if error is not None:
                raise RuntimeError(error)       # [code, message]
            return result

def stream(method, req):
    """流,逐条产出,直到 Core 结束这个流。"""
    global last_id
    last_id += 1
    sock.sendall(msgpack.packb([0, last_id, method, [req]]))
    for kind, msgid, *rest in messages():
        if msgid != last_id:
            continue
        if kind == 3:
            yield rest[0]
        elif kind == 1:
            if rest[0] is not None:
                raise RuntimeError(rest[0])
            return

print(call("sys.hello", [3, "my-script", CONTRACT_HASH, 3]))
ok, ready, state, message = call("core.getHealth", [])
proxy_id, ok, delay_ms, observed_at_ms, message = call(
    "proxy.testDelay", ["office", "tcp", "", 5000, "200-399"])
call("routing.setMode", [1, None])             # RouteMode 下标 1 = rule

# ActivateProfileReq [name, refresh_geo];每条是 ProfileActivationEvent
# [name, stage, message, terminal, succeeded, previous_profile_retained]
for event in stream("profile.activateProfile", ["home", False]):
    print(event[2])
    if event[3]:
        print("succeeded" if event[4] else "failed")

源码树里还有生成器 tool/rpcgen,可以根据 api/*.toml 生成带类型的 C++、C# 和 Swift 客户端 (python3 tool/rpcgen/rpcgen.py --api-dir api --lang csharp --out-dir out);C++ 运行时是 common/include/rpc 里的纯头文件库。

方法 ​

未标注的是普通调用,标 流 的是流。每个方法的请求和结果结构体都在对应的 api/*.toml 文件里。

sys(sys.toml) ​

方法作用
sys.hello契约握手,第一个调用
sys.ping返回服务端时间

core(core.toml) ​

方法作用
core.getHealthCore 是否就绪及其状态
core.getVersionCore 版本、平台、操作系统和总内存
core.getMemoryCore 的内存占用
core.probeHost不经代理测量本机公网 IP、所在位置和 UDP NAT 类型(工具)
core.locateHosts不经代理查询最多 64 个主机的 GeoIP 位置
core.shutdown停止 Core;只能走本地端点
core.checkUpdate立即检查新版本
core.startUpdate下载并校验更新包
core.cancelUpdate取消下载
core.installUpdate启动已校验的安装包,然后停止 Core
core.watchStartup 流启动进度,直到 Core 就绪
core.watchUpdate 流是否有更新、下载进度和安装状态
core.watchLogs 流某个序号之后的缓冲日志,然后是新日志

general(general.toml) ​

方法作用
general.getConfig已加载 Profile 的路由模式、日志级别、api-listen、端口和协议
general.getProfileSettings应用设置页显示的 Profile 值
general.updateProfileSettings把给定的值写入当前 Profile 文件并重新激活

profile(profile.toml) ​

方法作用
profile.setDirectory绑定调用者的 Profiles 目录,连接后调用一次
profile.getProfiles列出 Profile
profile.importProfile把一个 Profile 文件复制到 Profiles 目录
profile.createProfile新建 Profile,不激活
profile.renameProfile重命名 Profile
profile.removeProfile删除 Profile
profile.activateProfile 流加载或重新应用 Profile;每条报告一个阶段,最后一条说明是否成功
profile.createModule新建空模块文件
profile.deleteModule移走模块文件,并从所有 Profile 的列表中去掉
profile.setProfileModules按顺序设置 Profile 使用的模块
profile.watchProfiles 流有定义但没有服务:返回 -32601
profile.createSubscriptionProfile有定义但没有服务:返回 -32601
profile.updateSubscriptionProfile有定义但没有服务:返回 -32601
profile.refreshSubscriptionProfile有定义但没有服务:返回 -32601

routing(routing.toml) ​

方法作用
routing.getState路由模式、global 目标和监听状态
routing.setMode切换正在运行的 Core 的路由模式,不修改文件
routing.setEnhanced打开或关闭增强模式:带着这项改动重新应用 Profile
routing.setSshForward打开或关闭 SSH 端口转发,见工具
routing.watchState 流立即发送路由状态,之后每次变化都发送

proxy(proxy.toml) ​

方法作用
proxy.listProxies全部节点,含类型、地址和健康状态
proxy.listProxyGroups全部代理组,含成员和当前选择
proxy.getProxy单个节点
proxy.getProxyGroup单个代理组
proxy.getCatalog节点和代理组的一份快照
proxy.watchCatalog 流立即发送目录,之后每次变化都发送
proxy.selectGlobal切换到 global 模式,经指定节点或代理组
proxy.selectGroupMember选择 select 代理组的成员
proxy.testDelay经节点发送一次 HTTP 请求并计时(工具)
proxy.runNatTest经节点的 UDP 通道做 STUN 测试(工具)
proxy.getSource节点在 Profile 文件里的原文
proxy.save校验节点、写入 Profile 文件并应用
proxy.delete从文件中删除节点;仍被代理组或规则使用时拒绝
proxy.saveGroup把代理组写入文件并应用
proxy.deleteGroup删除代理组;仍被规则或代理组使用时拒绝
proxy.reorder按新顺序重写 [[proxy]] 表
proxy.reorderGroups按新顺序重写 [[proxy-group]] 表

rules(rules.toml) ​

方法作用
rules.list已加载 Profile 及其模块的规则
rules.replace校验规则列表、写入 Profile 文件并应用
rules.getFile某个 Profile 或模块文件的 route.rules
rules.replaceFile写入某个 Profile 或模块文件的 route.rules
rules.getProvider分页读取规则集的条目
rules.replaceProvider替换内联规则集的条目
rules.setProviderSource修改远程规则集的 URL
rules.listGeogeosite.dat 或 geoip.dat 的分类
rules.getGeo某个 geo 分类的条目
rules.match不做 DNS、不看进程,测试目标会命中哪条规则

dns(dns.toml) ​

方法作用
dns.getDnsSnapshotDNS 缓存
dns.watchDnsCache 流立即发送缓存,变化后再发送
dns.queryDns用 Core 的解析器解析域名(A 或 AAAA)
dns.lookupDns按被接管的查询那样解析域名,并说明由哪条规则、哪个上游、哪个节点应答
dns.getDnsConfig当前生效的 DNS 设置
dns.flushDnsCache清空 DNS 缓存
dns.flushFakeIpCache清除 Fake-IP 映射

connections(connections.toml) ​

方法作用
connections.listConnections当前连接,含进程、规则和节点
connections.watchConnections 流分批发送连接变化
connections.closeConnection关闭一个连接
connections.closeAllConnections关闭全部连接

telemetry 和 overview(telemetry.toml、overview.toml) ​

方法作用
telemetry.getTraffic流量计数和速率
telemetry.getProxyState路由模式、当前选择和监听状态
telemetry.watchTraffic 流每 interval_ms 一个流量样本
telemetry.watchProxyState 流立即发送代理状态,变化时再发送
overview.getOverview应用概览页的数据
overview.watchOverview 流立即发送概览,变化时再发送

system_proxy(system_proxy.toml) ​

方法作用
system_proxy.startLocalProxy打开 [general] 里的本地端口
system_proxy.stopLocalProxy关闭它;重新激活后仍保持关闭
system_proxy.getListeners本地端口和 DNS 监听及其地址
system_proxy.getState有定义但没有服务:返回 -32601
system_proxy.watchState 流有定义但没有服务:返回 -32601
system_proxy.setEnabled有定义但没有服务:返回 -32601

这些方法都不会修改操作系统的代理设置。

ssh(ssh.toml) ​

方法作用
ssh.probe在服务器上运行只读的检查命令(工具)
ssh.watchServer 流保持一个到服务器的会话并采样负载
ssh.scanHostKey不登录,只读取服务器的主机密钥
ssh.listConfigHostsCore 所在机器 ssh config 里的 Host 别名
ssh.listFiles通过 SFTP 列目录
ssh.makeDirectory创建目录
ssh.removeFile删除文件或目录
ssh.moveFile重命名或移动文件
ssh.readFile读取文件,每次最多 1 MiB
ssh.writeFile分块上传文件,每块最多 1 MiB
ssh.closeFiles关闭为该服务器保留的 SFTP 会话

license 和 gateway(license.toml、gateway.toml) ​

方法作用
license.getStatus许可证状态;和所有 license.* 方法一样只能走本地端点
license.activateOnline用激活码在线激活
license.activateOffline用为本机签发的令牌离线激活
license.refresh向服务器刷新许可证
license.deactivate释放本机的激活
gateway.getDevices路由器模式下看到的局域网设备

标注“有定义但没有服务”的方法写在接口定义里,但这个 Core 中没有服务响应它们。